private static void qualify(PsiMember member, PsiElement renamed, String name) {
    if (!(renamed instanceof GrReferenceExpression)) return;

    final PsiClass clazz = member.getContainingClass();
    if (clazz == null) return;

    final GrReferenceExpression refExpr = (GrReferenceExpression) renamed;
    final PsiElement replaced;
    if (member.hasModifierProperty(GrModifier.STATIC)) {
      final GrReferenceExpression newRefExpr =
          GroovyPsiElementFactory.getInstance(member.getProject())
              .createReferenceExpressionFromText(clazz.getQualifiedName() + "." + name);
      replaced = refExpr.replace(newRefExpr);
    } else {
      final PsiClass containingClass = PsiTreeUtil.getParentOfType(renamed, PsiClass.class);
      if (member.getManager().areElementsEquivalent(containingClass, clazz)) {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText("this." + name);
        replaced = refExpr.replace(newRefExpr);
      } else {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText(clazz.getQualifiedName() + ".this." + name);
        replaced = refExpr.replace(newRefExpr);
      }
    }
    PsiUtil.shortenReferences((GroovyPsiElement) replaced);
  }
Example #2
0
 @Nullable
 private static String getLongTypeName(PsiType type) {
   if (type instanceof PsiClassType) {
     PsiClass aClass = ((PsiClassType) type).resolve();
     if (aClass == null) {
       return null;
     } else if (aClass instanceof PsiAnonymousClass) {
       PsiClass baseClass = ((PsiAnonymousClass) aClass).getBaseClassType().resolve();
       return baseClass != null ? baseClass.getQualifiedName() : null;
     } else {
       return aClass.getQualifiedName();
     }
   } else if (type instanceof PsiArrayType) {
     return getLongTypeName(((PsiArrayType) type).getComponentType()) + "[]";
   } else if (type instanceof PsiPrimitiveType) {
     return type.getPresentableText();
   } else if (type instanceof PsiWildcardType) {
     final PsiType bound = ((PsiWildcardType) type).getBound();
     return bound != null ? getLongTypeName(bound) : CommonClassNames.JAVA_LANG_OBJECT;
   } else if (type instanceof PsiCapturedWildcardType) {
     final PsiType bound = ((PsiCapturedWildcardType) type).getWildcard().getBound();
     return bound != null ? getLongTypeName(bound) : CommonClassNames.JAVA_LANG_OBJECT;
   } else if (type instanceof PsiIntersectionType) {
     return getLongTypeName(((PsiIntersectionType) type).getRepresentative());
   } else if (type instanceof PsiDisjunctionType) {
     return getLongTypeName(((PsiDisjunctionType) type).getLeastUpperBound());
   } else {
     return null;
   }
 }
  /**
   * Creates a new {@link ClassElement} object.
   *
   * @param clazz class information.
   * @return a new {@link ClassElement} object.
   */
  public static ClassElement newClassElement(PsiClass clazz) {
    ClassElement ce = new ClassElement();

    // name
    ce.setName(clazz.getName());
    ce.setQualifiedName(clazz.getQualifiedName());

    // super
    PsiClass superClass = clazz.getSuperClass();
    if (superClass != null
        && !CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) {
      ce.setSuperName(superClass.getName());
    }

    // interfaces
    ce.setImplementNames(PsiAdapter.getImplementsClassnames(clazz));

    // other
    ce.setEnum(clazz.isEnum());
    ce.setDeprecated(clazz.isDeprecated());
    ce.setException(PsiAdapter.isExceptionClass(clazz));
    ce.setAbstract(clazz.hasModifierProperty(PsiModifier.ABSTRACT));
    ce.setTypeParams(clazz.getTypeParameters().length);

    return ce;
  }
 public void testRunningAllInPackage() throws IOException, ExecutionException {
   Module module1 = getModule1();
   GlobalSearchScope module1AndLibraries = GlobalSearchScope.moduleWithLibrariesScope(module1);
   PsiClass testCase = findClass(TestCase.class.getName(), module1AndLibraries);
   PsiClass psiClass = findTestA(module1);
   PsiClass psiClass2 = findTestA(getModule2());
   PsiClass derivedTest = findClass(module1, "test1.DerivedTest");
   PsiClass baseTestCase = findClass("junit.framework.ThirdPartyClass", module1AndLibraries);
   PsiClass testB = findClass(getModule3(), "test1.TestB");
   assertNotNull(testCase);
   assertNotNull(derivedTest);
   assertNotNull(psiClass);
   assertTrue(psiClass.isInheritor(testCase, false));
   assertEquals(baseTestCase, derivedTest.getSuperClass());
   assertTrue(baseTestCase.isInheritor(testCase, true));
   assertTrue(derivedTest.isInheritor(testCase, true));
   PsiPackage psiPackage = JUnitUtil.getContainingPackage(psiClass);
   JUnitConfiguration configuration = createConfiguration(psiPackage, module1);
   JavaParameters parameters = checkCanRun(configuration);
   List<String> lines = extractAllInPackageTests(parameters, psiPackage);
   Assertion.compareUnordered(
       new Object[] {
         "",
         psiClass.getQualifiedName(),
         psiClass2.getQualifiedName(),
         derivedTest.getQualifiedName(),
         RT_INNER_TEST_NAME,
         testB.getQualifiedName()
       },
       lines);
 }
  public void testEditJUnitConfiguration() throws ConfigurationException {
    if (PlatformTestUtil.COVERAGE_ENABLED_BUILD) return;

    PsiClass testA = findTestA(getModule2());
    JUnitConfiguration configuration = createConfiguration(testA);
    JUnitConfigurable editor = new JUnitConfigurable(myProject);
    try {
      Configurable configurable = new RunConfigurationConfigurableAdapter(editor, configuration);
      configurable.reset();
      final EditorTextFieldWithBrowseButton component =
          ((LabeledComponent<EditorTextFieldWithBrowseButton>)
                  editor.getTestLocation(JUnitConfigurationModel.CLASS))
              .getComponent();
      assertEquals(testA.getQualifiedName(), component.getText());
      PsiClass otherTest = findClass(getModule2(), "test2.Test2");
      component.setText(otherTest.getQualifiedName());
      configurable.apply();
      assertEquals(otherTest.getName(), configuration.getName());
      String specialName = "My name";
      configuration.setName(specialName);
      configuration.setNameChangedByUser(true);
      configurable.reset();
      component.setText(testA.getQualifiedName());
      configurable.apply();
      assertEquals(specialName, configuration.getName());
    } finally {
      Disposer.dispose(editor);
    }
  }
 private void findUsagesForInnerClass(PsiClass innerClass, List<FixableUsageInfo> usages) {
   final PsiManager psiManager = innerClass.getManager();
   final Project project = psiManager.getProject();
   final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
   final Iterable<PsiReference> calls = ReferencesSearch.search(innerClass, scope);
   final String innerName = innerClass.getQualifiedName();
   assert innerName != null;
   final String sourceClassQualifiedName = sourceClass.getQualifiedName();
   assert sourceClassQualifiedName != null;
   final String newInnerClassName =
       getQualifiedName() + innerName.substring(sourceClassQualifiedName.length());
   boolean hasExternalReference = false;
   for (PsiReference reference : calls) {
     final PsiElement referenceElement = reference.getElement();
     if (referenceElement instanceof PsiJavaCodeReferenceElement) {
       if (!isInMovedElement(referenceElement)) {
         usages.add(
             new ReplaceClassReference(
                 (PsiJavaCodeReferenceElement) referenceElement, newInnerClassName));
         hasExternalReference = true;
       }
     }
   }
   if (hasExternalReference) {
     innerClassesToMakePublic.add(innerClass);
   }
 }
 @Override
 @NotNull
 public String buildErrorString(Object... infos) {
   final PsiClass declaringClass = (PsiClass) infos[0];
   final PsiClass referencedClass = (PsiClass) infos[1];
   return InspectionGadgetsBundle.message(
       "static.method.via.subclass.problem.descriptor",
       declaringClass.getQualifiedName(),
       referencedClass.getQualifiedName());
 }
Example #8
0
 public static boolean resolvesTo(PsiType type, String fqn) {
   if (type instanceof PsiClassType) {
     final PsiClass resolved = ((PsiClassType) type).resolve();
     return resolved != null && fqn.equals(resolved.getQualifiedName());
   }
   return false;
 }
Example #9
0
 public static boolean isClassType(@Nullable PsiType type, @NotNull String qName) {
   if (type instanceof PsiClassType) {
     final PsiClass psiClass = ((PsiClassType) type).resolve();
     return psiClass != null && qName.equals(psiClass.getQualifiedName());
   }
   return false;
 }
  private static boolean isAcceptedByPattern(
      @NotNull PsiClass element,
      String qualifiedName,
      ClassPattern pattern,
      Set<PsiClass> visited) {
    if (qualifiedName == null) {
      return false;
    }

    if (qualifiedName.equals(pattern.pattern)) {
      return true;
    }

    if (pattern.pattern.endsWith(PATTERN_SUFFIX)
        && qualifiedName.startsWith(StringUtil.trimEnd(pattern.pattern, PATTERN_SUFFIX))) {
      return true;
    }

    if (pattern.hierarchically) {
      for (PsiClass superClass : element.getSupers()) {
        final String superClassQualifiedName = superClass.getQualifiedName();
        if (visited.add(superClass)
            && isAcceptedByPattern(superClass, superClassQualifiedName, pattern, visited)) {
          return true;
        }
      }
    }
    return false;
  }
  private static PsiAnnotationMemberValue[] readFromClass(
      @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) {
    PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName);
    PsiType fromClassType =
        fromClassAttr instanceof PsiClassObjectAccessExpression
            ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType()
            : null;
    PsiClass fromClass =
        fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null;
    if (fromClass == null) return null;
    String fqn = fromClass.getQualifiedName();
    if (fqn == null) return null;
    List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>();
    for (PsiField field : fromClass.getFields()) {
      if (!field.hasModifierProperty(PsiModifier.PUBLIC)
          || !field.hasModifierProperty(PsiModifier.STATIC)
          || !field.hasModifierProperty(PsiModifier.FINAL)) continue;
      PsiType fieldType = field.getType();
      if (!Comparing.equal(fieldType, type)) continue;
      PsiAssignmentExpression e =
          (PsiAssignmentExpression)
              JavaPsiFacade.getElementFactory(field.getProject())
                  .createExpressionFromText("x=" + fqn + "." + field.getName(), field);
      PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression();
      constants.add(refToField);
    }
    if (constants.isEmpty()) return null;

    return constants.toArray(new PsiAnnotationMemberValue[constants.size()]);
  }
  private GroovyResolveResult[] resolveTypeOrProperty() {
    if (isDefinitelyKeyOfMap()) return GroovyResolveResult.EMPTY_ARRAY;

    final GroovyResolveResult[] results = resolveTypeOrPropertyInner();
    if (results.length == 0) return GroovyResolveResult.EMPTY_ARRAY;

    if (!ResolveUtil.mayBeKeyOfMap(this)) return results;

    // filter out all members from super classes. We should return only accessible members from map
    // classes
    List<GroovyResolveResult> filtered = new ArrayList<GroovyResolveResult>();
    for (GroovyResolveResult result : results) {
      final PsiElement element = result.getElement();
      if (element instanceof PsiMember) {
        if (((PsiMember) element).hasModifierProperty(PsiModifier.PRIVATE)) continue;
        final PsiClass containingClass = ((PsiMember) element).getContainingClass();
        if (containingClass != null) {
          if (!InheritanceUtil.isInheritor(containingClass, CommonClassNames.JAVA_UTIL_MAP))
            continue;
          final String name = containingClass.getQualifiedName();
          if (name != null && name.startsWith("java.")) continue;
          if (containingClass.getLanguage() != GroovyFileType.GROOVY_LANGUAGE
              && !InheritanceUtil.isInheritor(
                  containingClass, GroovyCommonClassNames.DEFAULT_BASE_CLASS_NAME)) {
            continue;
          }
        }
      }
      filtered.add(result);
    }

    return ContainerUtil.toArray(filtered, new GroovyResolveResult[filtered.size()]);
  }
Example #13
0
  static String calcClassDisplayName(final PsiClass aClass) {
    final String qName = aClass.getQualifiedName();
    if (qName != null) {
      return qName;
    }
    final PsiClass parent = PsiTreeUtil.getParentOfType(aClass, PsiClass.class, true);
    if (parent == null) {
      return null;
    }

    final String name = aClass.getName();
    if (name != null) {
      return calcClassDisplayName(parent) + "$" + name;
    }

    final Ref<Integer> classIndex = new Ref<Integer>(0);
    try {
      parent.accept(
          new JavaRecursiveElementVisitor() {
            public void visitAnonymousClass(PsiAnonymousClass cls) {
              classIndex.set(classIndex.get() + 1);
              if (aClass.equals(cls)) {
                throw new ProcessCanceledException();
              }
            }
          });
    } catch (ProcessCanceledException ignored) {
    }
    return calcClassDisplayName(parent) + "$" + classIndex.get();
  }
  public static void addImportForItem(InsertionContext context, PsiClass aClass) {
    if (aClass.getQualifiedName() == null) return;
    PsiFile file = context.getFile();

    int startOffset = context.getStartOffset();
    int tail = context.getTailOffset();
    int newTail = JavaCompletionUtil.insertClassReference(aClass, file, startOffset, tail);
    if (newTail > context.getDocument().getTextLength() || newTail < 0) {
      LOG.error(
          LogMessageEx.createEvent(
              "Invalid offset after insertion ",
              "offset="
                  + newTail
                  + "\n"
                  + "start="
                  + startOffset
                  + "\n"
                  + "tail="
                  + tail
                  + "\n"
                  + "file.length="
                  + file.getTextLength()
                  + "\n"
                  + "document="
                  + context.getDocument()
                  + "\n"
                  + DebugUtil.currentStackTrace(),
              AttachmentFactory.createAttachment(context.getDocument())));
      return;
    }
    context.setTailOffset(newTail);
    JavaCompletionUtil.shortenReference(file, context.getStartOffset());
    PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
  }
 public AlternativeSourceNotificationPanel(
     ComboBoxClassElement[] alternatives,
     final PsiClass aClass,
     final Project project,
     final VirtualFile file) {
   setText(
       DebuggerBundle.message(
           "editor.notification.alternative.source", aClass.getQualifiedName()));
   final ComboBox switcher = new ComboBox(alternatives);
   switcher.addActionListener(
       new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
           FileEditorManager.getInstance(project).closeFile(file);
           PsiClass item = ((ComboBoxClassElement) switcher.getSelectedItem()).myClass;
           item = (PsiClass) item.getNavigationElement(); // go through compiled
           DebuggerUtilsEx.setAlternativeSource(file, item.getContainingFile().getVirtualFile());
           item.navigate(true);
           XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession();
           if (session != null) {
             session.updateExecutionPosition();
           }
         }
       });
   myLinksPanel.add(switcher);
 }
 @Override
 public boolean isReferenceTo(PsiElement element) {
   if (!(element instanceof PsiClass)) return false;
   PsiClass aClass = (PsiClass) element;
   return myCanonicalText.equals(aClass.getQualifiedName())
       || getManager().areElementsEquivalent(resolve(), element);
 }
 @Override
 public void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiIdentifier name = (PsiIdentifier) descriptor.getPsiElement();
   final PsiReferenceExpression expression = (PsiReferenceExpression) name.getParent();
   if (expression == null) {
     return;
   }
   final PsiMethodCallExpression call = (PsiMethodCallExpression) expression.getParent();
   final String methodName = expression.getReferenceName();
   if (call == null) {
     return;
   }
   final PsiMethod method = call.resolveMethod();
   if (method == null) {
     return;
   }
   final PsiClass containingClass = method.getContainingClass();
   final PsiExpressionList argumentList = call.getArgumentList();
   if (containingClass == null) {
     return;
   }
   final String containingClassName = containingClass.getQualifiedName();
   final String argText = argumentList.getText();
   PsiReplacementUtil.replaceExpressionAndShorten(
       call, containingClassName + '.' + methodName + argText);
 }
Example #18
0
 @NotNull
 public static PsiElement[] findSuperElements(@NotNull PsiElement element) {
   if (element instanceof PsiClass) {
     PsiClass aClass = (PsiClass) element;
     List<PsiClass> allSupers = new ArrayList<>(Arrays.asList(aClass.getSupers()));
     for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext(); ) {
       PsiClass superClass = iterator.next();
       if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName()))
         iterator.remove();
     }
     return allSupers.toArray(new PsiClass[allSupers.size()]);
   }
   if (element instanceof PsiMethod) {
     PsiMethod method = (PsiMethod) element;
     if (method.isConstructor()) {
       PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
       if (constructorInSuper != null) {
         return new PsiMethod[] {constructorInSuper};
       }
     } else {
       PsiMethod[] superMethods = method.findSuperMethods(false);
       if (superMethods.length == 0) {
         PsiMethod superMethod = getSiblingInheritedViaSubClass(method);
         if (superMethod != null) {
           superMethods = new PsiMethod[] {superMethod};
         }
       }
       return superMethods;
     }
   }
   return PsiElement.EMPTY_ARRAY;
 }
  private void collectUncaughtExceptions(@NotNull PsiMethod method) {
    if (isExternalOverride()) return;
    if (getRefManager().isOfflineView()) return;
    @NonNls final String name = method.getName();
    if (getOwnerClass().isTestCase() && name.startsWith("test")) return;

    if (getSuperMethods().isEmpty()) {
      PsiClassType[] throwsList = method.getThrowsList().getReferencedTypes();
      if (throwsList.length > 0) {
        myUnThrownExceptions =
            throwsList.length == 1
                ? new SmartList<String>()
                : new ArrayList<String>(throwsList.length);
        for (final PsiClassType type : throwsList) {
          PsiClass aClass = type.resolve();
          String fqn = aClass == null ? null : aClass.getQualifiedName();
          if (fqn != null) {
            myUnThrownExceptions.add(fqn);
          }
        }
      }
    }

    final PsiCodeBlock body = method.getBody();
    if (body == null) return;

    final Collection<PsiClassType> exceptionTypes =
        ExceptionUtil.collectUnhandledExceptions(body, method, false);
    for (final PsiClassType exceptionType : exceptionTypes) {
      updateThrowsList(exceptionType);
    }
  }
  public void testCreateConfiguration() throws IOException, ExecutionException {
    Module module1 = getModule1();
    PsiClass psiClass = findTestA(module1);
    JUnitConfiguration configuration = createConfiguration(psiClass);
    assertEquals(
        Collections.singleton(module1), ContainerUtilRt.newHashSet(configuration.getModules()));
    checkClassName(psiClass.getQualifiedName(), configuration);
    assertEquals(psiClass.getName(), configuration.getName());
    checkTestObject(JUnitConfiguration.TEST_CLASS, configuration);
    Module module2 = getModule2();
    Assertion.compareUnordered(new Module[] {module1, module2}, configuration.getValidModules());

    PsiClass innerTest = findClass(module1, INNER_TEST_NAME);
    configuration =
        createJUnitConfiguration(
            innerTest, TestClassConfigurationProducer.class, new MapDataContext());
    checkClassName(RT_INNER_TEST_NAME, configuration);
    checkCanRun(configuration);

    PsiMethod[] testMethod = innerTest.findMethodsByName("test", false);
    assertEquals(1, testMethod.length);
    configuration = createConfiguration(testMethod[0]);
    checkClassName(RT_INNER_TEST_NAME, configuration);
    checkMethodName("test", configuration);
    checkTestObject(JUnitConfiguration.TEST_METHOD, configuration);
    checkCanRun(configuration);

    PsiMethod mainMethod = innerTest.findMethodsByName("main", false)[0];
    ApplicationConfiguration appConfiguration = createConfiguration(mainMethod);
    assertEquals(RT_INNER_TEST_NAME, appConfiguration.MAIN_CLASS_NAME);
    checkCanRun(configuration);
  }
  private void parseProperties(PsiMethod method, JavaElementArrangementEntry entry) {
    if (!myGroupingRules.contains(StdArrangementTokens.Grouping.GETTERS_AND_SETTERS)) {
      return;
    }

    String propertyName = null;
    boolean getter = true;
    if (PropertyUtil.isSimplePropertyGetter(method)) {
      propertyName = PropertyUtil.getPropertyNameByGetter(method);
    } else if (PropertyUtil.isSimplePropertySetter(method)) {
      propertyName = PropertyUtil.getPropertyNameBySetter(method);
      getter = false;
    }

    if (propertyName == null) {
      return;
    }

    PsiClass containingClass = method.getContainingClass();
    String className = null;
    if (containingClass != null) {
      className = containingClass.getQualifiedName();
    }
    if (className == null) {
      className = NULL_CONTENT;
    }

    if (getter) {
      myInfo.registerGetter(propertyName, className, entry);
    } else {
      myInfo.registerSetter(propertyName, className, entry);
    }
  }
 public void testEnum() throws Exception {
   setupLoadingFilter();
   final PsiClass enumClass =
       myJavaFacade.findClass("enums.OurEnum", GlobalSearchScope.moduleScope(myModule));
   assertNotNull(enumClass);
   assertTrue(enumClass.isEnum());
   final PsiClass superClass = enumClass.getSuperClass();
   assertNotNull(superClass);
   assertEquals("java.lang.Enum", superClass.getQualifiedName());
   assertTrue(enumClass.isInheritor(superClass, false));
   final PsiClassType[] superTypes = enumClass.getSuperTypes();
   assertEquals(1, superTypes.length);
   assertEquals("java.lang.Enum<enums.OurEnum>", superTypes[0].getCanonicalText());
   final PsiClass[] supers = enumClass.getSupers();
   assertEquals(1, supers.length);
   assertEquals("java.lang.Enum", supers[0].getQualifiedName());
   final PsiClassType[] extendsListTypes = enumClass.getExtendsListTypes();
   assertEquals(1, extendsListTypes.length);
   assertEquals("java.lang.Enum<enums.OurEnum>", extendsListTypes[0].getCanonicalText());
   final PsiSubstitutor superClassSubstitutor =
       TypeConversionUtil.getSuperClassSubstitutor(superClass, enumClass, PsiSubstitutor.EMPTY);
   assertEquals(
       "java.lang.Enum<enums.OurEnum>",
       myJavaFacade
           .getElementFactory()
           .createType(superClass, superClassSubstitutor)
           .getCanonicalText());
   teardownLoadingFilter();
 }
 public ClassUsageGroup(@NotNull PsiClass aClass) {
   myQName = aClass.getQualifiedName();
   myText = createText(aClass);
   myClassPointer =
       SmartPointerManager.getInstance(aClass.getProject()).createSmartPsiElementPointer(aClass);
   myIcon = aClass.getIcon(Iconable.ICON_FLAG_VISIBILITY | Iconable.ICON_FLAG_READ_STATUS);
 }
  @Nullable
  private String verifyInnerClassDestination() {
    PsiClass targetClass = findTargetClass();
    if (targetClass == null) return null;

    for (PsiElement element : myElementsToMove) {
      if (PsiTreeUtil.isAncestor(element, targetClass, false)) {
        return RefactoringBundle.message("move.class.to.inner.move.to.self.error");
      }
      final Language targetClassLanguage = targetClass.getLanguage();
      if (!element.getLanguage().equals(targetClassLanguage)) {
        return RefactoringBundle.message(
            "move.to.different.language",
            UsageViewUtil.getType(element),
            ((PsiClass) element).getQualifiedName(),
            targetClass.getQualifiedName());
      }
      if (element.getLanguage().equals(Language.findLanguageByID("Groovy"))) {
        return RefactoringBundle.message("dont.support.inner.classes", "Groovy");
      }
    }

    while (targetClass != null) {
      if (targetClass.getContainingClass() != null
          && !targetClass.hasModifierProperty(PsiModifier.STATIC)) {
        return RefactoringBundle.message("move.class.to.inner.nonstatic.error");
      }
      targetClass = targetClass.getContainingClass();
    }

    return null;
  }
 @Override
 public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
   super.visitReferenceElement(reference);
   if (referenceFound) {
     return;
   }
   final String text = reference.getText();
   if (text.indexOf((int) '.') >= 0 || !name.equals(text)) {
     return;
   }
   final PsiElement element = reference.resolve();
   if (!(element instanceof PsiClass) || element instanceof PsiTypeParameter) {
     return;
   }
   final PsiClass aClass = (PsiClass) element;
   final String testClassName = aClass.getName();
   final String testClassQualifiedName = aClass.getQualifiedName();
   if (testClassQualifiedName == null
       || testClassName == null
       || testClassQualifiedName.equals(fullyQualifiedName)
       || !testClassName.equals(name)) {
     return;
   }
   referenceFound = true;
 }
  @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;
  }
  @NotNull
  public static PsiClassType[] getExtendsListTypes(GrTypeDefinition grType) {
    final PsiClassType[] extendsTypes = getReferenceListTypes(grType.getExtendsClause());
    if (grType.isInterface()) {
      return extendsTypes;
    }

    for (PsiClassType type : extendsTypes) {
      final PsiClass superClass = type.resolve();
      if (superClass instanceof GrTypeDefinition && !superClass.isInterface()
          || superClass != null
              && GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT.equals(
                  superClass.getQualifiedName())) {
        return extendsTypes;
      }
    }

    PsiClass grObSupport =
        GroovyPsiManager.getInstance(grType.getProject())
            .findClassWithCache(
                GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT, grType.getResolveScope());
    if (grObSupport != null) {
      final PsiClassType type =
          JavaPsiFacade.getInstance(grType.getProject())
              .getElementFactory()
              .createType(grObSupport);
      return ArrayUtil.append(extendsTypes, type, PsiClassType.ARRAY_FACTORY);
    }
    return extendsTypes;
  }
 @Nullable
 private static String getCannotRefactorMessage(PsiMember member) {
   if (member == null) {
     return RefactoringBundle.message("locate.caret.inside.a.method");
   }
   if (member instanceof PsiMethod) {
     if (((PsiMethod) member).isConstructor()) {
       return RefactoringBundle.message("replace.with.method.call.does.not.work.for.constructors");
     }
     final PsiCodeBlock body = ((PsiMethod) member).getBody();
     if (body == null) {
       return RefactoringBundle.message("method.does.not.have.a.body", member.getName());
     }
     final PsiStatement[] statements = body.getStatements();
     if (statements.length == 0) {
       return RefactoringBundle.message("method.has.an.empty.body", member.getName());
     }
   } else if (member instanceof PsiField) {
     final PsiField field = (PsiField) member;
     if (field.getInitializer() == null) {
       return "Field " + member.getName() + " doesn't have initializer";
     }
     final PsiClass containingClass = field.getContainingClass();
     if (!field.hasModifierProperty(PsiModifier.FINAL)
         || !field.hasModifierProperty(PsiModifier.STATIC)
         || containingClass == null
         || containingClass.getQualifiedName() == null) {
       return "Replace Duplicates works with constants only";
     }
   } else {
     return "Caret should be inside method or constant";
   }
   return null;
 }
  private static List<FunctionDescriptor> getSuperFunctionsForMethod(
      @NotNull PsiMethodWrapper method,
      @NotNull BindingTrace trace,
      @NotNull ClassDescriptor containingClass) {
    List<FunctionDescriptor> superFunctions = Lists.newArrayList();

    Map<ClassDescriptor, JetType> superclassToSupertype =
        getSuperclassToSupertypeMap(containingClass);

    Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>> superclassToFunctions =
        getSuperclassToFunctionsMultimap(method, trace.getBindingContext(), containingClass);

    for (HierarchicalMethodSignature superSignature :
        method.getPsiMethod().getHierarchicalMethodSignature().getSuperSignatures()) {
      PsiMethod superMethod = superSignature.getMethod();

      PsiClass psiClass = superMethod.getContainingClass();
      assert psiClass != null;
      String classFqNameString = psiClass.getQualifiedName();
      assert classFqNameString != null;
      FqName classFqName = new FqName(classFqNameString);

      if (!JavaToKotlinClassMap.getInstance().mapPlatformClass(classFqName).isEmpty()) {
        for (FunctionDescriptor superFun :
            JavaToKotlinMethodMap.INSTANCE.getFunctions(superMethod, containingClass)) {
          superFunctions.add(substituteSuperFunction(superclassToSupertype, superFun));
        }
        continue;
      }

      DeclarationDescriptor superFun =
          superMethod instanceof JetClsMethod
              ? trace.get(
                  BindingContext.DECLARATION_TO_DESCRIPTOR,
                  ((JetClsMethod) superMethod).getOrigin())
              : findSuperFunction(superclassToFunctions.get(classFqName), superMethod);
      if (superFun == null) {
        reportCantFindSuperFunction(method);
        continue;
      }

      assert superFun instanceof FunctionDescriptor : superFun.getClass().getName();

      superFunctions.add(
          substituteSuperFunction(superclassToSupertype, (FunctionDescriptor) superFun));
    }

    // sorting for diagnostic stability
    Collections.sort(
        superFunctions,
        new Comparator<FunctionDescriptor>() {
          @Override
          public int compare(FunctionDescriptor fun1, FunctionDescriptor fun2) {
            FqNameUnsafe fqName1 = getFQName(fun1.getContainingDeclaration());
            FqNameUnsafe fqName2 = getFQName(fun2.getContainingDeclaration());
            return fqName1.getFqName().compareTo(fqName2.getFqName());
          }
        });
    return superFunctions;
  }
 public String toString() {
   @NonNls StringBuilder buffer = new StringBuilder();
   final Set<Map.Entry<PsiTypeParameter, PsiType>> set = mySubstitutionMap.entrySet();
   for (Map.Entry<PsiTypeParameter, PsiType> entry : set) {
     final PsiTypeParameter typeParameter = entry.getKey();
     buffer.append(typeParameter.getName());
     final PsiElement owner = typeParameter.getOwner();
     if (owner instanceof PsiClass) {
       buffer.append(" of ");
       buffer.append(((PsiClass) owner).getQualifiedName());
     } else if (owner instanceof PsiMethod) {
       buffer.append(" of ");
       buffer.append(((PsiMethod) owner).getName());
       buffer.append(" in ");
       PsiClass aClass = ((PsiMethod) owner).getContainingClass();
       buffer.append(aClass != null ? aClass.getQualifiedName() : "<no class>");
     }
     buffer.append(" -> ");
     if (entry.getValue() != null) {
       buffer.append(entry.getValue().getCanonicalText());
     } else {
       buffer.append("null");
     }
     buffer.append('\n');
   }
   return buffer.toString();
 }