private void findUsagesForStaticMethod(PsiMethod method, List<FixableUsageInfo> usages) {
    final PsiManager psiManager = method.getManager();
    final Project project = psiManager.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope);
    final String fullyQualifiedName = getQualifiedName();
    for (PsiReference reference : calls) {
      final PsiElement referenceElement = reference.getElement();

      final PsiElement parent = referenceElement.getParent();
      if (parent instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression call = (PsiMethodCallExpression) parent;
        if (!isInMovedElement(call)) {
          usages.add(new RetargetStaticMethodCall(call, fullyQualifiedName));
        }
      } else if (parent instanceof PsiImportStaticStatement) {
        final PsiJavaCodeReferenceElement importReference =
            ((PsiImportStaticStatement) parent).getImportReference();
        if (importReference != null) {
          final PsiElement qualifier = importReference.getQualifier();
          if (qualifier instanceof PsiJavaCodeReferenceElement) {
            usages.add(
                new ReplaceClassReference(
                    (PsiJavaCodeReferenceElement) qualifier, fullyQualifiedName));
          }
        }
      }
    }
    usages.add(new RemoveMethod(method));
  }
 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);
   }
 }
  private void findUsagesForMethod(PsiMethod method, List<FixableUsageInfo> usages) {
    final PsiManager psiManager = method.getManager();
    final Project project = psiManager.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope);
    for (PsiReference reference : calls) {
      final PsiElement referenceElement = reference.getElement();
      final PsiElement parent = referenceElement.getParent();
      if (parent instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression call = (PsiMethodCallExpression) parent;
        if (isInMovedElement(call)) {
          continue;
        }
        final PsiReferenceExpression methodExpression = call.getMethodExpression();
        final PsiExpression qualifier = methodExpression.getQualifierExpression();
        if (qualifier == null || qualifier instanceof PsiThisExpression) {
          usages.add(new ReplaceThisCallWithDelegateCall(call, delegateFieldName));
        }
        delegationRequired = true;
      }
    }

    if (!delegationRequired && MethodInheritanceUtils.hasSiblingMethods(method)) {
      delegationRequired = true;
    }

    if (delegationRequired) {
      usages.add(new MakeMethodDelegate(method, delegateFieldName));
    } else {
      usages.add(new RemoveMethod(method));
    }
  }
  private static boolean canBePrivate(
      PsiMethod method,
      Collection<PsiReference> references,
      Collection<? extends PsiElement> deleted,
      final PsiElement[] allElementsToDelete) {
    final PsiClass containingClass = method.getContainingClass();
    if (containingClass == null) {
      return false;
    }

    PsiManager manager = method.getManager();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    final PsiElementFactory factory = facade.getElementFactory();
    final PsiModifierList privateModifierList;
    try {
      final PsiMethod newMethod = factory.createMethod("x3", PsiType.VOID);
      privateModifierList = newMethod.getModifierList();
      privateModifierList.setModifierProperty(PsiModifier.PRIVATE, true);
    } catch (IncorrectOperationException e) {
      LOG.assertTrue(false);
      return false;
    }
    for (PsiReference reference : references) {
      final PsiElement element = reference.getElement();
      if (!isInside(element, allElementsToDelete)
          && !isInside(element, deleted)
          && !facade
              .getResolveHelper()
              .isAccessible(method, privateModifierList, element, null, null)) {
        return false;
      }
    }
    return true;
  }
Exemplo n.º 5
0
  public static PsiType getType(@NotNull PsiClassObjectAccessExpression classAccessExpression) {
    GlobalSearchScope resolveScope = classAccessExpression.getResolveScope();
    PsiManager manager = classAccessExpression.getManager();
    final PsiClass classClass =
        JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Class", resolveScope);
    if (classClass == null) {
      return new PsiClassReferenceType(
          new LightClassReference(manager, "Class", "java.lang.Class", resolveScope), null);
    }
    if (!PsiUtil.isLanguageLevel5OrHigher(classAccessExpression)) {
      // Raw java.lang.Class
      return JavaPsiFacade.getInstance(manager.getProject())
          .getElementFactory()
          .createType(classClass);
    }

    PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
    PsiType operandType = classAccessExpression.getOperand().getType();
    if (operandType instanceof PsiPrimitiveType && !PsiType.NULL.equals(operandType)) {
      if (PsiType.VOID.equals(operandType)) {
        operandType =
            JavaPsiFacade.getInstance(manager.getProject())
                .getElementFactory()
                .createTypeByFQClassName("java.lang.Void", classAccessExpression.getResolveScope());
      } else {
        operandType = ((PsiPrimitiveType) operandType).getBoxedType(classAccessExpression);
      }
    }
    final PsiTypeParameter[] typeParameters = classClass.getTypeParameters();
    if (typeParameters.length == 1) {
      substitutor = substitutor.put(typeParameters[0], operandType);
    }

    return new PsiImmediateClassType(classClass, substitutor);
  }
Exemplo n.º 6
0
 public static void addLibraryChildren(
     final LibraryOrSdkOrderEntry entry,
     final List<AbstractTreeNode> children,
     Project project,
     ProjectViewNode node) {
   final PsiManager psiManager = PsiManager.getInstance(project);
   VirtualFile[] files =
       entry instanceof LibraryOrderEntry
           ? getLibraryRoots((LibraryOrderEntry) entry)
           : entry.getRootFiles(OrderRootType.CLASSES);
   for (final VirtualFile file : files) {
     if (!file.isValid()) continue;
     if (file.isDirectory()) {
       final PsiDirectory psiDir = psiManager.findDirectory(file);
       if (psiDir == null) {
         continue;
       }
       children.add(new PsiDirectoryNode(project, psiDir, node.getSettings()));
     } else {
       final PsiFile psiFile = psiManager.findFile(file);
       if (psiFile == null) continue;
       children.add(new PsiFileNode(project, psiFile, node.getSettings()));
     }
   }
 }
Exemplo n.º 7
0
 public static PsiElement setName(@NotNull PsiElement element, @NotNull String name)
     throws IncorrectOperationException {
   PsiManager manager = element.getManager();
   PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
   PsiIdentifier newNameIdentifier = factory.createIdentifier(name);
   return element.replace(newNameIdentifier);
 }
  @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;
  }
 @Nullable
 private static PsiClass getFieldOrMethodAccessedClass(
     PsiReferenceExpression ref, PsiClass fieldOrMethodClass) {
   PsiElement[] children = ref.getChildren();
   if (children.length > 1 && children[0] instanceof PsiExpression) {
     PsiExpression expr = (PsiExpression) children[0];
     PsiType type = expr.getType();
     if (type != null) {
       if (!(type instanceof PsiClassType)) return null;
       return PsiUtil.resolveClassInType(type);
     } else {
       if (expr instanceof PsiReferenceExpression) {
         PsiElement refElement = ((PsiReferenceExpression) expr).resolve();
         if (refElement instanceof PsiClass) return (PsiClass) refElement;
       }
       return null;
     }
   }
   PsiManager manager = ref.getManager();
   for (PsiElement parent = ref; parent != null; parent = parent.getParent()) {
     if (parent instanceof PsiClass
         && (manager.areElementsEquivalent(parent, fieldOrMethodClass)
             || ((PsiClass) parent).isInheritor(fieldOrMethodClass, true))) {
       return (PsiClass) parent;
     }
   }
   return null;
 }
Exemplo n.º 10
0
  @Nullable
  public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) {
    final PsiClass[][] holder = new PsiClass[1][];
    final Runnable process =
        () -> {
          final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();

          final Collection<PsiClass> set = new LinkedHashSet<>();
          final PsiManager manager = PsiManager.getInstance(filter.getProject());
          final GlobalSearchScope projectScope =
              GlobalSearchScope.projectScope(manager.getProject());
          final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope());
          for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) {
            if (filter.isAccepted(psiClass)) {
              if (indicator != null) {
                indicator.setText2(
                    "Found test class " + ReadAction.compute(psiClass::getQualifiedName));
              }
              set.add(psiClass);
            }
          }
          holder[0] = set.toArray(new PsiClass[set.size()]);
        };
    if (sync) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, "Searching For Tests...", true, filter.getProject());
    } else {
      process.run();
    }
    return holder[0];
  }
  private static boolean isGetterInvocation(@NotNull GrMethodCall call) {
    GrExpression expr = call.getInvokedExpression();
    if (!(expr instanceof GrReferenceExpression)) return false;

    PsiMethod method = call.resolveMethod();
    if (!GroovyPropertyUtils.isSimplePropertyGetter(method)) return false;
    LOG.assertTrue(method != null);
    if (!GroovyNamesUtil.isValidReference(
        GroovyPropertyUtils.getPropertyNameByGetterName(method.getName(), true),
        ((GrReferenceExpression) expr).getQualifier() != null,
        call.getProject())) {
      return false;
    }

    GrArgumentList args = call.getArgumentList();
    if (args == null || args.getAllArguments().length != 0) {
      return false;
    }

    GrExpression ref = genRefForGetter(call, ((GrReferenceExpression) expr).getReferenceName());
    if (ref instanceof GrReferenceExpression) {
      PsiElement resolved = ((GrReferenceExpression) ref).resolve();
      PsiManager manager = call.getManager();
      if (manager.areElementsEquivalent(resolved, method)
          || areEquivalentAccessors(method, resolved, manager)) {
        return true;
      }
    }

    return false;
  }
Exemplo n.º 12
0
  @NotNull
  public static <T extends PsiJavaCodeReferenceElement> JavaResolveResult[] multiResolveImpl(
      @NotNull T element,
      boolean incompleteCode,
      @NotNull ResolveCache.PolyVariantContextResolver<? super T> resolver) {

    FileASTNode fileElement = SharedImplUtil.findFileElement(element.getNode());
    if (fileElement == null) {
      PsiUtilCore.ensureValid(element);
      LOG.error("fileElement == null!");
      return JavaResolveResult.EMPTY_ARRAY;
    }
    PsiFile psiFile = SharedImplUtil.getContainingFile(fileElement);
    PsiManager manager = psiFile == null ? null : psiFile.getManager();
    if (manager == null) {
      PsiUtilCore.ensureValid(element);
      LOG.error("getManager() == null!");
      return JavaResolveResult.EMPTY_ARRAY;
    }
    boolean valid = psiFile.isValid();
    if (!valid) {
      PsiUtilCore.ensureValid(element);
      LOG.error("psiFile.isValid() == false!");
      return JavaResolveResult.EMPTY_ARRAY;
    }
    if (element instanceof PsiMethodReferenceExpression) {
      // method refs: do not cache results during parent conflict resolving, acceptable checks, etc
      final Map<PsiElement, PsiType> map = LambdaUtil.ourFunctionTypes.get();
      if (map != null && map.containsKey(element)) {
        return (JavaResolveResult[]) resolver.resolve(element, psiFile, incompleteCode);
      }
    }

    return multiResolveImpl(manager.getProject(), psiFile, element, incompleteCode, resolver);
  }
Exemplo n.º 13
0
  @Override
  @NotNull
  public Project getProject() {
    final PsiManager manager = getManager();
    if (manager == null) throw new PsiInvalidElementAccessException(this);

    return manager.getProject();
  }
Exemplo n.º 14
0
 private static PsiType genNewListBy(PsiType genericOwner, PsiManager manager) {
   PsiClass list =
       JavaPsiFacade.getInstance(manager.getProject())
           .findClass(JAVA_UTIL_LIST, genericOwner.getResolveScope());
   PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject());
   if (list == null) return factory.createTypeFromText(JAVA_UTIL_LIST, null);
   return factory.createType(list, PsiUtil.extractIterableTypeParameter(genericOwner, false));
 }
Exemplo n.º 15
0
  private JavaResolveResult advancedResolveInner(final PsiElement psiElement, final String qName) {
    final PsiManager manager = psiElement.getManager();
    final GlobalSearchScope scope = getScope();
    if (myIndex == myJavaClassReferenceSet.getReferences().length - 1) {
      final PsiClass aClass =
          JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, scope);
      if (aClass != null) {
        return new ClassCandidateInfo(aClass, PsiSubstitutor.EMPTY, false, psiElement);
      } else {
        if (!JavaClassReferenceProvider.ADVANCED_RESOLVE.getBooleanValue(getOptions())) {
          return JavaResolveResult.EMPTY;
        }
      }
    }
    PsiElement resolveResult = JavaPsiFacade.getInstance(manager.getProject()).findPackage(qName);
    if (resolveResult == null) {
      resolveResult = JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, scope);
    }
    if (myInStaticImport && resolveResult == null) {
      resolveResult = resolveMember(qName, manager, getElement().getResolveScope());
    }
    if (resolveResult == null) {
      PsiFile containingFile = psiElement.getContainingFile();

      if (containingFile instanceof PsiJavaFile) {
        if (containingFile instanceof JspFile) {
          containingFile = containingFile.getViewProvider().getPsi(StdLanguages.JAVA);
          if (containingFile == null) return JavaResolveResult.EMPTY;
        }

        final ClassResolverProcessor processor =
            new ClassResolverProcessor(getCanonicalText(), psiElement);
        containingFile.processDeclarations(processor, ResolveState.initial(), null, psiElement);

        if (processor.getResult().length == 1) {
          final JavaResolveResult javaResolveResult = processor.getResult()[0];

          if (javaResolveResult != JavaResolveResult.EMPTY && getOptions() != null) {
            final Boolean value =
                JavaClassReferenceProvider.RESOLVE_QUALIFIED_CLASS_NAME.getValue(getOptions());
            final PsiClass psiClass = (PsiClass) javaResolveResult.getElement();
            if (value != null && value.booleanValue() && psiClass != null) {
              final String qualifiedName = psiClass.getQualifiedName();

              if (!qName.equals(qualifiedName)) {
                return JavaResolveResult.EMPTY;
              }
            }
          }

          return javaResolveResult;
        }
      }
    }
    return resolveResult != null
        ? new CandidateInfo(resolveResult, PsiSubstitutor.EMPTY, false, false, psiElement)
        : JavaResolveResult.EMPTY;
  }
  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;
  }
Exemplo n.º 17
0
 protected PsiPackage getPackage(JUnitConfiguration.Data data) throws CantRunException {
   final Project project = myConfiguration.getProject();
   final String packageName = data.getPackageName();
   final PsiManager psiManager = PsiManager.getInstance(project);
   final PsiPackage aPackage =
       JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(packageName);
   if (aPackage == null) throw CantRunException.packageNotFound(packageName);
   return aPackage;
 }
  private CodeFormatterFacade getFormatterFacade(final FileViewProvider viewProvider) {
    final CodeStyleSettings styleSettings =
        CodeStyleSettingsManager.getSettings(myPsiManager.getProject());
    final PsiDocumentManager documentManager =
        PsiDocumentManager.getInstance(myPsiManager.getProject());
    final Document document = viewProvider.getDocument();
    final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(styleSettings);

    documentManager.commitDocument(document);
    return codeFormatter;
  }
 public void fix() throws IncorrectOperationException {
   if (myField == null) return;
   final PsiManager manager = myScope.getManager();
   for (GrReferenceExpression referenceExpression : myReferenceExpressions) {
     if (!referenceExpression.isValid()) continue;
     final PsiElement newlyResolved = referenceExpression.resolve();
     if (!manager.areElementsEquivalent(newlyResolved, myField)) {
       qualifyReference(referenceExpression, myField, myQualifyingClass);
     }
   }
 }
Exemplo n.º 20
0
  private static PsiType genNewMapBy(PsiType genericOwner, PsiManager manager) {
    PsiClass map =
        JavaPsiFacade.getInstance(manager.getProject())
            .findClass(JAVA_UTIL_MAP, genericOwner.getResolveScope());
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject());
    if (map == null) return factory.createTypeFromText(JAVA_UTIL_MAP, null);

    final PsiType key = PsiUtil.substituteTypeParameter(genericOwner, JAVA_UTIL_MAP, 0, false);
    final PsiType value = PsiUtil.substituteTypeParameter(genericOwner, JAVA_UTIL_MAP, 1, false);
    return factory.createType(map, key, value);
  }
 private static void addParameterUsages(
     PsiParameter parameter, ArrayList<UsageInfo> results, ParameterInfo info) {
   PsiManager manager = parameter.getManager();
   GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
   for (PsiReference psiReference : ReferencesSearch.search(parameter, projectScope, false)) {
     PsiElement parmRef = psiReference.getElement();
     UsageInfo usageInfo =
         new ChangeSignatureParameterUsageInfo(parmRef, parameter.getName(), info.getName());
     results.add(usageInfo);
   }
 }
Exemplo n.º 22
0
 @Nullable
 private static DeclarationDescriptor findSuperFunction(
     @NotNull Collection<Pair<FunctionDescriptor, PsiMethod>> superFunctionCandidates,
     @NotNull PsiMethod superMethod) {
   PsiManager psiManager = PsiManager.getInstance(superMethod.getProject());
   for (Pair<FunctionDescriptor, PsiMethod> candidate : superFunctionCandidates) {
     if (psiManager.areElementsEquivalent(candidate.second, superMethod)) {
       return candidate.first;
     }
   }
   return null;
 }
  @SuppressWarnings("ConstantConditions")
  public void testIsSupported() throws Exception {
    VirtualFile layoutFile =
        myFixture.copyFileToProject("xmlpull/layout.xml", "res/layout-land-v14/foo.xml");
    VirtualFile menuFile = myFixture.copyFileToProject("menus/menu1.xml", "res/menu/menu1.xml");
    VirtualFile drawableFile = myFixture.copyFileToProject("menus/menu1.xml", "res/menu/menu1.xml");

    PsiManager psiManager = PsiManager.getInstance(getProject());

    assertTrue(LayoutPullParserFactory.isSupported(psiManager.findFile(layoutFile)));
    assertTrue(LayoutPullParserFactory.isSupported(psiManager.findFile(menuFile)));
    assertTrue(LayoutPullParserFactory.isSupported(psiManager.findFile(drawableFile)));
  }
Exemplo n.º 24
0
 @Nullable
 public static PsiElement resolveMember(
     String fqn, PsiManager manager, GlobalSearchScope resolveScope) {
   PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(fqn, resolveScope);
   if (aClass != null) return aClass;
   int i = fqn.lastIndexOf('.');
   if (i == -1) return null;
   String memberName = fqn.substring(i + 1);
   fqn = fqn.substring(0, i);
   aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(fqn, resolveScope);
   if (aClass == null) return null;
   return doResolveMember(aClass, memberName);
 }
  @NotNull
  protected UsageInfo[] findUsages() {
    final PsiManager manager = myMethod.getManager();
    final GlobalSearchScope searchScope = GlobalSearchScope.allScope(manager.getProject());
    final List<UsageInfo> usages = new ArrayList<UsageInfo>();
    for (PsiReference ref : ReferencesSearch.search(myMethod, searchScope, false)) {
      final PsiElement element = ref.getElement();
      if (element instanceof PsiReferenceExpression) {
        boolean isInternal = PsiTreeUtil.isAncestor(myMethod, element, true);
        usages.add(new MethodCallUsageInfo((PsiReferenceExpression) element, isInternal));
      } else if (element instanceof PsiDocTagValue) {
        usages.add(new JavadocUsageInfo(((PsiDocTagValue) element)));
      } else {
        throw new UnknownReferenceTypeException(element.getLanguage());
      }
    }

    if (myTargetClass.isInterface()) {
      addInheritorUsages(myTargetClass, searchScope, usages);
    }

    final PsiCodeBlock body = myMethod.getBody();
    if (body != null) {
      body.accept(
          new JavaRecursiveElementWalkingVisitor() {
            @Override
            public void visitNewExpression(PsiNewExpression expression) {
              if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) {
                usages.add(new InternalUsageInfo(expression));
              }
              super.visitNewExpression(expression);
            }

            @Override
            public void visitReferenceExpression(PsiReferenceExpression expression) {
              if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) {
                usages.add(new InternalUsageInfo(expression));
              } else if (!expression.isQualified()) {
                final PsiElement resolved = expression.resolve();
                if (myTargetVariable.equals(resolved)) {
                  usages.add(new InternalUsageInfo(expression));
                }
              }

              super.visitReferenceExpression(expression);
            }
          });
    }

    return usages.toArray(new UsageInfo[usages.size()]);
  }
 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;
 }
 private static void rename(
     PsiReference ref, String newName, PsiManager manager, PsiMember elementToResolve) {
   final PsiElement renamed = ref.handleElementRename(newName);
   PsiElement newly_resolved = ref.resolve();
   if (!manager.areElementsEquivalent(newly_resolved, elementToResolve)) {
     if (newly_resolved instanceof PsiMethod) {
       newly_resolved =
           GroovyPropertyUtils.findFieldForAccessor((PsiMethod) newly_resolved, false);
     }
     if (!manager.areElementsEquivalent(newly_resolved, elementToResolve)) {
       qualify(elementToResolve, renamed, newName);
     }
   }
 }
  private void selectElementInLeftTree(PsiElement elt) {
    PsiManager manager = PsiManager.getInstance(myProject);

    PackageDependenciesNode root = (PackageDependenciesNode) myLeftTree.getModel().getRoot();
    Enumeration enumeration = root.breadthFirstEnumeration();
    while (enumeration.hasMoreElements()) {
      PackageDependenciesNode child = (PackageDependenciesNode) enumeration.nextElement();
      if (manager.areElementsEquivalent(child.getPsiElement(), elt)) {
        myLeftTree.setSelectionPath(
            new TreePath(((DefaultTreeModel) myLeftTree.getModel()).getPathToRoot(child)));
        break;
      }
    }
  }
Exemplo n.º 29
0
  public static String getRootDirectoryForPackage(PsiDirectory directory) {
    PsiManager manager = directory.getManager();
    final VirtualFile virtualFile = directory.getVirtualFile();
    final ProjectFileIndex fileIndex =
        ProjectRootManager.getInstance(manager.getProject()).getFileIndex();
    VirtualFile root = fileIndex.getSourceRootForFile(virtualFile);

    if (root == null) {
      root = fileIndex.getClassRootForFile(virtualFile);
    }
    if (root != null) {
      return root.getPresentableUrl();
    }
    return null;
  }
Exemplo n.º 30
0
  private Map<PsiJavaStubDataSource, SModel> getModelMap() {
    Map<PsiJavaStubDataSource, SModel> modelMap =
        MapSequence.fromMap(new HashMap<PsiJavaStubDataSource, SModel>());

    final VirtualFile[] sourceRoots =
        ModuleRootManager.getInstance(myIdeaModule).getSourceRoots(false);
    PsiManager psiMgr = PsiManager.getInstance(myIdeaModule.getProject());

    for (VirtualFile root : sourceRoots) {
      PsiDirectory dir = psiMgr.findDirectory(root);
      addModelsForDir(dir, dir, modelMap);
    }

    return modelMap;
  }