public static @Nullable PsiType getContextType(@NotNull PsiPattern pattern) {
    PsiElement parent = pattern.getParent();
    if (parent instanceof PsiInstanceOfExpression) {
      return ((PsiInstanceOfExpression)parent).getOperand().getType();
    }
    if (parent instanceof PsiForeachPatternStatement) {
      PsiExpression iteratedValue = ((PsiForeachPatternStatement)parent).getIteratedValue();
      if (iteratedValue == null) {
        return null;
      }
      return JavaGenericsUtil.getCollectionItemType(iteratedValue);
    }
    if (parent instanceof PsiCaseLabelElementList) {
      PsiSwitchLabelStatementBase label = ObjectUtils.tryCast(parent.getParent(), PsiSwitchLabelStatementBase.class);
      if (label != null) {
        PsiSwitchBlock block = label.getEnclosingSwitchBlock();
        if (block != null) {
          PsiExpression expression = block.getExpression();
          if (expression != null) {
            return expression.getType();
          }
        }
      }
    }
    if (parent instanceof PsiDeconstructionList) {
      PsiDeconstructionPattern parentPattern = ObjectUtils.tryCast(parent.getParent(), PsiDeconstructionPattern.class);
      if (parentPattern != null) {
        int index = ArrayUtil.indexOf(((PsiDeconstructionList)parent).getDeconstructionComponents(), pattern);
        if (index < 0) return null;
        PsiType patternType = parentPattern.getTypeElement().getType();
        if (!(patternType instanceof PsiClassType)) return null;
        PsiSubstitutor parentSubstitutor = ((PsiClassType)patternType).resolveGenerics().getSubstitutor();
        PsiClass parentRecord = PsiUtil.resolveClassInClassTypeOnly(parentPattern.getTypeElement().getType());
        if (parentRecord == null) return null;
        PsiRecordComponent[] components = parentRecord.getRecordComponents();
        if (index >= components.length) return null;
        return parentSubstitutor.substitute(components[index].getType());
      }
    }
    return null;
  }
public static @Nullable PsiType getContextType(@NotNull PsiPattern pattern)