@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;
  }
 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);
   }
 }
  public static PsiType eliminateWildcards(PsiType type, final boolean eliminateInTypeArguments) {
    if (eliminateInTypeArguments && type instanceof PsiClassType) {
      PsiClassType classType = (PsiClassType) type;
      JavaResolveResult resolveResult = classType.resolveGenerics();
      PsiClass aClass = (PsiClass) resolveResult.getElement();
      if (aClass != null) {
        PsiManager manager = aClass.getManager();
        PsiTypeParameter[] typeParams = aClass.getTypeParameters();
        Map<PsiTypeParameter, PsiType> map = new HashMap<PsiTypeParameter, PsiType>();
        for (PsiTypeParameter typeParam : typeParams) {
          PsiType substituted = resolveResult.getSubstitutor().substitute(typeParam);
          if (substituted instanceof PsiWildcardType) {
            substituted = ((PsiWildcardType) substituted).getBound();
            if (substituted == null)
              substituted = TypeConversionUtil.typeParameterErasure(typeParam);
          }
          map.put(typeParam, substituted);
        }

        PsiElementFactory factory =
            JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
        PsiSubstitutor substitutor = factory.createSubstitutor(map);
        type = factory.createType(aClass, substitutor);
      }
    } else if (type instanceof PsiArrayType) {
      return eliminateWildcards(((PsiArrayType) type).getComponentType(), false).createArrayType();
    } else if (type instanceof PsiWildcardType) {
      final PsiType bound = ((PsiWildcardType) type).getBound();
      return bound != null ? bound : ((PsiWildcardType) type).getExtendsBound(); // object
    } else if (type instanceof PsiCapturedWildcardType && !eliminateInTypeArguments) {
      return eliminateWildcards(
          ((PsiCapturedWildcardType) type).getWildcard(), eliminateInTypeArguments);
    }
    return type;
  }
  @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 boolean checkAccessibility(final PsiClass aClass) {
    // We don't care about accessibility in javadoc
    if (JavaResolveUtil.isInJavaDoc(myPlace)) {
      return true;
    }

    if (PsiImplUtil.isInServerPage(aClass.getContainingFile())) {
      PsiFile file = FileContextUtil.getContextFile(myPlace);
      if (PsiImplUtil.isInServerPage(file)) {
        return true;
      }
    }

    boolean accessible = true;
    if (aClass instanceof PsiTypeParameter) {
      accessible = !myStaticContext;
    }

    PsiManager manager = aClass.getManager();
    if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) {
      PsiElement parent = aClass.getParent();
      while (true) {
        PsiElement parentScope = parent.getParent();
        if (parentScope instanceof PsiJavaFile) break;
        parent = parentScope;
        if (!(parentScope instanceof PsiClass)) break;
      }
      if (parent instanceof PsiDeclarationStatement) {
        parent = parent.getParent();
      }
      accessible = false;
      for (PsiElement placeParent = myPlace;
          placeParent != null;
          placeParent = placeParent.getContext()) {
        if (manager.areElementsEquivalent(placeParent, parent)) accessible = true;
      }
    }
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
      accessible = false;
      if (myPlace != null && facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = true;
      } else {
        if (aClass.getContainingClass() != null) {
          accessible =
              myAccessClass == null
                  || myPlace != null
                      && facade.getResolveHelper().isAccessible(aClass, myPlace, myAccessClass);
        }
      }
    }
    if (aClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
      if (myPlace == null || !facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = false;
      }
    }
    return accessible;
  }
  public static boolean isClassEquivalentTo(@NotNull PsiClass aClass, PsiElement another) {
    if (aClass == another) return true;
    if (!(another instanceof PsiClass)) return false;
    String name1 = aClass.getName();
    if (name1 == null) return false;
    if (!another.isValid()) return false;
    String name2 = ((PsiClass) another).getName();
    if (name2 == null) return false;
    if (name1.hashCode() != name2.hashCode()) return false;
    if (!name1.equals(name2)) return false;
    String qName1 = aClass.getQualifiedName();
    String qName2 = ((PsiClass) another).getQualifiedName();
    if (qName1 == null || qName2 == null) {
      //noinspection StringEquality
      if (qName1 != qName2) return false;

      if (aClass instanceof PsiTypeParameter && another instanceof PsiTypeParameter) {
        PsiTypeParameter p1 = (PsiTypeParameter) aClass;
        PsiTypeParameter p2 = (PsiTypeParameter) another;

        return p1.getIndex() == p2.getIndex()
            && aClass.getManager().areElementsEquivalent(p1.getOwner(), p2.getOwner());
      } else {
        return false;
      }
    }
    if (qName1.hashCode() != qName2.hashCode() || !qName1.equals(qName2)) {
      return false;
    }

    if (originalElement(aClass).equals(originalElement((PsiClass) another))) {
      return true;
    }

    final PsiFile file1 = aClass.getContainingFile().getOriginalFile();
    final PsiFile file2 = another.getContainingFile().getOriginalFile();

    // see com.intellij.openapi.vcs.changes.PsiChangeTracker
    // see com.intellij.psi.impl.PsiFileFactoryImpl#createFileFromText(CharSequence,PsiFile)
    final PsiFile original1 = file1.getUserData(PsiFileFactory.ORIGINAL_FILE);
    final PsiFile original2 = file2.getUserData(PsiFileFactory.ORIGINAL_FILE);
    if (original1 == original2 && original1 != null
        || original1 == file2
        || original2 == file1
        || file1 == file2) {
      return compareClassSeqNumber(aClass, (PsiClass) another);
    }

    final FileIndexFacade fileIndex =
        ServiceManager.getService(file1.getProject(), FileIndexFacade.class);
    final VirtualFile vfile1 = file1.getViewProvider().getVirtualFile();
    final VirtualFile vfile2 = file2.getViewProvider().getVirtualFile();
    boolean lib1 = fileIndex.isInLibraryClasses(vfile1);
    boolean lib2 = fileIndex.isInLibraryClasses(vfile2);

    return (fileIndex.isInSource(vfile1) || lib1) && (fileIndex.isInSource(vfile2) || lib2);
  }
Example #7
0
 public boolean isAvailable(
     @NotNull final Project project, final Editor editor, final PsiFile file) {
   return myMethod != null
       && myMethod.isValid()
       && myClass != null
       && myClass.isValid()
       && myClass.getManager().isInProject(myClass)
       && myText != null
       && MethodSignatureUtil.findMethodBySignature(myClass, myMethod, false) == null;
 }
  @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);
  }
 @Override
 public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
   return myClass != null
       && myClass.isValid()
       && myClass.getManager().isInProject(myClass)
       && myVariable != null
       && myVariable.isValid()
       && myFixType != -1
       && !getVariablesToFix().isEmpty()
       && !inOwnInitializer(myVariable, myClass);
 }
 public PsiImmediateClassType(
     @NotNull PsiClass aClass,
     @NotNull PsiSubstitutor substitutor,
     @Nullable LanguageLevel level,
     @NotNull PsiAnnotation... annotations) {
   super(level, annotations);
   myClass = aClass;
   myManager = aClass.getManager();
   mySubstitutor = substitutor;
   assert substitutor.isValid();
 }
  protected <Psi extends PsiElement> void processIntern(
      @NotNull PsiClass psiClass, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) {
    PsiElementFactory psiElementFactory = psiElementFactory(psiClass);
    PsiManager manager = psiClass.getContainingFile().getManager();

    PsiType psiProviderType = psiElementFactory.createTypeFromText(RMI_PROVIDER_TYPE, psiClass);
    LombokLightFieldBuilder providerField =
        LombokPsiElementFactory.getInstance()
            .createLightField(manager, RMI_PROVIDER_FIELD_NAME, psiProviderType)
            .withContainingClass(psiClass)
            .withModifier(PsiModifier.PRIVATE)
            .withNavigationElement(psiAnnotation);
    PsiExpression initializer =
        psiElementFactory.createExpressionFromText(
            String.format(RMI_PROVIDER_FIELD_INITIALIZER), psiClass);
    providerField.setInitializer(initializer);

    LombokLightMethodBuilder method =
        LombokPsiElementFactory.getInstance()
            .createLightMethod(psiClass.getManager(), METHOD_GET_RMI_PROVIDER)
            .withMethodReturnType(psiProviderType)
            .withContainingClass(psiClass)
            .withModifier(PsiModifier.PUBLIC)
            .withNavigationElement(psiAnnotation);
    target.add((Psi) method);

    method =
        LombokPsiElementFactory.getInstance()
            .createLightMethod(psiClass.getManager(), METHOD_SET_RMI_PROVIDER)
            .withMethodReturnType(PsiPrimitiveTypeFactory.getInstance().getVoidType())
            .withContainingClass(psiClass)
            .withParameter(PROVIDER, psiProviderType)
            .withModifier(PsiModifier.PUBLIC)
            .withNavigationElement(psiAnnotation);
    target.add((Psi) method);

    for (MethodDescriptor methodDesc : METHODS) {
      target.add((Psi) PsiMethodUtil.createMethod(psiClass, methodDesc.signature, psiAnnotation));
    }
  }
 @Nullable
 public static HighlightInfo checkCyclicMemberType(PsiTypeElement typeElement, PsiClass aClass) {
   LOG.assertTrue(aClass.isAnnotationType());
   PsiType type = typeElement.getType();
   final Set<PsiClass> checked = new HashSet<PsiClass>();
   if (cyclicDependencies(aClass, type, checked, aClass.getManager())) {
     String description = JavaErrorMessages.message("annotation.cyclic.element.type");
     return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
         .range(typeElement)
         .descriptionAndTooltip(description)
         .create();
   }
   return null;
 }
Example #13
0
 public static @Nullable PsiType resolveMethod(
     @Nullable PsiType type, String methodName, @NotNull PsiType... argTypes) {
   if (!(type instanceof PsiClassType) || methodName == null) return null;
   for (PsiType a : argTypes) if (a == null) return null;
   PsiClassType clas = (PsiClassType) type;
   PsiSubstitutor subst = clas.resolveGenerics().getSubstitutor();
   PsiClass psiClass = clas.resolve();
   if (psiClass == null) return null;
   LightMethodBuilder method =
       new LightMethodBuilder(psiClass.getManager(), JavaLanguage.INSTANCE, methodName);
   for (PsiType a : argTypes) method.addParameter("_", a);
   PsiMethod m = psiClass.findMethodBySignature(method, true);
   return m == null ? null : subst.substitute(m.getReturnType());
 }
 private static boolean isSafeToShortenReference(
     final String referenceText, final PsiElement psiReference, final PsiClass refClass) {
   final PsiManager manager = refClass.getManager();
   final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
   final PsiResolveHelper helper = facade.getResolveHelper();
   if (manager.areElementsEquivalent(
       refClass, helper.resolveReferencedClass(referenceText, psiReference))) {
     PsiElement parent = psiReference.getParent();
     if (parent instanceof PsiJavaCodeReferenceElement
         && parent.getParent() instanceof PsiNewExpression) return true;
     return helper.resolveReferencedVariable(referenceText, psiReference) == null;
   }
   return false;
 }
  @Override
  public boolean isAvailable(
      @NotNull Project project,
      @NotNull PsiFile file,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiClass myClass = (PsiClass) startElement;

    return myMethodPrototype != null
        && myMethodPrototype.isValid()
        && myClass.isValid()
        && myClass.getManager().isInProject(myClass)
        && myText != null
        && MethodSignatureUtil.findMethodBySignature(myClass, myMethodPrototype, false) == null;
  }
  @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 static void addFieldsUsages(
     final PsiClass aClass,
     final Processor<UsageInfo> results,
     final JavaClassFindUsagesOptions options) {
   if (options.isIncludeInherited) {
     final PsiManager manager = aClass.getManager();
     PsiField[] fields = aClass.getAllFields();
     FieldsLoop:
     for (int i = 0; i < fields.length; i++) {
       final PsiField field = fields[i];
       // filter hidden fields
       for (int j = 0; j < i; j++) {
         if (Comparing.strEqual(field.getName(), fields[j].getName())) continue FieldsLoop;
       }
       final PsiClass fieldClass = field.getContainingClass();
       if (manager.areElementsEquivalent(fieldClass, aClass)) {
         addElementUsages(fields[i], results, options);
       } else {
         ReferencesSearch.search(
                 new ReferencesSearch.SearchParameters(
                     field, options.searchScope, false, options.fastTrack))
             .forEach(
                 new ReadActionProcessor<PsiReference>() {
                   @Override
                   public boolean processInReadAction(final PsiReference reference) {
                     addResultFromReference(
                         reference, fieldClass, manager, aClass, results, options);
                     return true;
                   }
                 });
       }
     }
   } else {
     PsiField[] fields =
         ApplicationManager.getApplication()
             .runReadAction(
                 new Computable<PsiField[]>() {
                   @Override
                   public PsiField[] compute() {
                     return aClass.getFields();
                   }
                 });
     for (PsiField field : fields) {
       addElementUsages(field, results, options);
     }
   }
 }
 private void copyToFinal() throws IncorrectOperationException {
   PsiManager psiManager = myClass.getManager();
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
   PsiExpression initializer = factory.createExpressionFromText(myVariable.getName(), myClass);
   String newName = suggestNewName(psiManager.getProject(), myVariable);
   PsiType type = myVariable.getType();
   PsiDeclarationStatement copyDecl =
       factory.createVariableDeclarationStatement(newName, type, initializer);
   PsiVariable newVariable = (PsiVariable) copyDecl.getDeclaredElements()[0];
   PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
   PsiElement statement = getStatementToInsertBefore();
   if (statement == null) return;
   statement.getParent().addBefore(copyDecl, statement);
   PsiExpression newExpression = factory.createExpressionFromText(newName, myVariable);
   replaceReferences(myClass, myVariable, newExpression);
 }
  private List<PsiClass> calculateInterfacesSupported() {
    final List<PsiClass> out = new ArrayList<PsiClass>();
    final PsiClass[] supers = sourceClass.getSupers();
    for (PsiClass superClass : supers) {
      if (!superClass.isInterface()) {
        continue;
      }
      final PsiMethod[] superclassMethods = superClass.getMethods();
      if (superclassMethods.length == 0) {
        continue;
      }
      boolean allMethodsCovered = true;

      for (PsiMethod method : superclassMethods) {
        boolean isCovered = false;
        for (PsiMethod movedMethod : methods) {
          if (isSuperMethod(method, movedMethod)) {
            isCovered = true;
            break;
          }
        }
        if (!isCovered) {
          allMethodsCovered = false;
          break;
        }
      }
      if (allMethodsCovered) {
        out.add(superClass);
      }
    }
    final Project project = sourceClass.getProject();
    final PsiManager manager = sourceClass.getManager();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    if (usesDefaultSerialization(sourceClass)) {
      final PsiClass serializable =
          JavaPsiFacade.getInstance(manager.getProject()).findClass("java.io.Serializable", scope);
      out.add(serializable);
    }
    if (usesDefaultClone(sourceClass)) {
      final PsiClass cloneable =
          JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Cloneable", scope);
      out.add(cloneable);
    }
    return out;
  }
  private static PsiTypeLookupItem doCreateItem(
      final PsiType type,
      PsiElement context,
      int bracketsCount,
      boolean diamond,
      InsertHandler<PsiTypeLookupItem> importFixer) {
    if (type instanceof PsiClassType) {
      PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType) type).resolveGenerics();
      final PsiClass psiClass = classResolveResult.getElement();

      if (psiClass != null) {
        String name = psiClass.getName();
        if (name != null) {
          final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();

          PsiClass resolved =
              JavaPsiFacade.getInstance(psiClass.getProject())
                  .getResolveHelper()
                  .resolveReferencedClass(name, context);

          Set<String> allStrings = new HashSet<String>();
          allStrings.add(name);
          if (!psiClass.getManager().areElementsEquivalent(resolved, psiClass)
              && !PsiUtil.isInnerClass(psiClass)) {
            // inner class name should be shown qualified if its not accessible by single name
            PsiClass aClass = psiClass.getContainingClass();
            while (aClass != null && !PsiUtil.isInnerClass(aClass) && aClass.getName() != null) {
              name = aClass.getName() + '.' + name;
              allStrings.add(name);
              aClass = aClass.getContainingClass();
            }
          }

          PsiTypeLookupItem item =
              new PsiTypeLookupItem(
                  psiClass, name, diamond, bracketsCount, importFixer, substitutor);
          item.addLookupStrings(ArrayUtil.toStringArray(allStrings));
          return item;
        }
      }
    }
    return new PsiTypeLookupItem(
        type, type.getPresentableText(), false, bracketsCount, importFixer, PsiSubstitutor.EMPTY);
  }
  private void buildDelegate() {
    final PsiManager manager = sourceClass.getManager();
    final PsiElementFactory factory =
        JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    @NonNls final StringBuilder fieldBuffer = new StringBuilder();
    final String delegateVisibility = calculateDelegateVisibility();
    if (delegateVisibility.length() > 0) fieldBuffer.append(delegateVisibility).append(' ');
    fieldBuffer.append("final ");
    final String fullyQualifiedName = getQualifiedName();
    fieldBuffer.append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append(' ');
    fieldBuffer.append(delegateFieldName);
    fieldBuffer.append(" = new ").append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append('(');
    if (requiresBackpointer) {
      fieldBuffer.append("this");
    }

    fieldBuffer.append(");");
    try {
      final String fieldString = fieldBuffer.toString();
      final PsiField field = factory.createFieldFromText(fieldString, sourceClass);
      final PsiElement newField = sourceClass.add(field);
      codeStyleManager.reformat(
          JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(newField));
    } catch (IncorrectOperationException e) {
      logger.error(e);
    }
  }
 private static boolean usesDefaultClone(PsiClass aClass) {
   final Project project = aClass.getProject();
   final PsiManager manager = aClass.getManager();
   final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
   final PsiClass cloneable =
       JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Cloneable", scope);
   if (!InheritanceUtil.isInheritorOrSelf(aClass, cloneable, true)) {
     return false;
   }
   final PsiMethod[] methods = aClass.findMethodsByName("clone", false);
   for (PsiMethod method : methods) {
     final PsiParameterList parameterList = method.getParameterList();
     final PsiParameter[] parameters = parameterList.getParameters();
     if (parameters.length == 0) {
       return false;
     }
   }
   return true;
 }
 private static void addMethodsUsages(
     final PsiClass aClass,
     final Processor<UsageInfo> results,
     final JavaClassFindUsagesOptions options) {
   if (options.isIncludeInherited) {
     final PsiManager manager = aClass.getManager();
     PsiMethod[] methods = aClass.getAllMethods();
     MethodsLoop:
     for (int i = 0; i < methods.length; i++) {
       final PsiMethod method = methods[i];
       // filter overriden methods
       MethodSignature methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
       for (int j = 0; j < i; j++) {
         if (methodSignature.equals(methods[j].getSignature(PsiSubstitutor.EMPTY)))
           continue MethodsLoop;
       }
       final PsiClass methodClass = method.getContainingClass();
       if (methodClass != null && manager.areElementsEquivalent(methodClass, aClass)) {
         addElementUsages(methods[i], results, options);
       } else {
         MethodReferencesSearch.search(
                 new MethodReferencesSearch.SearchParameters(
                     method, options.searchScope, true, options.fastTrack))
             .forEach(
                 new PsiReferenceProcessorAdapter(
                     new PsiReferenceProcessor() {
                       @Override
                       public boolean execute(PsiReference reference) {
                         addResultFromReference(
                             reference, methodClass, manager, aClass, results, options);
                         return true;
                       }
                     }));
       }
     }
   } else {
     for (PsiMethod method : aClass.getMethods()) {
       addElementUsages(method, results, options);
     }
   }
 }
  public void invoke(
      @NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
    if (elements.length != 1) return;

    PsiElement element = elements[0];
    PsiClass aClass;
    PsiElement aMember = null;

    if (element instanceof PsiClass) {
      aClass = (PsiClass) element;
    } else if (element instanceof PsiMethod) {
      aClass = ((PsiMethod) element).getContainingClass();
      aMember = element;
    } else if (element instanceof PsiField) {
      aClass = ((PsiField) element).getContainingClass();
      aMember = element;
    } else return;

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return;
    MemberInfoStorage memberInfoStorage =
        new MemberInfoStorage(
            aClass,
            new MemberInfo.Filter<PsiMember>() {
              public boolean includeMember(PsiMember element) {
                return !(element instanceof PsiEnumConstant);
              }
            });
    List<MemberInfo> members = memberInfoStorage.getClassMemberInfos(aClass);
    PsiManager manager = aClass.getManager();

    for (MemberInfoBase<PsiMember> member : members) {
      if (manager.areElementsEquivalent(member.getMember(), aMember)) {
        member.setChecked(true);
        break;
      }
    }
    PushDownDialog dialog =
        new PushDownDialog(project, members.toArray(new MemberInfo[members.size()]), aClass);
    dialog.show();
  }
Example #25
0
  @Nullable
  private static Boolean isAssignableForNativeTypes(
      @NotNull PsiType lType, @NotNull PsiClassType rType, @NotNull PsiElement context) {
    if (!(lType instanceof PsiClassType)) return null;
    final PsiClassType.ClassResolveResult leftResult = ((PsiClassType) lType).resolveGenerics();
    final PsiClassType.ClassResolveResult rightResult = rType.resolveGenerics();
    final PsiClass leftClass = leftResult.getElement();
    PsiClass rightClass = rightResult.getElement();
    if (rightClass == null || leftClass == null) return null;

    if (!InheritanceUtil.isInheritorOrSelf(rightClass, leftClass, true)) return Boolean.FALSE;

    PsiSubstitutor rightSubstitutor = rightResult.getSubstitutor();

    if (!leftClass.hasTypeParameters()) return Boolean.TRUE;
    PsiSubstitutor leftSubstitutor = leftResult.getSubstitutor();

    if (!leftClass.getManager().areElementsEquivalent(leftClass, rightClass)) {
      rightSubstitutor =
          TypeConversionUtil.getSuperClassSubstitutor(leftClass, rightClass, rightSubstitutor);
      rightClass = leftClass;
    } else if (!rightClass.hasTypeParameters()) return Boolean.TRUE;

    Iterator<PsiTypeParameter> li = PsiUtil.typeParametersIterator(leftClass);
    Iterator<PsiTypeParameter> ri = PsiUtil.typeParametersIterator(rightClass);
    while (li.hasNext()) {
      if (!ri.hasNext()) return Boolean.FALSE;
      PsiTypeParameter lp = li.next();
      PsiTypeParameter rp = ri.next();
      final PsiType typeLeft = leftSubstitutor.substitute(lp);
      if (typeLeft == null) continue;
      final PsiType typeRight = rightSubstitutor.substituteWithBoundsPromotion(rp);
      if (typeRight == null) {
        return Boolean.TRUE;
      }
      if (!isAssignableWithoutConversions(typeLeft, typeRight, context)) return Boolean.FALSE;
    }
    return Boolean.TRUE;
  }
  private GdkMethodHolder(
      final PsiClass categoryClass, final boolean isStatic, final GlobalSearchScope scope) {
    myStatic = isStatic;
    myScope = scope;
    final MultiMap<String, PsiMethod> byName = new MultiMap<String, PsiMethod>();
    myPsiManager = categoryClass.getManager();
    for (PsiMethod m : categoryClass.getMethods()) {
      final PsiParameter[] params = m.getParameterList().getParameters();
      if (params.length == 0) continue;

      byName.putValue(m.getName(), m);
    }
    this.myOriginalMethodByType =
        new VolatileNotNullLazyValue<MultiMap<String, PsiMethod>>() {
          @NotNull
          @Override
          protected MultiMap<String, PsiMethod> compute() {
            MultiMap<String, PsiMethod> map = new MultiMap<String, PsiMethod>();
            for (PsiMethod method : byName.values()) {
              if (!method.hasModifierProperty(PsiModifier.PUBLIC)) continue;
              map.putValue(getCategoryTargetType(method).getCanonicalText(), method);
            }
            return map;
          }
        };

    myOriginalMethodsByNameAndType =
        new ConcurrentFactoryMap<String, MultiMap<String, PsiMethod>>() {
          @Override
          protected MultiMap<String, PsiMethod> create(String name) {
            MultiMap<String, PsiMethod> map = new MultiMap<String, PsiMethod>();
            for (PsiMethod method : byName.get(name)) {
              map.putValue(getCategoryTargetType(method).getCanonicalText(), method);
            }
            return map;
          }
        };
  }
  @Override
  public void processElement(
      @NotNull PsiClass parent, @NotNull PsiField psiField, @NotNull List<PsiElement> result) {
    LightMethodBuilder builder =
        new LightMethodBuilder(
            parent.getManager(), parent.getLanguage(), PropertyUtil.suggestSetterName(psiField));
    builder.setMethodReturnType(PsiType.VOID);
    builder.setContainingClass(parent);
    builder.setNavigationElement(psiField);

    builder.addParameter(psiField.getName(), psiField.getType());

    if (psiField.hasModifierProperty(PsiModifier.STATIC)) {
      builder.addModifier(PsiModifier.STATIC);
    }

    PsiAnnotation annotation = getAffectedAnnotation(psiField);

    LombokUtil.setAccessModifierFromAnnotation(
        annotation, builder, PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME);

    result.add(builder);
  }
 private static PsiClassType getEnumSuperType(
     @NotNull PsiClass psiClass, @NotNull PsiElementFactory factory) {
   PsiClassType superType;
   final PsiManager manager = psiClass.getManager();
   final PsiClass enumClass =
       JavaPsiFacade.getInstance(manager.getProject())
           .findClass("java.lang.Enum", psiClass.getResolveScope());
   if (enumClass == null) {
     try {
       superType = (PsiClassType) factory.createTypeFromText("java.lang.Enum", null);
     } catch (IncorrectOperationException e) {
       superType = null;
     }
   } else {
     final PsiTypeParameter[] typeParameters = enumClass.getTypeParameters();
     PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
     if (typeParameters.length == 1) {
       substitutor = substitutor.put(typeParameters[0], factory.createType(psiClass));
     }
     superType = new PsiImmediateClassType(enumClass, substitutor);
   }
   return superType;
 }
 private static boolean usesDefaultSerialization(PsiClass aClass) {
   final Project project = aClass.getProject();
   final PsiManager manager = aClass.getManager();
   final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
   final PsiClass serializable =
       JavaPsiFacade.getInstance(manager.getProject()).findClass("java.io.Serializable", scope);
   if (!InheritanceUtil.isInheritorOrSelf(aClass, serializable, true)) {
     return false;
   }
   final PsiMethod[] methods = aClass.findMethodsByName("writeObject", false);
   for (PsiMethod method : methods) {
     final PsiParameterList parameterList = method.getParameterList();
     final PsiParameter[] parameters = parameterList.getParameters();
     if (parameters.length == 1) {
       final PsiType type = parameters[0].getType();
       final String text = type.getCanonicalText();
       if ("java.io.DataOutputStream".equals(text)) {
         return false;
       }
     }
   }
   return true;
 }
  private static LookupItem doCreateItem(PsiType type, PsiElement context) {
    if (type instanceof PsiClassType) {
      PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType) type).resolveGenerics();
      final PsiClass psiClass = classResolveResult.getElement();
      final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
      final String text = type.getCanonicalText();
      String typeString = text;
      String typeParams = "";
      if (text.indexOf('<') > 0 && text.endsWith(">")) {
        typeString = text.substring(0, text.indexOf('<'));
        typeParams = text.substring(text.indexOf('<'));
      }

      String lookupString = text.substring(typeString.lastIndexOf('.') + 1);
      if (psiClass != null) {
        PsiClass resolved =
            JavaPsiFacade.getInstance(psiClass.getProject())
                .getResolveHelper()
                .resolveReferencedClass(psiClass.getName(), context);
        if (!psiClass.getManager().areElementsEquivalent(resolved, psiClass)) {
          // inner class name should be shown qualified if its not accessible by single name
          PsiClass aClass = psiClass;
          lookupString = "";
          while (aClass != null) {
            lookupString = aClass.getName() + (lookupString == "" ? "" : ".") + lookupString;
            aClass = aClass.getContainingClass();
          }
          lookupString += typeParams;
        }
        LookupItem item = new PsiTypeLookupItem(psiClass, lookupString);
        item.setAttribute(SUBSTITUTOR, substitutor);
        return item;
      }
    }
    return new LookupItem(type, type.getPresentableText());
  }