Java 类com.intellij.util.Query 实例源码

项目:manifold-ij    文件:MoveTypeManifoldFileProcessor.java   
@Nullable
@Override
public List<UsageInfo> findUsages( PsiFile psiFile, PsiDirectory newParent, boolean searchInComments, boolean searchInNonJavaFiles )
{
  Module mod = ModuleUtilCore.findModuleForPsiElement( psiFile );
  ManModule module = ManProject.getModule( mod );
  PsiClass psiClass = findPsiClass( psiFile );
  if( psiClass == null )
  {
    return Collections.emptyList();
  }

  Query<PsiReference> search = ReferencesSearch.search( psiClass, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ) );
  List<UsageInfo> usages = new ArrayList<>();
  for( PsiReference ref: search.findAll() )
  {
    usages.add( new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
      ref.getRangeInElement().getEndOffset(), psiClass,
      ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) ) );
  }
  return usages;
}
项目:manifold-ij    文件:RenameResourceElementProcessor.java   
private static List<UsageInfo> findUsages( PsiElement element, PsiElement ctx )
  {
//    Module mod = ModuleUtilCore.findModuleForPsiElement( element );
//    if( mod == null )
//    {
//      return Collections.emptyList();
//    }

    Query<PsiReference> search = ReferencesSearch.search( element, GlobalSearchScope.moduleScope( ModuleUtilCore.findModuleForPsiElement( ctx ) ) );
    List<UsageInfo> usages = new ArrayList<>();
    for( PsiReference ref : search.findAll() )
    {
      MoveRenameUsageInfo usageInfo = new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
                                                               ref.getRangeInElement().getEndOffset(), element,
                                                               ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) );
      usages.add( usageInfo );
    }
    return usages;
  }
项目:intellij-ce-playground    文件:MethodUtils.java   
public static boolean isOverriddenInHierarchy(PsiMethod method, PsiClass baseClass) {
  // previous implementation:
  // final Query<PsiMethod> search = OverridingMethodsSearch.search(method);
  //for (PsiMethod overridingMethod : search) {
  //    final PsiClass aClass = overridingMethod.getContainingClass();
  //    if (InheritanceUtil.isCorrectDescendant(aClass, baseClass, true)) {
  //        return true;
  //    }
  //}
  // was extremely slow and used an enormous amount of memory for clone()
  final Query<PsiClass> search = ClassInheritorsSearch.search(baseClass, baseClass.getUseScope(), true, true, true);
  for (PsiClass inheritor : search) {
    final PsiMethod overridingMethod = inheritor.findMethodBySignature(method, false);
    if (overridingMethod != null) {
      return true;
    }
  }
  return false;
}
项目:epigraph    文件:SchemaRenameUtil.java   
private static void addMaxSuperMembers(@NotNull SchemaTypeDef currentType,
                                       @NotNull Function<SchemaTypeDef, PsiNamedElement> typeFunc,
                                       @NotNull List<PsiNamedElement> acc) {

  final int accSizeBefore = acc.size();

  Query<SchemaTypeDef> parentsQuery = SchemaDirectTypeParentsSearch.search(currentType);
  parentsQuery.forEach(typeDef -> {
    PsiNamedElement member = typeFunc.apply(typeDef);
    if (member != null) addMaxSuperMembers(typeDef, typeFunc, acc);

    return true;
  });

  if (acc.size() == accSizeBefore /*&& accSizeBefore > 0*/) acc.add(currentType);
}
项目:intellij-ce-playground    文件:DirectClassInheritorsSearch.java   
public static Query<PsiClass> search(final PsiClass aClass,
                                     SearchScope scope,
                                     boolean includeAnonymous,
                                     final boolean checkInheritance) {
  final Query<PsiClass> raw = INSTANCE.createUniqueResultsQuery(new SearchParameters(aClass, scope, includeAnonymous, checkInheritance));

  if (!includeAnonymous) {
    return new FilteredQuery<PsiClass>(raw, new Condition<PsiClass>() {
      @Override
      public boolean value(final PsiClass psiClass) {
        return !(psiClass instanceof PsiAnonymousClass);
      }
    });
  }

  return raw;
}
项目:intellij-ce-playground    文件:ConvertInterfaceToClassIntention.java   
private static boolean moveSubClassImplementsToExtends(PsiClass oldInterface) throws IncorrectOperationException {
  final Project project = oldInterface.getProject();
  final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
  final PsiElementFactory elementFactory = psiFacade.getElementFactory();
  final PsiJavaCodeReferenceElement oldInterfaceReference = elementFactory.createClassReferenceElement(oldInterface);
  final SearchScope searchScope = oldInterface.getUseScope();
  final Query<PsiClass> query = ClassInheritorsSearch.search(oldInterface, searchScope, false);
  final Collection<PsiClass> inheritors = query.findAll();
  final boolean success = CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, inheritors, false);
  if (!success) {
    return false;
  }
  for (PsiClass inheritor : inheritors) {
    final PsiReferenceList implementsList = inheritor.getImplementsList();
    final PsiReferenceList extendsList = inheritor.getExtendsList();
    if (implementsList != null) {
      moveReference(implementsList, extendsList, oldInterfaceReference);
    }
  }
  return true;
}
项目:intellij-ce-playground    文件:StaticMethodOnlyUsedInOneClassInspectionBase.java   
/**
 * @return the class the specified method is used from, or null if it is
 *         used from 0 or more than 1 other classes.
 */
@Nullable
public PsiClass getUsageClass(final PsiMethod method) {
  final ProgressManager progressManager = ProgressManager.getInstance();
  final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(method.getProject());
  final String name = method.getName();
  final GlobalSearchScope scope = GlobalSearchScope.allScope(method.getProject());
  if (searchHelper.isCheapEnoughToSearch(name, scope, null, progressManager.getProgressIndicator())
      == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) {
    return null;
  }
  progressManager.runProcess(new Runnable() {
    @Override
    public void run() {
      final Query<PsiReference> query = MethodReferencesSearch.search(method);
      if (!query.forEach(UsageProcessor.this)) {
        foundClass.set(null);
      }
    }
  }, null);
  return foundClass.get();
}
项目:intellij-ce-playground    文件:PackageUtil.java   
private static PsiPackage findLongestExistingPackage(Module module, String packageName) {
  final PsiManager manager = PsiManager.getInstance(module.getProject());

  String nameToMatch = packageName;
  while (true) {
    Query<VirtualFile> vFiles = ModulePackageIndex.getInstance(module).getDirsByPackageName(nameToMatch, false);
    PsiDirectory directory = getWritableModuleDirectory(vFiles, module, manager);
    if (directory != null) return JavaDirectoryService.getInstance().getPackage(directory);

    int lastDotIndex = nameToMatch.lastIndexOf('.');
    if (lastDotIndex >= 0) {
      nameToMatch = nameToMatch.substring(0, lastDotIndex);
    }
    else {
      return null;
    }
  }
}
项目:intellij-ce-playground    文件:JavaInvertBooleanDelegate.java   
public void collectRefsToInvert(PsiElement namedElement, Collection<PsiElement> elementsToInvert) {
  final Query<PsiReference> query = namedElement instanceof PsiMethod ?
                                    MethodReferencesSearch.search((PsiMethod)namedElement) :
                                    ReferencesSearch.search(namedElement);
  final Collection<PsiReference> refs = query.findAll();

  for (PsiReference ref : refs) {
    final PsiElement element = ref.getElement();
    PsiElement refElement = getElementToInvert(namedElement, element);
    if (refElement == null) {
      refElement = getForeignElementToInvert(namedElement, element, JavaLanguage.INSTANCE);
    }
    if (refElement != null) {
      elementsToInvert.add(refElement);
    }
  }
}
项目:intellij-ce-playground    文件:TypeMigrationLabeler.java   
public static List<PsiReference> filterReferences(final PsiClass psiClass, final Query<PsiReference> memberReferences) {
  final List<PsiReference> refs = new ArrayList<PsiReference>();
  for (PsiReference memberReference : memberReferences) {
    if (psiClass == null) {
      refs.add(memberReference);
    } else {
      final PsiElement referencedElement = memberReference.getElement();
      if (referencedElement instanceof PsiReferenceExpression) {
        final PsiExpression qualifierExpression = ((PsiReferenceExpression)referencedElement).getQualifierExpression();
        if (qualifierExpression != null) {
          final PsiType qualifierType = qualifierExpression.getType();
          if (qualifierType instanceof PsiClassType && psiClass == ((PsiClassType)qualifierType).resolve()) {
            refs.add(memberReference);
          }
        } else {
          if (psiClass == PsiTreeUtil.getParentOfType(referencedElement, PsiClass.class)) {
            refs.add(memberReference);
          }
        }
      }
    }
  }
  return refs;
}
项目:intellij-ce-playground    文件:QuerySearchRequest.java   
public QuerySearchRequest(@NotNull Query<PsiReference> query,
                          @NotNull final SearchRequestCollector collector,
                          boolean inReadAction,
                          @NotNull final PairProcessor<PsiReference, SearchRequestCollector> processor) {
  this.query = query;
  this.collector = collector;
  if (inReadAction) {
    this.processor = new ReadActionProcessor<PsiReference>() {
      @Override
      public boolean processInReadAction(PsiReference psiReference) {
        return processor.process(psiReference, collector);
      }
    };
  }
  else {
    this.processor = new Processor<PsiReference>() {
      @Override
      public boolean process(PsiReference psiReference) {
        return processor.process(psiReference, collector);
      }
    };
  }
}
项目:intellij-ce-playground    文件:ParameterNameDiffersFromOverriddenParameterInspectionBase.java   
@Override
public void visitMethod(@NotNull PsiMethod method) {
  final PsiParameterList parameterList = method.getParameterList();
  if (parameterList.getParametersCount() == 0) {
    return;
  }
  final Query<MethodSignatureBackedByPsiMethod> query =
    SuperMethodsSearch.search(
      method, method.getContainingClass(), true, false);
  final MethodSignatureBackedByPsiMethod methodSignature =
    query.findFirst();
  if (methodSignature == null) {
    return;
  }
  final PsiMethod superMethod = methodSignature.getMethod();
  final PsiParameter[] parameters = parameterList.getParameters();
  checkParameters(superMethod, parameters);
}
项目:intellij-ce-playground    文件:PyInlineLocalHandler.java   
private static Pair<PyStatement, Boolean> getAssignmentToInline(ScopeOwner containerBlock, PyReferenceExpression expr,
                                                                PyTargetExpression local, Project project) {
  if (expr != null) {
    try {
      final List<ReadWriteInstruction> candidates = PyDefUseUtil.getLatestDefs(containerBlock, local.getName(), expr, true);
      if (candidates.size() == 1) {
        final PyStatement expression = getAssignmentByLeftPart((PyElement)candidates.get(0).getElement());
        return Pair.create(expression, false);
      }
      return Pair.create(null, candidates.size() > 0);
    }
    catch (PyDefUseUtil.InstructionNotFoundException ignored) {
    }
  }
  final Query<PsiReference> query = ReferencesSearch.search(local, GlobalSearchScope.allScope(project), false);
  final PsiReference first = query.findFirst();

  final PyElement lValue = first != null ? (PyElement)first.resolve() : null;
  return lValue != null ? Pair.create(getAssignmentByLeftPart(lValue), false) : EMPTY_DEF_RESULT;
}
项目:intellij-ce-playground    文件:UtilityClassWithoutPrivateConstructorInspection.java   
@NotNull
@Override
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
  final List<InspectionGadgetsFix> fixes = new ArrayList<InspectionGadgetsFix>();
  final PsiClass aClass = (PsiClass)infos[0];
  final PsiMethod constructor = getNullArgConstructor(aClass);
  if (constructor == null) {
    fixes.add(new CreateEmptyPrivateConstructor());
  }
  else {
    final Query<PsiReference> query = ReferencesSearch.search(constructor, constructor.getUseScope());
    final PsiReference reference = query.findFirst();
    if (reference == null) {
      fixes.add(new MakeConstructorPrivateFix());
    }
  }
  AddToIgnoreIfAnnotatedByListQuickFix.build(aClass, ignorableAnnotations, fixes);
  return fixes.toArray(new InspectionGadgetsFix[fixes.size()]);
}
项目:intellij-ce-playground    文件:MultipleExceptionsDeclaredOnTestMethodInspection.java   
@Override
public void visitMethod(PsiMethod method) {
  super.visitMethod(method);
  if (!TestUtils.isJUnitTestMethod(method)) {
    return;
  }
  final PsiReferenceList throwsList = method.getThrowsList();
  final PsiJavaCodeReferenceElement[] referenceElements =
    throwsList.getReferenceElements();
  if (referenceElements.length < 2) {
    return;
  }

  final Query<PsiReference> query =
    MethodReferencesSearch.search(method);
  final PsiReference firstReference = query.findFirst();
  if (firstReference != null) {
    return;
  }
  registerError(throwsList);
}
项目:processing-idea    文件:ProcessingRunConfigurationEditor.java   
private void refreshSketchSelector(Module [] moduleSearchScope) {
    ApplicationManager.getApplication().runWriteAction(() -> {
        Query<PsiClass> classQuery =
                AllClassesSearch.search(ProcessingPluginUtil.INSTANCE.sketchesInModuleScope(moduleSearchScope), project);
        Collection<PsiClass> classesInModule = classQuery.findAll();

        for (PsiClass classInModule : classesInModule) {
            if (SketchClassFilter.isSketchClass(classInModule)) {
                sketchSelector.addItem(new SketchSelectorComboItem(classInModule));
            }
        }
    });
}
项目:manifold-ij    文件:RenameTypeManifoldFileProcessor.java   
private void storeTypeManifoldReferences( @NotNull PsiElement element )
{
  Module mod = ModuleUtilCore.findModuleForPsiElement( element );
  if( mod == null )
  {
    return;
  }

  ManModule module = ManProject.getModule( mod );

  PsiClass psiClass = findPsiClass( (PsiFileSystemItem)element, module );
  if( psiClass == null )
  {
    return;
  }

  Query<PsiReference> search = ReferencesSearch.search( psiClass, GlobalSearchScope.projectScope( mod.getProject() ) );
  List<UsageInfo> usages = new ArrayList<>();
  for( PsiReference ref: search.findAll() )
  {
    usages.add( new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
      ref.getRangeInElement().getEndOffset(), element,
      ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) ) );
  }
  _usages = usages;

  if( psiClass instanceof ManifoldPsiClass )
  {
    PsiElement fakeElement = ManGotoDeclarationHandler.find( psiClass, (ManifoldPsiClass)psiClass );
    if( fakeElement instanceof PsiNamedElement && isTopLevelClassDeclaration( fakeElement ) )
    {
      _classDeclElement = (PsiNamedElement)fakeElement;
    }
  }
}
项目:intellij-ce-playground    文件:MethodOnlyUsedFromInnerClassInspection.java   
public boolean isOnlyAccessedFromInnerClass() {
  final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(method.getProject());
  final ProgressManager progressManager = ProgressManager.getInstance();
  final ProgressIndicator progressIndicator = progressManager.getProgressIndicator();
  final PsiSearchHelper.SearchCostResult searchCost =
    searchHelper.isCheapEnoughToSearch(method.getName(), method.getResolveScope(), null, progressIndicator);
  if (searchCost == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES ||
      searchCost == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES) {
    return onlyAccessedFromInnerClass;
  }
  final Query<PsiReference> query = ReferencesSearch.search(method);
  query.forEach(this);
  return onlyAccessedFromInnerClass;
}
项目:MVPManager    文件:ChangeHelper.java   
public static void method(Project project, PsiJavaFile psiJavaFile, int type, MethodEntity methodEntity, boolean isDel) {
        for (PsiElement psiInterface :
                getClasses(psiJavaFile)) {
            if (psiInterface instanceof PsiClass) {
                switch (type) {
                    case ChangeMVPDialog.VIEW:
                        if (!ClassHelper.VIEW.equals(((PsiClass) psiInterface).getName())) continue;
                        break;
                    case ChangeMVPDialog.PRESENTER:
                        if (!ClassHelper.PRESENTER.equals(((PsiClass) psiInterface).getName())) continue;
                        break;
                    case ChangeMVPDialog.MODEL:
                        if (!ClassHelper.MODEL.equals(((PsiClass) psiInterface).getName())) continue;
                        break;
                }
                if (isDel) {
                    delMethod(project, psiInterface, methodEntity);
                } else {
                    ClassHelper.addMethodToClass(project, (PsiClass) psiInterface, createList(methodEntity), false);
                }
                if (((PsiClass) psiInterface).getExtendsList() == null) return;
//                ClassInheritorsSearch query = ClassInheritorsSearch.search((PsiClass) psiInterface, true);
                Query<PsiClass> query = ClassInheritorsSearch.search((PsiClass) psiInterface);
                for (Iterator<PsiClass> it = query.iterator(); it.hasNext(); ) {
                    PsiClass p = it.next();
                    if (isDel) {
                        delMethod(project, p, methodEntity);
                    } else {
                        ClassHelper.addMethodToClass(project, p, createList(methodEntity), true);
                    }
                }
            }
        }
    }
项目:intellij-ce-playground    文件:JavaFileManagerImpl.java   
@Override
@Nullable
public PsiPackage findPackage(@NotNull String packageName) {
  Query<VirtualFile> dirs = myPackageIndex.getDirsByPackageName(packageName, true);
  if (dirs.findFirst() == null) return null;
  return new PsiPackageImpl(myManager, packageName);
}
项目:intellij-ce-playground    文件:TypeMayBeWeakenedInspection.java   
@Override
public void visitMethod(PsiMethod method) {
  super.visitMethod(method);
  if (isOnTheFly() && !method.hasModifierProperty(PsiModifier.PRIVATE) && !ApplicationManager.getApplication().isUnitTestMode()) {
    // checking methods with greater visibility is too expensive.
    // for error checking in the editor
    return;
  }
  if (MethodUtils.hasSuper(method)) {
    // do not try to weaken methods with super methods
    return;
  }
  final Query<PsiMethod> overridingSearch = OverridingMethodsSearch.search(method);
  if (overridingSearch.findFirst() != null) {
    // do not try to weaken methods with overriding methods.
    return;
  }
  final Collection<PsiClass> weakestClasses =
    WeakestTypeFinder.calculateWeakestClassesNecessary(method,
                                                       useRighthandTypeAsWeakestTypeInAssignments,
                                                       useParameterizedTypeForCollectionMethods);
  if (doNotWeakenToJavaLangObject) {
    final Project project = method.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final PsiClass javaLangObjectClass = facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, method.getResolveScope());
    weakestClasses.remove(javaLangObjectClass);
  }
  if (onlyWeakentoInterface) {
    for (Iterator<PsiClass> iterator = weakestClasses.iterator(); iterator.hasNext(); ) {
      final PsiClass weakestClass = iterator.next();
      if (!weakestClass.isInterface()) {
        iterator.remove();
      }
    }
  }
  if (weakestClasses.isEmpty()) {
    return;
  }
  registerMethodError(method, method, weakestClasses);
}
项目:intellij-ce-playground    文件:OverridingMethodsSearch.java   
public static Query<PsiMethod> search(final PsiMethod method, SearchScope scope, final boolean checkDeep) {
  if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
    @Override
    public Boolean compute() {
      return cannotBeOverriden(method);
    }
  })) return EmptyQuery.getEmptyQuery(); // Optimization
  return INSTANCE.createUniqueResultsQuery(new SearchParameters(method, scope, checkDeep));
}
项目:intellij-ce-playground    文件:OverridingMethodsSearch.java   
public static Query<PsiMethod> search(final PsiMethod method, final boolean checkDeep) {
  return search(method, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
    @Override
    public SearchScope compute() {
      return method.getUseScope();
    }
  }), checkDeep);
}
项目:intellij-ce-playground    文件:MakeMethodVarargsIntention.java   
private static void makeMethodCallsVarargs(PsiElement element)
  throws IncorrectOperationException {
  final PsiMethod method = (PsiMethod)element.getParent();
  final Query<PsiReference> query =
    ReferencesSearch.search(method, method.getUseScope(), false);
  for (PsiReference reference : query) {
    final PsiElement referenceElement = reference.getElement();
    if (!(referenceElement instanceof PsiReferenceExpression)) {
      continue;
    }
    final PsiReferenceExpression referenceExpression =
      (PsiReferenceExpression)referenceElement;
    final PsiMethodCallExpression methodCallExpression =
      (PsiMethodCallExpression)referenceExpression.getParent();
    final PsiExpressionList argumentList =
      methodCallExpression.getArgumentList();
    final PsiExpression[] arguments = argumentList.getExpressions();
    if (arguments.length == 0) {
      continue;
    }
    final PsiExpression lastArgument = arguments[arguments.length - 1];
    if (!(lastArgument instanceof PsiNewExpression)) {
      continue;
    }
    final PsiNewExpression newExpression =
      (PsiNewExpression)lastArgument;
    final PsiArrayInitializerExpression arrayInitializerExpression =
      newExpression.getArrayInitializer();
    if (arrayInitializerExpression == null) {
      continue;
    }
    final PsiExpression[] initializers =
      arrayInitializerExpression.getInitializers();
    for (PsiExpression initializer : initializers) {
      argumentList.add(initializer);
    }
    lastArgument.delete();
  }
}
项目:intellij-ce-playground    文件:ClassInheritorsSearch.java   
public static Query<PsiClass> search(@NotNull SearchParameters parameters) {
  return INSTANCE.createUniqueResultsQuery(parameters, ContainerUtil.<SmartPsiElementPointer<PsiClass>>canonicalStrategy(), new Function<PsiClass, SmartPsiElementPointer<PsiClass>>() {
    @Override
    public SmartPsiElementPointer<PsiClass> fun(final PsiClass psiClass) {
      return ApplicationManager.getApplication().runReadAction(new Computable<SmartPsiElementPointer<PsiClass>>() {
        @Override
        public SmartPsiElementPointer<PsiClass> compute() {
          return SmartPointerManager.getInstance(psiClass.getProject()).createSmartPsiElementPointer(psiClass);
        }
      });
    }
  });
}
项目:dagger2-intellij-plugin    文件:GenerateComponentAction.java   
@NotNull
private List<PsiClass> extractDagger2ModulesPsiClasses(AnActionEvent e) {
    DaggerModuleClassFilter filter = new DaggerModuleClassFilter();
    final Module module = LangDataKeys.MODULE.getData(e.getDataContext());
    SearchScope scope = GlobalSearchScope.moduleScope(module);
    Query<PsiClass> search = AllClassesSearch.search(scope, e.getProject());
    List<PsiClass> modulesClasses = new ArrayList<>();
    for (PsiClass psiClass : search.findAll()) {
        if (filter.isAccepted(psiClass)) {
            modulesClasses.add(psiClass);
        }
    }
    return modulesClasses;
}
项目:intellij-ce-playground    文件:ClassInheritorsSearch.java   
public static Query<PsiClass> search(@NotNull final PsiClass aClass, final boolean checkDeep) {
  return search(aClass, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
    @Override
    public SearchScope compute() {
      if (!aClass.isValid()) {
        throw new ProcessCanceledException();
      }
      return aClass.getUseScope();
    }
  }), checkDeep);
}
项目:intellij-ce-playground    文件:SuperMethodsSearch.java   
@NotNull
public static Query<MethodSignatureBackedByPsiMethod> search(@NotNull PsiMethod derivedMethod,
                                                             @Nullable final PsiClass psiClass,
                                                             boolean checkBases,
                                                             boolean allowStaticMethod) {
  final SearchParameters parameters = new SearchParameters(derivedMethod, psiClass, checkBases, allowStaticMethod);
  return SUPER_METHODS_SEARCH_INSTANCE.createUniqueResultsQuery(parameters, MethodSignatureUtil.METHOD_BASED_HASHING_STRATEGY);
}
项目:intellij-ce-playground    文件:RedundantThrows.java   
private static void removeException(final RefMethod refMethod,
                                    final PsiType exceptionType,
                                    final List<PsiJavaCodeReferenceElement> refsToDelete,
                                    final PsiMethod psiMethod) {
  PsiManager psiManager = psiMethod.getManager();

  PsiJavaCodeReferenceElement[] refs = psiMethod.getThrowsList().getReferenceElements();
  for (PsiJavaCodeReferenceElement ref : refs) {
    PsiType refType = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(ref);
    if (exceptionType.isAssignableFrom(refType)) {
      refsToDelete.add(ref);
    }
  }

  if (refMethod != null) {
    for (RefMethod refDerived : refMethod.getDerivedMethods()) {
      PsiModifierListOwner method = refDerived.getElement();
      if (method != null) {
        removeException(refDerived, exceptionType, refsToDelete, (PsiMethod)method);
      }
    }
  } else {
    final Query<Pair<PsiMethod,PsiMethod>> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass());
    query.forEach(new Processor<Pair<PsiMethod, PsiMethod>>(){
      @Override
      public boolean process(final Pair<PsiMethod, PsiMethod> pair) {
        if (pair.first == psiMethod) {
          removeException(null, exceptionType, refsToDelete, pair.second);
        }
        return true;
      }
    });
  }
}
项目:intellij-ce-playground    文件:EmptyMethodInspection.java   
@Override
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
  final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class, false);
  if (psiMethod != null) {
    final List<PsiElement> psiElements = new ArrayList<PsiElement>();
    psiElements.add(psiMethod);
    if (Boolean.valueOf(myHint).booleanValue()) {
      final Query<Pair<PsiMethod, PsiMethod>> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass());
      query.forEach(new Processor<Pair<PsiMethod, PsiMethod>>() {
        @Override
        public boolean process(final Pair<PsiMethod, PsiMethod> pair) {
          if (pair.first == psiMethod) {
            psiElements.add(pair.second);
          }
          return true;
        }
      });
    }

    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        SafeDeleteHandler.invoke(project, PsiUtilCore.toPsiElementArray(psiElements), false);
      }
    }, project.getDisposed());
  }
}
项目:intellij-ce-playground    文件:NullityInferrer.java   
private boolean variableNeverAssignedNull(@NotNull PsiVariable variable) {
  final PsiExpression initializer = variable.getInitializer();
  if (initializer != null) {
    if (!expressionIsNeverNull(initializer)) {
      return false;
    }
  }
  else if (!variable.hasModifierProperty(PsiModifier.FINAL)) {
    return false;
  }
  final Query<PsiReference> references = ReferencesSearch.search(variable);
  for (final PsiReference reference : references) {
    final PsiElement element = reference.getElement();
    if (!(element instanceof PsiReferenceExpression)) {
      continue;
    }
    final PsiElement parent = element.getParent();
    if (!(parent instanceof PsiAssignmentExpression)) {
      continue;
    }
    final PsiAssignmentExpression assignment = (PsiAssignmentExpression)parent;
    if (assignment.getLExpression().equals(element) &&
        !expressionIsNeverNull(assignment.getRExpression())) {
      return false;
    }
  }
  return true;
}
项目:intellij-ce-playground    文件:XsltImplicitUsagesProvider.java   
public boolean isImplicitUsage(PsiElement element) {
    if (!(element instanceof XmlAttribute)) {
        return false;
    }
    final XmlAttribute attr = (XmlAttribute)element;
    if (!attr.isNamespaceDeclaration()) {
        return false;
    }
    final PsiFile file = attr.getContainingFile();
    if (!(file instanceof XmlFile)) {
      return false;
    }

    // also catch namespace declarations in "normal" XML files that have XPath injected into some attributes
    // ContextProvider.hasXPathInjections() is an optimization that avoids to run the references search on totally XPath-free XML files
    if (!ContextProvider.hasXPathInjections((XmlFile)file) && !XsltSupport.isXsltFile(file)) {
        return false;
    }

    // This need to catch both prefix references from injected XPathFiles and prefixes from mode declarations/references:
    // <xsl:template match="*" mode="prefix:name" />

    // BTW: Almost the same logic applies to other XML dialects (RELAX-NG).
    // Pull this class into the platform?
    final String prefix = attr.getLocalName();
    final SchemaPrefix target = new SchemaPrefix(attr, TextRange.from("xmlns:".length(), prefix.length()), prefix);
    final Query<PsiReference> q = ReferencesSearch.search(target, new LocalSearchScope(attr.getParent()));
    return !q.forEach(new Processor<PsiReference>() {
        public boolean process(PsiReference psiReference) {
            if (psiReference.getElement() == attr) {
                return true;
            }
            return false;
        }
    });
}
项目:intellij-ce-playground    文件:PackageUtil.java   
private static PsiDirectory getWritableModuleDirectory(@NotNull Query<VirtualFile> vFiles, @NotNull Module module, PsiManager manager) {
  for (VirtualFile vFile : vFiles) {
    if (ModuleUtil.findModuleForFile(vFile, module.getProject()) != module) continue;
    PsiDirectory directory = manager.findDirectory(vFile);
    if (directory != null && directory.isValid() && directory.isWritable()) {
      return directory;
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:RootIndex.java   
@NotNull
public Query<VirtualFile> getDirectoriesByPackageName(@NotNull final String packageName, final boolean includeLibrarySources) {
  // Note that this method is used in upsource as well, hence, don't reduce this method's visibility.
  List<VirtualFile> result = myPackageDirectoryCache.getDirectoriesByPackageName(packageName);
  if (!includeLibrarySources) {
    result = ContainerUtil.filter(result, new Condition<VirtualFile>() {
      @Override
      public boolean value(VirtualFile file) {
        DirectoryInfo info = getInfoForFile(file);
        return info.isInProject() && (!info.isInLibrarySource() || info.isInModuleSource() || info.hasLibraryClassRoot());
      }
    });
  }
  return new CollectionQuery<VirtualFile>(result);
}
项目:intellij-ce-playground    文件:VarargParameterInspection.java   
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PsiMethod method = (PsiMethod)element.getParent();
  final PsiParameterList parameterList = method.getParameterList();
  final PsiParameter[] parameters = parameterList.getParameters();
  final PsiParameter lastParameter = parameters[parameters.length - 1];
  if (!lastParameter.isVarArgs()) {
    return;
  }
  final PsiEllipsisType type = (PsiEllipsisType)lastParameter.getType();
  final Query<PsiReference> query = ReferencesSearch.search(method);
  final PsiType componentType = type.getComponentType();
  final String typeText;
  if (componentType instanceof PsiClassType) {
    final PsiClassType classType = (PsiClassType)componentType;
    typeText = classType.rawType().getCanonicalText();
  } else {
    typeText = componentType.getCanonicalText();
  }
  final Collection<PsiReference> references = query.findAll();
  for (PsiReference reference : references) {
    modifyCalls(reference, typeText, parameters.length - 1);
  }
  final PsiType arrayType = type.toArrayType();
  final PsiManager psiManager = lastParameter.getManager();
  final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
  final PsiTypeElement newTypeElement = factory.createTypeElement(arrayType);
  final PsiTypeElement typeElement = lastParameter.getTypeElement();
  if (typeElement == null) {
    return;
  }
  final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, "java.lang.SafeVarargs");
  if (annotation != null) {
    annotation.delete();
  }
  typeElement.replace(newTypeElement);
}
项目:intellij-ce-playground    文件:InplaceRefactoring.java   
protected Collection<PsiReference> collectRefs(SearchScope referencesSearchScope) {
  final Query<PsiReference> search = ReferencesSearch.search(myElementToRename, referencesSearchScope, false);

  final CommonProcessors.CollectProcessor<PsiReference> processor = new CommonProcessors.CollectProcessor<PsiReference>() {
    @Override
    protected boolean accept(PsiReference reference) {
      return acceptReference(reference);
    }
  };

  search.forEach(processor);
  return processor.getResults();
}
项目:intellij-ce-playground    文件:CallerChooserBase.java   
protected Collection<PsiElement> findElementsToHighlight(M caller, PsiElement callee) {
  Query<PsiReference> references = ReferencesSearch.search(callee, new LocalSearchScope(caller), false);
  return ContainerUtil.mapNotNull(references, new Function<PsiReference, PsiElement>() {
    @Override
    public PsiElement fun(PsiReference psiReference) {
      return psiReference.getElement();
    }
  });
}
项目:intellij-ce-playground    文件:PyLineMarkerNavigator.java   
public void navigate(final MouseEvent e, final T elt) {
  final List<NavigatablePsiElement> navElements = new ArrayList<NavigatablePsiElement>();
  Query<T> elementQuery = search(elt);
  if (elementQuery == null) return;
  elementQuery.forEach(new Processor<T>() {
    public boolean process(final T psiElement) {
      if (psiElement instanceof NavigatablePsiElement) {
        navElements.add((NavigatablePsiElement)psiElement);
      }
      return true;
    }
  });
  final NavigatablePsiElement[] methods = navElements.toArray(new NavigatablePsiElement[navElements.size()]);
  PsiElementListNavigator.openTargets(e, methods, getTitle(elt), null, new DefaultPsiElementCellRenderer());
}
项目:intellij-ce-playground    文件:PyLineMarkerProvider.java   
@Nullable
protected Query<PsiElement> search(final PsiElement elt) {
  List<PsiElement> result = new ArrayList<PsiElement>();
  PyClass containingClass = PsiTreeUtil.getParentOfType(elt, PyClass.class);
  if (containingClass != null && elt instanceof PyTargetExpression) {
    for (PyClass ancestor : containingClass.getAncestorClasses(null)) {
      final PyTargetExpression attribute = ancestor.findClassAttribute(((PyTargetExpression)elt).getReferencedName(), false);
      if (attribute != null) {
        result.add(attribute);
      }
    }
  }
  return new CollectionQuery<PsiElement>(result);
}
项目:intellij-ce-playground    文件:ConvertVarargParameterToArrayIntention.java   
private static void convertVarargsToArray(PsiParameterList parameterList)
  throws IncorrectOperationException {
  final PsiParameter[] parameters = parameterList.getParameters();
  if (parameters.length == 0) {
    return;
  }
  final PsiParameter lastParameter = parameters[parameters.length - 1];
  if (lastParameter == null || !lastParameter.isVarArgs()) {
    return;
  }
  final PsiEllipsisType type =
    (PsiEllipsisType)lastParameter.getType();
  final PsiMethod method = (PsiMethod)parameterList.getParent();
  final Query<PsiReference> query = ReferencesSearch.search(method);
  final PsiType componentType = type.getComponentType();
  final String typeText = componentType.getCanonicalText();
  final int parameterIndex =
    parameterList.getParameterIndex(lastParameter);
  for (PsiReference reference : query) {
    final PsiElement referenceElement = reference.getElement();
    if (!(referenceElement instanceof PsiReferenceExpression)) {
      continue;
    }
    final PsiReferenceExpression referenceExpression =
      (PsiReferenceExpression)referenceElement;
    final PsiMethodCallExpression methodCallExpression =
      (PsiMethodCallExpression)referenceExpression.getParent();
    modifyCall(methodCallExpression, typeText, parameterIndex);
  }
  final PsiType arrayType = type.toArrayType();
  final Project project = lastParameter.getProject();
  final PsiElementFactory factory =
    JavaPsiFacade.getElementFactory(project);
  final PsiTypeElement newTypeElement =
    factory.createTypeElement(arrayType);
  final PsiTypeElement typeElement =
    lastParameter.getTypeElement();
  typeElement.replace(newTypeElement);
}