@Nullable
  public static PsiClass getSuperClass(@NotNull PsiClass psiClass) {
    PsiManager manager = psiClass.getManager();
    GlobalSearchScope resolveScope = psiClass.getResolveScope();

    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    if (psiClass.isInterface()) {
      return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);
    }
    if (psiClass.isEnum()) {
      return facade.findClass(CommonClassNames.JAVA_LANG_ENUM, resolveScope);
    }

    if (psiClass instanceof PsiAnonymousClass) {
      PsiClassType baseClassReference = ((PsiAnonymousClass) psiClass).getBaseClassType();
      PsiClass baseClass = baseClassReference.resolve();
      if (baseClass == null || baseClass.isInterface())
        return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);
      return baseClass;
    }

    if (CommonClassNames.JAVA_LANG_OBJECT.equals(psiClass.getQualifiedName())) return null;

    final PsiClassType[] referenceElements = psiClass.getExtendsListTypes();

    if (referenceElements.length == 0)
      return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);

    PsiClass psiResoved = referenceElements[0].resolve();
    return psiResoved == null
        ? facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope)
        : psiResoved;
  }
  private static Map<String, PsiType> getCompatibleTypeNames(
      @NotNull PsiType type, @Nullable PsiType min, PsiManager manager, GlobalSearchScope scope) {
    if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound();

    // if initial type is not assignable to min type we don't take into consideration min type.
    if (min != null && !TypesUtil.isAssignable(min, type, manager, scope)) {
      min = null;
    }

    Map<String, PsiType> map = new LinkedHashMap<String, PsiType>();
    final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(type);
    if (unboxed != null) type = unboxed;
    final Set<PsiType> set = new LinkedHashSet<PsiType>();
    set.add(type);
    while (!set.isEmpty()) {
      PsiType cur = set.iterator().next();
      set.remove(cur);
      if (!map.containsValue(cur)
          && (min == null || TypesUtil.isAssignable(min, cur, manager, scope))) {
        if (isPartiallySubstituted(cur)) {
          LOG.assertTrue(cur instanceof PsiClassType);
          PsiClassType rawType = ((PsiClassType) cur).rawType();
          map.put(rawType.getPresentableText(), rawType);
        } else {
          map.put(cur.getPresentableText(), cur);
        }
        for (PsiType superType : cur.getSuperTypes()) {
          if (!map.containsValue(superType)) {
            set.add(superType);
          }
        }
      }
    }
    return map;
  }
 private static String compoundLambdaOrMethodReference(
     PsiParameter parameter,
     PsiExpression expression,
     String samQualifiedName,
     PsiType[] samParamTypes) {
   String result = "";
   final Project project = parameter.getProject();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiClass functionClass =
       psiFacade.findClass(samQualifiedName, GlobalSearchScope.allScope(project));
   for (int i = 0; i < samParamTypes.length; i++) {
     if (samParamTypes[i] instanceof PsiPrimitiveType) {
       samParamTypes[i] = ((PsiPrimitiveType) samParamTypes[i]).getBoxedType(expression);
     }
   }
   final PsiClassType functionalInterfaceType =
       functionClass != null
           ? psiFacade.getElementFactory().createType(functionClass, samParamTypes)
           : null;
   final PsiParameter[] parameters = {parameter};
   final String methodReferenceText =
       LambdaCanBeMethodReferenceInspection.convertToMethodReference(
           expression, parameters, functionalInterfaceType, null);
   if (methodReferenceText != null) {
     LOG.assertTrue(functionalInterfaceType != null);
     result += "(" + functionalInterfaceType.getCanonicalText() + ")" + methodReferenceText;
   } else {
     result += parameter.getName() + " -> " + expression.getText();
   }
   return result;
 }
 @Nullable
 private PsiType extractContentTypeFromType(PsiType collectionType) {
   if (!(collectionType instanceof PsiClassType)) {
     return null;
   }
   final PsiClassType classType = (PsiClassType) collectionType;
   final PsiType[] parameterTypes = classType.getParameters();
   if (parameterTypes.length == 0) {
     return null;
   }
   final PsiType parameterType = parameterTypes[0];
   if (parameterType == null) {
     return null;
   }
   if (parameterType instanceof PsiWildcardType) {
     final PsiWildcardType wildcardType = (PsiWildcardType) parameterType;
     return wildcardType.getExtendsBound();
   } else if (parameterType instanceof PsiCapturedWildcardType) {
     final PsiCapturedWildcardType capturedWildcardType =
         (PsiCapturedWildcardType) parameterType;
     final PsiWildcardType wildcardType = capturedWildcardType.getWildcard();
     return wildcardType.getExtendsBound();
   }
   return parameterType;
 }
  @NotNull
  private static PsiClass[] resolveClassReferenceList(
      @NotNull PsiClassType[] listOfTypes,
      @NotNull PsiManager manager,
      @NotNull GlobalSearchScope resolveScope,
      boolean includeObject) {
    PsiClass objectClass =
        JavaPsiFacade.getInstance(manager.getProject())
            .findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);
    if (objectClass == null) includeObject = false;
    if (listOfTypes.length == 0) {
      if (includeObject) return new PsiClass[] {objectClass};
      return PsiClass.EMPTY_ARRAY;
    }

    int referenceCount = listOfTypes.length;
    if (includeObject) referenceCount++;

    PsiClass[] resolved = new PsiClass[referenceCount];
    int resolvedCount = 0;

    if (includeObject) resolved[resolvedCount++] = objectClass;
    for (PsiClassType reference : listOfTypes) {
      PsiClass refResolved = reference.resolve();
      if (refResolved != null) resolved[resolvedCount++] = refResolved;
    }

    if (resolvedCount < referenceCount) {
      PsiClass[] shorter = new PsiClass[resolvedCount];
      System.arraycopy(resolved, 0, shorter, 0, resolvedCount);
      resolved = shorter;
    }

    return resolved;
  }
  @Nullable
  public PsiClass getContainingClassElement() {
    final PsiClassType containingClassType =
        JavaPsiFacade.getInstance(getProject())
            .getElementFactory()
            .createTypeByFQClassName(myContainingClassName, ProjectScope.getAllScope(getProject()));

    return containingClassType.resolve();
  }
 @Override
 public void visitThrowStatement(PsiThrowStatement statement) {
   super.visitThrowStatement(statement);
   final PsiCatchSection catchSection =
       PsiTreeUtil.getParentOfType(statement, PsiCatchSection.class, true, PsiClass.class);
   if (catchSection == null) {
     return;
   }
   final PsiParameter parameter = catchSection.getParameter();
   if (parameter == null) {
     return;
   }
   @NonNls final String parameterName = parameter.getName();
   if (PsiUtil.isIgnoredName(parameterName)) {
     return;
   }
   final PsiExpression exception = statement.getException();
   if (exception == null) {
     return;
   }
   if (ignoreCantWrap) {
     final PsiType thrownType = exception.getType();
     if (thrownType instanceof PsiClassType) {
       final PsiClassType classType = (PsiClassType) thrownType;
       final PsiClass exceptionClass = classType.resolve();
       if (exceptionClass != null) {
         final PsiMethod[] constructors = exceptionClass.getConstructors();
         final PsiClassType throwableType =
             TypeUtils.getType(CommonClassNames.JAVA_LANG_THROWABLE, statement);
         boolean canWrap = false;
         outer:
         for (PsiMethod constructor : constructors) {
           final PsiParameterList parameterList = constructor.getParameterList();
           final PsiParameter[] parameters = parameterList.getParameters();
           for (PsiParameter constructorParameter : parameters) {
             final PsiType type = constructorParameter.getType();
             if (throwableType.equals(type)) {
               canWrap = true;
               break outer;
             }
           }
         }
         if (!canWrap) {
           return;
         }
       }
     }
   }
   final ReferenceFinder visitor = new ReferenceFinder(parameter);
   exception.accept(visitor);
   if (visitor.usesParameter()) {
     return;
   }
   registerStatementError(statement);
 }
 private boolean isTypeParameter(PsiType type) {
   if (!(type instanceof PsiClassType)) {
     return false;
   }
   final PsiClassType classType = (PsiClassType) type;
   final PsiClass aClass = classType.resolve();
   if (aClass == null) {
     return false;
   }
   return aClass instanceof PsiTypeParameter;
 }
  @NotNull
  private static PsiClass[] getSupersInner(@NotNull PsiClass psiClass) {
    PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes();
    PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes();

    if (psiClass.isInterface()) {
      return resolveClassReferenceList(
          extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), true);
    }

    if (psiClass instanceof PsiAnonymousClass) {
      PsiAnonymousClass psiAnonymousClass = (PsiAnonymousClass) psiClass;
      PsiClassType baseClassReference = psiAnonymousClass.getBaseClassType();
      PsiClass baseClass = baseClassReference.resolve();
      if (baseClass != null) {
        if (baseClass.isInterface()) {
          PsiClass objectClass =
              JavaPsiFacade.getInstance(psiClass.getProject())
                  .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope());
          return objectClass != null
              ? new PsiClass[] {objectClass, baseClass}
              : new PsiClass[] {baseClass};
        }
        return new PsiClass[] {baseClass};
      }

      PsiClass objectClass =
          JavaPsiFacade.getInstance(psiClass.getProject())
              .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope());
      return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY;
    }
    if (psiClass instanceof PsiTypeParameter) {
      if (extendsListTypes.length == 0) {
        final PsiClass objectClass =
            JavaPsiFacade.getInstance(psiClass.getProject())
                .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope());
        return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY;
      }
      return resolveClassReferenceList(
          extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false);
    }

    PsiClass[] interfaces =
        resolveClassReferenceList(
            implementsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false);

    PsiClass superClass = getSuperClass(psiClass);
    if (superClass == null) return interfaces;
    PsiClass[] types = new PsiClass[interfaces.length + 1];
    types[0] = superClass;
    System.arraycopy(interfaces, 0, types, 1, interfaces.length);

    return types;
  }
 @NotNull
 public static PsiClass[] getInterfaces(@NotNull PsiTypeParameter typeParameter) {
   final PsiClassType[] referencedTypes = typeParameter.getExtendsListTypes();
   if (referencedTypes.length == 0) {
     return PsiClass.EMPTY_ARRAY;
   }
   final List<PsiClass> result = new ArrayList<PsiClass>(referencedTypes.length);
   for (PsiClassType referencedType : referencedTypes) {
     final PsiClass psiClass = referencedType.resolve();
     if (psiClass != null && psiClass.isInterface()) {
       result.add(psiClass);
     }
   }
   return result.toArray(new PsiClass[result.size()]);
 }
 @Nullable
 private PsiType extractListTypeFromContainingClass(PsiElement element) {
   PsiClass listClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
   if (listClass == null) {
     return null;
   }
   final PsiMethod[] getMethods = listClass.findMethodsByName("get", true);
   if (getMethods.length == 0) {
     return null;
   }
   final PsiType type = getMethods[0].getReturnType();
   if (!(type instanceof PsiClassType)) {
     return null;
   }
   final PsiClassType classType = (PsiClassType) type;
   final PsiClass parameterClass = classType.resolve();
   if (parameterClass == null) {
     return null;
   }
   PsiClass subClass = null;
   while (listClass != null && !listClass.hasTypeParameters()) {
     subClass = listClass;
     listClass = listClass.getSuperClass();
   }
   if (listClass == null || subClass == null) {
     return TypeUtils.getObjectType(element);
   }
   final PsiTypeParameter[] typeParameters = listClass.getTypeParameters();
   if (!parameterClass.equals(typeParameters[0])) {
     return TypeUtils.getObjectType(element);
   }
   final PsiReferenceList extendsList = subClass.getExtendsList();
   if (extendsList == null) {
     return null;
   }
   final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements();
   if (referenceElements.length == 0) {
     return null;
   }
   final PsiType[] types = referenceElements[0].getTypeParameters();
   if (types.length == 0) {
     return TypeUtils.getObjectType(element);
   }
   return types[0];
 }
 private static String createInitializerReplacementText(
     PsiType varType, PsiExpression initializer) {
   final PsiType initializerType = initializer.getType();
   final PsiClassType rawType =
       initializerType instanceof PsiClassType
           ? ((PsiClassType) initializerType).rawType()
           : null;
   final PsiClassType rawVarType =
       varType instanceof PsiClassType ? ((PsiClassType) varType).rawType() : null;
   if (rawType != null
       && rawVarType != null
       && rawType.equalsToText(CommonClassNames.JAVA_UTIL_ARRAY_LIST)
       && rawVarType.equalsToText(CommonClassNames.JAVA_UTIL_LIST)) {
     return "toList()";
   } else if (rawType != null
       && rawVarType != null
       && rawType.equalsToText(CommonClassNames.JAVA_UTIL_HASH_SET)
       && rawVarType.equalsToText(CommonClassNames.JAVA_UTIL_SET)) {
     return "toSet()";
   } else if (rawType != null) {
     return "toCollection(" + rawType.getClassName() + "::new)";
   } else {
     return "toCollection(() -> " + initializer.getText() + ")";
   }
 }
 private void checkExpression(@NotNull PsiExpression expression) {
   if (expression.getParent() instanceof PsiParenthesizedExpression) {
     return;
   }
   final PsiType expressionType = expression.getType();
   if (expressionType == null
       || expressionType.equals(PsiType.VOID)
       || !TypeConversionUtil.isPrimitiveAndNotNull(expressionType)) {
     return;
   }
   final PsiPrimitiveType primitiveType = (PsiPrimitiveType) expressionType;
   final PsiClassType boxedType = primitiveType.getBoxedType(expression);
   if (boxedType == null) {
     return;
   }
   final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false);
   if (expectedType == null || ClassUtils.isPrimitive(expectedType)) {
     return;
   }
   if (!expectedType.isAssignableFrom(boxedType)) {
     // JLS 5.2 Assignment Conversion
     // check if a narrowing primitive conversion is applicable
     if (!(expectedType instanceof PsiClassType) || !PsiUtil.isConstantExpression(expression)) {
       return;
     }
     final PsiClassType classType = (PsiClassType) expectedType;
     final String className = classType.getCanonicalText();
     if (!convertableBoxedClassNames.contains(className)) {
       return;
     }
     if (!PsiType.BYTE.equals(expressionType)
         && !PsiType.CHAR.equals(expressionType)
         && !PsiType.SHORT.equals(expressionType)
         && !PsiType.INT.equals(expressionType)) {
       return;
     }
   }
   if (ignoreAddedToCollection && isAddedToCollection(expression)) {
     return;
   }
   registerError(expression);
 }
  @NotNull
  public static PsiClass[] getInterfaces(@NotNull PsiClass psiClass) {
    if (psiClass.isInterface()) {
      final PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes();
      return resolveClassReferenceList(
          extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false);
    }

    if (psiClass instanceof PsiAnonymousClass) {
      PsiClassType baseClassReference = ((PsiAnonymousClass) psiClass).getBaseClassType();
      PsiClass baseClass = baseClassReference.resolve();
      return baseClass != null && baseClass.isInterface()
          ? new PsiClass[] {baseClass}
          : PsiClass.EMPTY_ARRAY;
    }

    final PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes();
    return resolveClassReferenceList(
        implementsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false);
  }
 private static boolean processSuperTypes(
     @NotNull PsiClass aClass,
     @NotNull PsiScopeProcessor processor,
     @Nullable Set<PsiClass> visited,
     PsiElement last,
     @NotNull PsiElement place,
     @NotNull ResolveState state,
     boolean isRaw,
     @NotNull PsiElementFactory factory,
     @NotNull LanguageLevel languageLevel) {
   boolean resolved = false;
   for (final PsiClassType superType : aClass.getSuperTypes()) {
     final PsiClassType.ClassResolveResult superTypeResolveResult = superType.resolveGenerics();
     PsiClass superClass = superTypeResolveResult.getElement();
     if (superClass == null) continue;
     PsiSubstitutor finalSubstitutor =
         obtainFinalSubstitutor(
             superClass,
             superTypeResolveResult.getSubstitutor(),
             aClass,
             state.get(PsiSubstitutor.KEY),
             factory,
             languageLevel);
     if (aClass instanceof PsiTypeParameter
         && PsiUtil.isRawSubstitutor(superClass, finalSubstitutor)) {
       finalSubstitutor = PsiSubstitutor.EMPTY;
     }
     if (!processDeclarationsInClass(
         superClass,
         processor,
         state.put(PsiSubstitutor.KEY, finalSubstitutor),
         visited,
         last,
         place,
         isRaw)) {
       resolved = true;
     }
   }
   return !resolved;
 }
    private void checkExpression(PsiExpression expression) {
      if (expression == null) return;

      final PsiType type = expression.getType();
      if (!(type instanceof PsiClassType)) return;

      if (IGNORE_TOSTRING
          && MethodUtils.isToString(PsiTreeUtil.getParentOfType(expression, PsiMethod.class)))
        return;

      if (IGNORE_EXCEPTION
          && (ExceptionUtils.isExceptionArgument(expression)
              || PsiTreeUtil.getParentOfType(
                      expression, PsiThrowStatement.class, true, PsiCodeBlock.class, PsiClass.class)
                  != null)) return;

      if (IGNORE_ASSERT
          && PsiTreeUtil.getParentOfType(
                  expression, PsiAssertStatement.class, true, PsiCodeBlock.class, PsiClass.class)
              != null) {
        return;
      }

      if (IGNORE_NONNLS && NonNlsUtils.isNonNlsAnnotatedUse(expression)) return;

      final PsiClassType classType = (PsiClassType) type;
      if (type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return;

      final PsiClass referencedClass = classType.resolve();
      if (referencedClass == null || referencedClass instanceof PsiTypeParameter) return;
      if (referencedClass.isEnum() || referencedClass.isInterface()) return;
      if (referencedClass.hasModifierProperty(PsiModifier.ABSTRACT)
          && !(expression instanceof PsiSuperExpression)) return;
      if (hasGoodToString(referencedClass)) return;

      registerError(expression);
    }
  @NotNull
  public static PsiClassType[] getSuperTypes(@NotNull PsiClass psiClass) {
    if (psiClass instanceof PsiAnonymousClass) {
      PsiClassType baseClassType = ((PsiAnonymousClass) psiClass).getBaseClassType();
      PsiClass baseClass = baseClassType.resolve();
      if (baseClass == null || !baseClass.isInterface()) {
        return new PsiClassType[] {baseClassType};
      } else {
        PsiClassType objectType =
            PsiType.getJavaLangObject(psiClass.getManager(), psiClass.getResolveScope());
        return new PsiClassType[] {objectType, baseClassType};
      }
    }

    PsiClassType[] extendsTypes = psiClass.getExtendsListTypes();
    PsiClassType[] implementsTypes = psiClass.getImplementsListTypes();
    boolean hasExtends = extendsTypes.length != 0;
    int extendsListLength = extendsTypes.length + (hasExtends ? 0 : 1);
    PsiClassType[] result = new PsiClassType[extendsListLength + implementsTypes.length];

    System.arraycopy(extendsTypes, 0, result, 0, extendsTypes.length);
    if (!hasExtends) {
      if (CommonClassNames.JAVA_LANG_OBJECT.equals(psiClass.getQualifiedName())) {
        return PsiClassType.EMPTY_ARRAY;
      }
      PsiManager manager = psiClass.getManager();
      PsiClassType objectType = PsiType.getJavaLangObject(manager, psiClass.getResolveScope());
      result[0] = objectType;
    }
    System.arraycopy(implementsTypes, 0, result, extendsListLength, implementsTypes.length);
    for (int i = 0; i < result.length; i++) {
      PsiClassType type = result[i];
      result[i] = (PsiClassType) PsiUtil.captureToplevelWildcards(type, psiClass);
    }
    return result;
  }
        private boolean hasTypeParametersToInfer(PsiClassType classType) {
          final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics();
          PsiClass aClass = resolveResult.getElement();
          if (aClass == null) return false;

          final Iterable<PsiTypeParameter> iterable =
              com.intellij.psi.util.PsiUtil.typeParametersIterable(aClass);
          if (!iterable.iterator().hasNext()) {
            return false;
          }

          for (PsiTypeParameter parameter : iterable) {
            PsiType type = resolveResult.getSubstitutor().substitute(parameter);
            if (type != null) {
              if (!(type instanceof PsiWildcardType)
                  || ((PsiWildcardType) type).getBound() != null) {
                return false;
              }
            }
          }
          return true;
        }
  @Override
  protected String validateAndCommitData() {
    PsiManager manager = PsiManager.getInstance(myProject);
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();

    String name = getMethodName();
    if (!JavaPsiFacade.getInstance(manager.getProject()).getNameHelper().isIdentifier(name)) {
      return RefactoringMessageUtil.getIncorrectIdentifierMessage(name);
    }

    if (myMethod.canChangeReturnType() == MethodDescriptor.ReadWriteOption.ReadWrite) {
      try {
        ((PsiTypeCodeFragment) myReturnTypeCodeFragment).getType();
      } catch (PsiTypeCodeFragment.TypeSyntaxException e) {
        myReturnTypeField.requestFocus();
        return RefactoringBundle.message(
            "changeSignature.wrong.return.type", myReturnTypeCodeFragment.getText());
      } catch (PsiTypeCodeFragment.NoTypeException e) {
        myReturnTypeField.requestFocus();
        return RefactoringBundle.message("changeSignature.no.return.type");
      }
    }

    List<ParameterTableModelItemBase<ParameterInfoImpl>> parameterInfos =
        myParametersTableModel.getItems();
    final int newParametersNumber = parameterInfos.size();

    for (int i = 0; i < newParametersNumber; i++) {
      final ParameterTableModelItemBase<ParameterInfoImpl> item = parameterInfos.get(i);

      if (!JavaPsiFacade.getInstance(manager.getProject())
          .getNameHelper()
          .isIdentifier(item.parameter.getName())) {
        return RefactoringMessageUtil.getIncorrectIdentifierMessage(item.parameter.getName());
      }

      final PsiType type;
      try {
        type = ((PsiTypeCodeFragment) parameterInfos.get(i).typeCodeFragment).getType();
      } catch (PsiTypeCodeFragment.TypeSyntaxException e) {
        return RefactoringBundle.message(
            "changeSignature.wrong.type.for.parameter",
            item.typeCodeFragment.getText(),
            item.parameter.getName());
      } catch (PsiTypeCodeFragment.NoTypeException e) {
        return RefactoringBundle.message(
            "changeSignature.no.type.for.parameter", item.parameter.getName());
      }

      item.parameter.setType(type);

      if (type instanceof PsiEllipsisType && i != newParametersNumber - 1) {
        return RefactoringBundle.message("changeSignature.vararg.not.last");
      }

      if (item.parameter.oldParameterIndex < 0) {
        item.parameter.defaultValue =
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Computable<String>() {
                      @Override
                      public String compute() {
                        return JavaCodeStyleManager.getInstance(myProject)
                            .qualifyClassReferences(item.defaultValueCodeFragment)
                            .getText();
                      }
                    });
        String def = item.parameter.defaultValue;
        def = def.trim();
        if (!(type instanceof PsiEllipsisType)) {
          try {
            if (!StringUtil.isEmpty(def)) {
              factory.createExpressionFromText(def, null);
            }
          } catch (IncorrectOperationException e) {
            return e.getMessage();
          }
        }
      }
    }

    ThrownExceptionInfo[] exceptionInfos = myExceptionsModel.getThrownExceptions();
    PsiTypeCodeFragment[] typeCodeFragments = myExceptionsModel.getTypeCodeFragments();
    for (int i = 0; i < exceptionInfos.length; i++) {
      ThrownExceptionInfo exceptionInfo = exceptionInfos[i];
      PsiTypeCodeFragment typeCodeFragment = typeCodeFragments[i];
      try {
        PsiType type = typeCodeFragment.getType();
        if (!(type instanceof PsiClassType)) {
          return RefactoringBundle.message(
              "changeSignature.wrong.type.for.exception", typeCodeFragment.getText());
        }

        PsiClassType throwable =
            JavaPsiFacade.getInstance(myProject)
                .getElementFactory()
                .createTypeByFQClassName("java.lang.Throwable", type.getResolveScope());
        if (!throwable.isAssignableFrom(type)) {
          return RefactoringBundle.message(
              "changeSignature.not.throwable.type", typeCodeFragment.getText());
        }
        exceptionInfo.setType((PsiClassType) type);
      } catch (PsiTypeCodeFragment.TypeSyntaxException e) {
        return RefactoringBundle.message(
            "changeSignature.wrong.type.for.exception", typeCodeFragment.getText());
      } catch (PsiTypeCodeFragment.NoTypeException e) {
        return RefactoringBundle.message("changeSignature.no.type.for.exception");
      }
    }

    // warnings
    try {
      if (myMethod.canChangeReturnType() == MethodDescriptor.ReadWriteOption.ReadWrite) {
        if (!RefactoringUtil.isResolvableType(
            ((PsiTypeCodeFragment) myReturnTypeCodeFragment).getType())) {
          if (Messages.showOkCancelDialog(
                  myProject,
                  RefactoringBundle.message(
                      "changeSignature.cannot.resolve.return.type",
                      myReturnTypeCodeFragment.getText()),
                  RefactoringBundle.message("changeSignature.refactoring.name"),
                  Messages.getWarningIcon())
              != 0) {
            return EXIT_SILENTLY;
          }
        }
      }
      for (ParameterTableModelItemBase<ParameterInfoImpl> item : parameterInfos) {

        if (!RefactoringUtil.isResolvableType(
            ((PsiTypeCodeFragment) item.typeCodeFragment).getType())) {
          if (Messages.showOkCancelDialog(
                  myProject,
                  RefactoringBundle.message(
                      "changeSignature.cannot.resolve.parameter.type",
                      item.typeCodeFragment.getText(),
                      item.parameter.getName()),
                  RefactoringBundle.message("changeSignature.refactoring.name"),
                  Messages.getWarningIcon())
              != 0) {
            return EXIT_SILENTLY;
          }
        }
      }
    } catch (PsiTypeCodeFragment.IncorrectTypeException ignored) {
    }
    return null;
  }
 @Override
 public void visitTypeCastExpression(@NotNull PsiTypeCastExpression expression) {
   super.visitTypeCastExpression(expression);
   final PsiExpression operand = expression.getOperand();
   if (operand == null) {
     return;
   }
   final PsiType operandType = operand.getType();
   if (operandType == null) {
     return;
   }
   final PsiType type = expression.getType();
   if (type == null) {
     return;
   }
   final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, true);
   if (expectedType == null) {
     return;
   }
   if (expectedType.equals(type)) {
     return;
   }
   final PsiClass resolved = PsiUtil.resolveClassInType(expectedType);
   if (resolved != null && !resolved.isPhysical()) {
     return;
   }
   if (expectedType.isAssignableFrom(operandType)) {
     // then it's redundant, and caught by the built-in exception
     return;
   }
   if (isTypeParameter(expectedType)) {
     return;
   }
   if (expectedType instanceof PsiArrayType) {
     final PsiArrayType arrayType = (PsiArrayType) expectedType;
     final PsiType componentType = arrayType.getDeepComponentType();
     if (isTypeParameter(componentType)) {
       return;
     }
   }
   if (type instanceof PsiPrimitiveType || expectedType instanceof PsiPrimitiveType) {
     return;
   }
   if (PsiPrimitiveType.getUnboxedType(type) != null
       || PsiPrimitiveType.getUnboxedType(expectedType) != null) {
     return;
   }
   if (expectedType instanceof PsiClassType) {
     final PsiClassType expectedClassType = (PsiClassType) expectedType;
     final PsiClassType expectedRawType = expectedClassType.rawType();
     if (type.equals(expectedRawType)) {
       return;
     }
     if (type instanceof PsiClassType) {
       final PsiClassType classType = (PsiClassType) type;
       final PsiClassType rawType = classType.rawType();
       if (rawType.equals(expectedRawType)) {
         return;
       }
     }
     if (type instanceof PsiArrayType) {
       return;
     }
   }
   if (ignoreInMatchingInstanceof && InstanceOfUtils.hasAgreeingInstanceof(expression)) {
     return;
   }
   final PsiTypeElement castTypeElement = expression.getCastType();
   if (castTypeElement == null) {
     return;
   }
   registerError(castTypeElement, expectedType);
 }
  private boolean validateInputData() {
    if (!isGroovyMethodName(getNewName())) {
      showErrorHint(message("name.is.wrong", getNewName()));
      return false;
    }

    if (!checkType(myReturnTypeCodeFragment, true)) {
      showErrorHint(message("return.type.is.wrong"));
      return false;
    }

    List<GrTableParameterInfo> parameterInfos = myParameterModel.getParameterInfos();
    for (int i = 0; i < parameterInfos.size(); i++) {
      GrTableParameterInfo info = parameterInfos.get(i);
      if (!StringUtil.isJavaIdentifier(info.getName())) {
        showErrorHint(message("name.is.wrong", info.getName()));
        return false;
      }
      if (!checkType(info.getTypeFragment(), i == parameterInfos.size() - 1)) {
        showErrorHint(message("type.for.parameter.is.incorrect", info.getName()));
        return false;
      }
      String defaultValue = info.getDefaultValue();
      final String initializer = info.getDefaultInitializerFragment().getText();
      if (info.getOldIndex() < 0
          && defaultValue.trim().length() == 0
          && initializer.trim().length() == 0) {
        showErrorHint(message("specify.default.value", info.getName()));
        return false;
      }
    }

    ThrownExceptionInfo[] exceptionInfos = myExceptionTableModel.getThrownExceptions();
    PsiTypeCodeFragment[] typeCodeFragments = myExceptionTableModel.getTypeCodeFragments();
    for (int i = 0; i < exceptionInfos.length; i++) {
      ThrownExceptionInfo exceptionInfo = exceptionInfos[i];
      PsiTypeCodeFragment typeCodeFragment = typeCodeFragments[i];
      try {
        PsiType type = typeCodeFragment.getType();
        if (!(type instanceof PsiClassType)) {
          showErrorHint(
              GroovyRefactoringBundle.message(
                  "changeSignature.wrong.type.for.exception", typeCodeFragment.getText()));
          return false;
        }

        PsiClassType throwable =
            JavaPsiFacade.getInstance(myMethod.getProject())
                .getElementFactory()
                .createTypeByFQClassName("java.lang.Throwable", myMethod.getResolveScope());
        if (!throwable.isAssignableFrom(type)) {
          showErrorHint(
              GroovyRefactoringBundle.message(
                  "changeSignature.not.throwable.type", typeCodeFragment.getText()));
          return false;
        }
        exceptionInfo.setType((PsiClassType) type);
      } catch (PsiTypeCodeFragment.TypeSyntaxException e) {
        showErrorHint(
            GroovyRefactoringBundle.message(
                "changeSignature.wrong.type.for.exception", typeCodeFragment.getText()));
        return false;
      } catch (PsiTypeCodeFragment.NoTypeException e) {
        showErrorHint(GroovyRefactoringBundle.message("changeSignature.no.type.for.exception"));
        return false;
      }
    }

    return true;
  }