Java 类com.intellij.psi.search.searches.ReferencesSearch 实例源码

项目:AppleScript-IDEA    文件:AppleScriptDictionaryComponentReferencesSearch.java   
private Boolean doExecute(ReferencesSearch.SearchParameters queryParameters, final Processor<PsiReference> consumer) {
  final PsiElement element = queryParameters.getElementToSearch(); //was selector_identifier->redefined in
  DictionaryComponent dictionaryComponent = null;
  if (element instanceof DictionaryComponent) {
    dictionaryComponent = (DictionaryComponent) element;
  }

  if (dictionaryComponent == null) return true;

  final List<String> parts = dictionaryComponent.getNameIdentifiers();
  if (parts.isEmpty())
    return true;
  final String componentName = dictionaryComponent.getName(); //or just getName()...
  final PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(element.getProject());

  String searchWord = parts.get(0);
  return searchWord.isEmpty() || helper.processElementsWithWord(new MyOccurrenceProcessor(dictionaryComponent, componentName, consumer), 
      queryParameters.getScopeDeterminedByUser(), searchWord, UsageSearchContext.IN_CODE, true);

}
项目:jgiven-intellij-plugin    文件:ReferenceProviderTest.java   
@Test
public void should_process_reference() throws Exception {
    // given
    PsiReference reference1 = mock(PsiReference.class);
    PsiReference reference2 = mock(PsiReference.class);

    PsiField field = mock(PsiField.class);
    ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class);
    when(searchParameters.getElementToSearch()).thenReturn(field);
    when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(GlobalSearchScope.class));
    when(scenarioStateReferenceProvider.findReferences(field)).thenReturn(Arrays.asList(reference1, reference2));
    when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(true);

    // when
    referenceProvider.processQuery(searchParameters, processor);

    // then
    verify(processor).process(reference1);
    verify(processor).process(reference2);
}
项目: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    文件:InputVariables.java   
public void removeParametersUsedInExitsOnly(PsiElement codeFragment,
                                            Collection<PsiStatement> exitStatements,
                                            ControlFlow controlFlow,
                                            int startOffset,
                                            int endOffset) {
  final LocalSearchScope scope = new LocalSearchScope(codeFragment);
  Variables:
  for (Iterator<VariableData> iterator = myInputVariables.iterator(); iterator.hasNext();) {
    final VariableData data = iterator.next();
    for (PsiReference ref : ReferencesSearch.search(data.variable, scope)) {
      PsiElement element = ref.getElement();
      int elementOffset = controlFlow.getStartOffset(element);
      if (elementOffset >= startOffset && elementOffset <= endOffset) {
        if (!isInExitStatements(element, exitStatements)) continue Variables;
      }
    }
    iterator.remove();
  }
}
项目:intellij-ce-playground    文件:FieldCanBeLocalInspection.java   
@Nullable
@Override
protected PsiElement moveDeclaration(@NotNull final Project project, @NotNull final PsiField variable) {
  final Map<PsiCodeBlock, Collection<PsiReference>> refs = new HashMap<PsiCodeBlock, Collection<PsiReference>>();
  if (!groupByCodeBlocks(ReferencesSearch.search(variable).findAll(), refs)) return null;
  PsiElement element = null;
  for (Collection<PsiReference> psiReferences : refs.values()) {
    element = super.moveDeclaration(project, variable, psiReferences, false);
  }
  if (element != null) {
    final PsiElement finalElement = element;
    Runnable runnable = new Runnable() {
      public void run() {
        beforeDelete(project, variable, finalElement);
        variable.normalizeDeclaration();
        variable.delete();
      }
    };
    ApplicationManager.getApplication().runWriteAction(runnable);
  }
  return element;
}
项目:intellij-ce-playground    文件:NullityInferrer.java   
private boolean variableSometimesAssignedNull(@NotNull PsiVariable variable) {
  final PsiExpression initializer = variable.getInitializer();
  if (initializer != null && expressionIsSometimesNull(initializer)) {
    return true;
  }
  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) && expressionIsSometimesNull(assignment.getRExpression())) {
      return true;
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:JavaWithRunnableSurrounder.java   
private static boolean canBeDeclaredFinal(@NotNull final PsiVariable variable, @Nullable final PsiElement scope) {
  if (scope == null) {
    return false;
  }
  final Collection<PsiReference> references = ReferencesSearch.search(variable, new LocalSearchScope(scope)).findAll();
  boolean foundOnce = (variable instanceof PsiParameter) || (variable.getInitializer() != null);
  for (PsiReference reference : references) {
    if (reference instanceof PsiReferenceExpression) {
      if (PsiUtil.isAccessedForWriting((PsiReferenceExpression) reference)) {
        if (foundOnce) {
          return false;
        }
        foundOnce = true;
      }
    }
  }
  return true;
}
项目:intellij-ce-playground    文件:SliceUtil.java   
private static void addContainerReferences(@NotNull PsiVariable variable,
                                           @NotNull final Processor<SliceUsage> processor,
                                           @NotNull final SliceUsage parent,
                                           @NotNull final PsiSubstitutor parentSubstitutor,
                                           final int indexNesting,
                                           @NotNull final String syntheticField) {
  if (indexNesting != 0) {
    ReferencesSearch.search(variable).forEach(new Processor<PsiReference>() {
      @Override
      public boolean process(PsiReference reference) {
        PsiElement element = reference.getElement();
        if (element instanceof PsiExpression && !element.getManager().areElementsEquivalent(element, parent.getElement())) {
          PsiExpression expression = (PsiExpression)element;
          if (!addContainerItemModification(expression, processor, parent, parentSubstitutor, indexNesting, syntheticField)) return false;
        }
        return true;
      }
    });
  }
}
项目:intellij-ce-playground    文件:StaticIconFieldsAction.java   
private static void searchFields(final PsiClass allIcons, final UsageView view, final ProgressIndicator indicator) {
  ApplicationManager.getApplication().runReadAction(new Runnable() {
    @Override
    public void run() {
      indicator.setText("Searching for: " + allIcons.getQualifiedName());
    }
  });

  ReferencesSearch.search(allIcons).forEach(new Processor<PsiReference>() {
    @Override
    public boolean process(PsiReference reference) {
      PsiElement elt = reference.getElement();

      while (elt instanceof PsiExpression) elt = elt.getParent();

      if (elt instanceof PsiField) {
        UsageInfo info = new UsageInfo(elt, false);
        view.appendUsage(new UsageInfo2UsageAdapter(info));
      }

      return true;
    }
  });
}
项目:intellij-ce-playground    文件:EncapsulateFieldsProcessor.java   
@NotNull protected UsageInfo[] findUsages() {
  ArrayList<EncapsulateFieldUsageInfo> array = ContainerUtil.newArrayList();
  for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
    for (final PsiReference reference : ReferencesSearch.search(fieldDescriptor.getField())) {
      final PsiElement element = reference.getElement();
      if (element == null) continue;

      final EncapsulateFieldHelper helper = EncapsulateFieldHelper.getHelper(element.getLanguage());
      if (helper != null) {
        EncapsulateFieldUsageInfo usageInfo = helper.createUsage(myDescriptor, fieldDescriptor, reference);
        if (usageInfo != null) {
          array.add(usageInfo);
        }
      }
    }
  }
  EncapsulateFieldUsageInfo[] usageInfos = array.toArray(new EncapsulateFieldUsageInfo[array.size()]);
  return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
项目:intellij-ce-playground    文件:MoveFilesOrDirectoriesProcessor.java   
@Override
@NotNull
protected UsageInfo[] findUsages() {
  ArrayList<UsageInfo> result = new ArrayList<UsageInfo>();
  for (int i = 0; i < myElementsToMove.length; i++) {
    PsiElement element = myElementsToMove[i];
    if (mySearchForReferences) {
      for (PsiReference reference : ReferencesSearch.search(element, GlobalSearchScope.projectScope(myProject))) {
        result.add(new MyUsageInfo(reference.getElement(), i, reference));
      }
    }
    findElementUsages(result, element);
  }

  return result.toArray(new UsageInfo[result.size()]);
}
项目:intellij-ce-playground    文件:FindParameterTest.java   
public void testMethod() throws Exception {
  String text =
          "void method(final int i) {" +
          "  Runnable runnable = new Runnable() {" +
          "    public void run() {" +
          "      System.out.println(i);" +
          "    }" +
          "  };" +
          "  System.out.println(i);" +
          "}";
  final PsiManager psiManager = PsiManager.getInstance(myProject);
  final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
  final PsiMethod methodFromText = elementFactory.createMethodFromText(text, null);
  final PsiParameter[] parameters = methodFromText.getParameterList().getParameters();
  final PsiReference[] references =
    ReferencesSearch.search(parameters[0], new LocalSearchScope(methodFromText), false).toArray(new PsiReference[0]);
  Assert.assertEquals(references.length, 2);
}
项目:intellij-ce-playground    文件:JavaFxRelatedItemLineMarkerProvider.java   
private static <T> void collectTargets(PsiField field, final ArrayList<T> targets, final Function<PsiElement, T> fun, final boolean stopAtFirst) {
  final PsiClass containingClass = field.getContainingClass();
  LOG.assertTrue(containingClass != null);
  final String qualifiedName = containingClass.getQualifiedName();
  LOG.assertTrue(qualifiedName != null);
  final List<VirtualFile> fxmls = JavaFxControllerClassIndex.findFxmlsWithController(field.getProject(), qualifiedName);
  if (fxmls.isEmpty()) return;
  ReferencesSearch.search(field, GlobalSearchScope.filesScope(field.getProject(), fxmls)).forEach(
    new Processor<PsiReference>() {
      @Override
      public boolean process(PsiReference reference) {
        final PsiElement referenceElement = reference.getElement();
        if (referenceElement == null) return true;
        final PsiFile containingFile = referenceElement.getContainingFile();
        if (containingFile == null) return true;
        if (!JavaFxFileTypeFactory.isFxml(containingFile)) return true;
        if (!(referenceElement instanceof XmlAttributeValue)) return true;
        final XmlAttributeValue attributeValue = (XmlAttributeValue)referenceElement;
        final PsiElement parent = attributeValue.getParent();
        if (!(parent instanceof XmlAttribute)) return true;
        if (!FxmlConstants.FX_ID.equals(((XmlAttribute)parent).getName())) return true;
        targets.add(fun.fun(parent));
        return !stopAtFirst;
      }
  });
}
项目:intellij-ce-playground    文件:MoveMembersProcessor.java   
@NotNull
protected UsageInfo[] findUsages() {
  final List<UsageInfo> usagesList = new ArrayList<UsageInfo>();
  for (PsiMember member : myMembersToMove) {
    for (PsiReference psiReference : ReferencesSearch.search(member)) {
      PsiElement ref = psiReference.getElement();
      final MoveMemberHandler handler = MoveMemberHandler.EP_NAME.forLanguage(ref.getLanguage());
      MoveMembersUsageInfo usage = null;
      if (handler != null && myTargetClass != null) {
        usage = handler.getUsage(member, psiReference, myMembersToMove, myTargetClass);
      }
      if (usage != null) {
        usagesList.add(usage);
      }
      else {
        if (!isInMovedElement(ref)) {
          usagesList.add(new MoveMembersUsageInfo(member, ref, null, ref, psiReference));
        }
      }
    }
  }
  UsageInfo[] usageInfos = usagesList.toArray(new UsageInfo[usagesList.size()]);
  usageInfos = UsageViewUtil.removeDuplicatedUsages(usageInfos);
  return usageInfos;
}
项目:intellij-ce-playground    文件:PyStringReferenceSearch.java   
public void processQuery(@NotNull final ReferencesSearch.SearchParameters params,
                         @NotNull final Processor<PsiReference> consumer) {
  final PsiElement element = params.getElementToSearch();
  if (!(element instanceof PyElement) && !(element instanceof PsiDirectory)) {
    return;
  }

  SearchScope searchScope = params.getEffectiveSearchScope();
  if (searchScope instanceof GlobalSearchScope) {
    searchScope = GlobalSearchScope.getScopeRestrictedByFileTypes((GlobalSearchScope)searchScope, PythonFileType.INSTANCE);
  }

  String name = PyUtil.computeElementNameForStringSearch(element);

  if (StringUtil.isEmpty(name)) {
    return;
  }
  params.getOptimizer().searchWord(name, searchScope, UsageSearchContext.IN_STRINGS, true, element);
}
项目:intellij-ce-playground    文件:MoveClassesOrPackagesUtil.java   
public static UsageInfo[] findUsages(final PsiElement element,
                                     boolean searchInStringsAndComments,
                                     boolean searchInNonJavaFiles,
                                     final String newQName) {
  PsiManager manager = element.getManager();

  ArrayList<UsageInfo> results = new ArrayList<UsageInfo>();
  Set<PsiReference> foundReferences = new HashSet<PsiReference>();

  GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
  for (PsiReference reference : ReferencesSearch.search(element, projectScope, false)) {
    TextRange range = reference.getRangeInElement();
    if (foundReferences.contains(reference)) continue;
    results.add(new MoveRenameUsageInfo(reference.getElement(), reference, range.getStartOffset(), range.getEndOffset(), element, false));
    foundReferences.add(reference);
  }

  findNonCodeUsages(searchInStringsAndComments, searchInNonJavaFiles, element, newQName, results);
  preprocessUsages(results);
  return results.toArray(new UsageInfo[results.size()]);
}
项目:intellij-ce-playground    文件:BindingProperty.java   
private static boolean isFieldUnreferenced(final PsiField field) {
  try {
    return ReferencesSearch.search(field).forEach(new Processor<PsiReference>() {
      public boolean process(final PsiReference t) {
        PsiFile f = t.getElement().getContainingFile();
        if (f != null && f.getFileType().equals(StdFileTypes.GUI_DESIGNER_FORM)) {
          return true;
        }
        PsiMethod method = PsiTreeUtil.getParentOfType(t.getElement(), PsiMethod.class);
        if (method != null && method.getName().equals(AsmCodeGenerator.SETUP_METHOD_NAME)) {
          return true;
        }
        return false;
      }
    });
  }
  catch (IndexNotReadyException e) {
    return false;
  }
}
项目:intellij-ce-playground    文件:ConvertToVarargsMethodFix.java   
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement parent = element.getParent();
  if (!(parent instanceof PsiMethod)) {
    return;
  }
  final PsiMethod method = (PsiMethod)parent;
  final Collection<PsiElement> writtenElements = new ArrayList<PsiElement>();
  final Collection<PsiReferenceExpression> methodCalls = new ArrayList<PsiReferenceExpression>();
  writtenElements.add(method);
  for (final PsiReference reference : ReferencesSearch.search(method, method.getUseScope(), false)) {
    final PsiElement referenceElement = reference.getElement();
    if (referenceElement instanceof PsiReferenceExpression) {
      writtenElements.add(referenceElement);
      methodCalls.add((PsiReferenceExpression)referenceElement);
    }
  }
  if (!FileModificationService.getInstance().preparePsiElementsForWrite(writtenElements)) {
    return;
  }
  makeMethodVarargs(method);
  makeMethodCallsVarargs(methodCalls);
}
项目:intellij-ce-playground    文件:GrIntroduceHandlerBase.java   
public static PsiElement[] collectVariableUsages(GrVariable variable, PsiElement scope) {
  final List<PsiElement> list = Collections.synchronizedList(new ArrayList<PsiElement>());
  if (scope instanceof GroovyScriptClass) {
    scope = scope.getContainingFile();
  }
  ReferencesSearch.search(variable, new LocalSearchScope(scope)).forEach(new Processor<PsiReference>() {
    @Override
    public boolean process(PsiReference psiReference) {
      final PsiElement element = psiReference.getElement();
      if (element != null) {
        list.add(element);
      }
      return true;
    }
  });
  return list.toArray(new PsiElement[list.size()]);
}
项目:intellij-ce-playground    文件:IntroduceFieldCentralPanel.java   
private boolean initializedInSetUp(Set<PsiField> fields) {
  if (hasSetUpChoice()) {
    for (PsiField field : fields) {
      final PsiMethod setUpMethod = TestFrameworks.getInstance().findSetUpMethod((field).getContainingClass());
      if (setUpMethod != null) {
        final Processor<PsiReference> initializerSearcher = new Processor<PsiReference>() {
          @Override
          public boolean process(PsiReference reference) {
            final PsiElement referenceElement = reference.getElement();
            if (referenceElement instanceof PsiExpression) {
              return !PsiUtil.isAccessedForWriting((PsiExpression)referenceElement);
            }
            return true;
          }
        };
        if (ReferencesSearch.search(field, new LocalSearchScope(setUpMethod)).forEach(initializerSearcher)) {
          return false;
        }
      }
    }
    return true;
  }
  return false;
}
项目:intellij-ce-playground    文件:SearchUtils.java   
public static Iterable<PsiReference> findAllReferences(PsiElement element, SearchScope scope){

        return new ArrayIterable<PsiReference>(ReferencesSearch.search(element, scope, true).toArray(new PsiReference[0]));
/*
        try {
            Class<?> searchClass = Class.forName("com.intellij.psi.search.searches.ReferencesSearch");

            final Method[] methods = searchClass.getMethods();
            for (Method method : methods) {
                if ("search".equals(method.getName()) &&) {
                    return (Iterable<PsiReference>) method.invoke(null, element, scope, true);
                }
            }
            return null;
        } catch (ClassNotFoundException ignore) {
            return null;
        } catch (IllegalAccessException ignore) {
            return null;
        } catch (InvocationTargetException ignore) {
            return null;
        }
        return ReferencesSearch.search(element, scope, true).findAll();
        */
    }
项目:intellij-ce-playground    文件:StringEditorDialog.java   
private static Collection<PsiReference> findPropertyReferences(final Property pproperty, final Module module) {
  final Collection<PsiReference> references = Collections.synchronizedList(new ArrayList<PsiReference>());
  ProgressManager.getInstance().runProcessWithProgressSynchronously(
        new Runnable() {
      public void run() {
        ReferencesSearch.search(pproperty).forEach(new Processor<PsiReference>() {
          public boolean process(final PsiReference psiReference) {
            PsiMethod method = PsiTreeUtil.getParentOfType(psiReference.getElement(), PsiMethod.class);
            if (method == null || !AsmCodeGenerator.SETUP_METHOD_NAME.equals(method.getName())) {
              references.add(psiReference);
            }
            return true;
          }
        });
      }
    }, UIDesignerBundle.message("edit.text.searching.references"), false, module.getProject()
  );
  return references;
}
项目:intellij-ce-playground    文件:NonThreadSafeLazyInitializationInspection.java   
private static boolean isStaticAndAssignedOnce(PsiField field) {
  if (!field.hasModifierProperty(PsiModifier.STATIC)) {
    return false;
  }
  final int[] writeCount = new int[1];
  return ReferencesSearch.search(field).forEach(new Processor<PsiReference>() {
    @Override
    public boolean process(PsiReference reference) {
      final PsiElement element = reference.getElement();
      if (!(element instanceof PsiExpression) || !PsiUtil.isAccessedForWriting((PsiExpression)element)) {
        return true;
      }
      return ++writeCount[0] != 2;
    }
  });
}
项目:intellij-ce-playground    文件:InlineUtil.java   
public static boolean allUsagesAreTailCalls(final PsiMethod method) {
  final List<PsiReference> nonTailCallUsages = Collections.synchronizedList(new ArrayList<PsiReference>());
  boolean result = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
    @Override
    public void run() {
      ReferencesSearch.search(method).forEach(new Processor<PsiReference>() {
        @Override
        public boolean process(final PsiReference psiReference) {
          ProgressManager.checkCanceled();
          if (getTailCallType(psiReference) == TailCallType.None) {
            nonTailCallUsages.add(psiReference);
            return false;
          }
          return true;
        }
      });
    }
  }, RefactoringBundle.message("inline.method.checking.tail.calls.progress"), true, method.getProject());
  return result && nonTailCallUsages.isEmpty();
}
项目:intellij-ce-playground    文件:SafeDeleteJavaCallerChooser.java   
private PsiParameter getParameter(PsiMethod caller) {

      //do not change hierarchy
      if (caller.findDeepestSuperMethods().length > 0) {
        return null;
      }

      //find first method call
      final Ref<PsiParameter> ref = new Ref<PsiParameter>();
      ReferencesSearch.search(myMethod, new LocalSearchScope(caller)).forEach(new Processor<PsiReference>() {
        @Override
        public boolean process(PsiReference reference) {
          final PsiElement element = reference.getElement();
          if (element instanceof PsiReferenceExpression) {
            final PsiElement elementParent = element.getParent();
            if (elementParent instanceof PsiCallExpression) {
              ref.set(isTheOnlyOneParameterUsage(elementParent, myParameterIdx, myMethod));
              return false;
            }
          }
          return true;
        }
      });
      return ref.get();
    }
项目:intellij-ce-playground    文件:PyInvertBooleanDelegate.java   
@Override
public void collectRefElements(PsiElement psiElement,
                               @Nullable RenameProcessor renameProcessor,
                               @NotNull String newName,
                               Collection<PsiElement> elementsToInvert) {
  final Collection<PsiReference> refs = ReferencesSearch.search(psiElement).findAll();

  for (PsiReference ref : refs) {
    final PsiElement refElement = ref.getElement();
    final PsiElement elementToInvert = getElementToInvert(psiElement, refElement);
    if (elementToInvert != null) {
      elementsToInvert.add(elementToInvert);
    }
    else {
      ContainerUtil.addIfNotNull(elementsToInvert, getForeignElementToInvert(psiElement, refElement, PythonLanguage.getInstance()));
    }
  }
}
项目:intellij-ce-playground    文件:ClassTypeArgumentMigrationProcessor.java   
private void processMemberType(final PsiElement element,
                               final TypeParameterSearcher parameterSearcher,
                               final PsiClass psiClass,
                               final PsiSubstitutor substitutor,
                               final Map<PsiElement, Pair<PsiReference[], PsiType>> roots) {
  final PsiType elementType = TypeMigrationLabeler.getElementType(element);
  if (elementType != null && elementType.accept(parameterSearcher).booleanValue()) {
    final PsiType memberType = substitutor.substitute(elementType);

    prepareMethodsChangeSignature(psiClass, element, memberType);

    final List<PsiReference> refs = TypeMigrationLabeler.filterReferences(psiClass, ReferencesSearch.search(element, psiClass.getUseScope()));

    roots.put(element, Pair.create(myLabeler.markRootUsages(element, memberType, refs.toArray(new PsiReference[refs.size()])), memberType));
  }
}
项目: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    文件:ReassignVariableUtil.java   
static void replaceWithAssignment(final PsiDeclarationStatement declaration, final PsiVariable variable, final Editor editor) {
  final PsiVariable var = (PsiVariable)declaration.getDeclaredElements()[0];
  final PsiExpression initializer = var.getInitializer();
  new WriteCommandAction(declaration.getProject()) {
    @Override
    protected void run(@NotNull Result result) throws Throwable {
      final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(variable.getProject());
      final String chosenVariableName = variable.getName();
      //would generate red code for final variables
      PsiElement newDeclaration = elementFactory.createStatementFromText(chosenVariableName + " = " + initializer.getText() + ";", declaration);
      final Collection<PsiReference> references = ReferencesSearch.search(var).findAll();
      newDeclaration = declaration.replace(newDeclaration);
      for (PsiReference reference : references) {
        final PsiElement element = reference.getElement();
        if (element instanceof PsiExpression) {
          element.replace(elementFactory.createExpressionFromText(chosenVariableName, newDeclaration));
        }
      }
    }
  }.execute();
  finishTemplate(editor);
}
项目:AppleScript-IDEA    文件:AppleScriptHandlerReferencesSearch.java   
@Override
public boolean execute(@NotNull final ReferencesSearch.SearchParameters queryParameters, @NotNull final
Processor<PsiReference> consumer) {
  return new ReadAction<Boolean>() {
    protected void run(@NotNull final Result<Boolean> result) {
      result.setResult(doExecute(queryParameters, consumer));
    }
  }.execute().getResultObject();
}
项目:AppleScript-IDEA    文件:AppleScriptDictionaryComponentReferencesSearch.java   
@Override
public boolean execute(@NotNull final ReferencesSearch.SearchParameters queryParameters, @NotNull final
Processor<PsiReference> consumer) {
  return new ReadAction<Boolean>() {
    protected void run(@NotNull final Result<Boolean> result) {
      result.setResult(doExecute(queryParameters, consumer));
    }
  }.execute().getResultObject();
}
项目:jgiven-intellij-plugin    文件:ReferenceProvider.java   
@Override
public void processQuery(@NotNull ReferencesSearch.SearchParameters queryParameters, @NotNull Processor<PsiReference> consumer) {
    final PsiElement element = queryParameters.getElementToSearch();

    ApplicationManager.getApplication().runReadAction(() -> {
        SearchScope scope = queryParameters.getEffectiveSearchScope();
        if (!scenarioStateProvider.isJGivenScenarioState(element)
                || !(scope instanceof GlobalSearchScope)) {
            return;
        }
        PsiField field = (PsiField) element;
        scenarioStateReferenceProvider.findReferences(field).forEach(consumer::process);
    });
}
项目:jgiven-intellij-plugin    文件:ReferenceProviderTest.java   
@Test
public void should_not_process_reference_if_search_scope_is_not_global() throws Exception {
    // given
    PsiField field = mock(PsiField.class);
    ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class);
    when(searchParameters.getElementToSearch()).thenReturn(field);
    when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(LocalSearchScope.class));
    when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(true);

    // when
    referenceProvider.processQuery(searchParameters, processor);

    // then
    verifyZeroInteractions(processor);
}
项目:jgiven-intellij-plugin    文件:ReferenceProviderTest.java   
@Test
public void should_not_process_reference_if_element_is_not_a_JGiven_scenario_state() throws Exception {
    // given
    PsiField field = mock(PsiField.class);
    ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class);
    when(searchParameters.getElementToSearch()).thenReturn(field);
    when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(GlobalSearchScope.class));
    when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(false);

    // when
    referenceProvider.processQuery(searchParameters, processor);

    // then
    verifyZeroInteractions(processor);
}
项目:hybris-integration-intellij-idea-plugin    文件:ImpexReferenceSearcher.java   
@Override
public void processQuery(
    @NotNull final ReferencesSearch.SearchParameters queryParameters,
    @NotNull final Processor<PsiReference> consumer
) {
    final PsiElement elementToSearch = queryParameters.getElementToSearch();
    if (!elementToSearch.isValid()) {
        return;
    }

    final SearchScope scope = queryParameters.getEffectiveSearchScope();
    if (!(scope instanceof GlobalSearchScope)) {
        return;
    }

    // search macros usage references
    if (isMacroUsage(elementToSearch) || isMacroNameDeclaration(elementToSearch)) {
        final PsiFile file = elementToSearch.getContainingFile();
        final PsiElement[] results = PsiTreeUtil.collectElements(
            file,
            element -> isMacroUsage(element) && element.textMatches(elementToSearch)
        );
        stream(results)
            .map(ImpexMacrosReferenceBase::new)
            .forEach(consumer::process);
    }
}
项目: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;
    }
  }
}
项目:lua-for-idea    文件:LuaAliasedElementSearcher.java   
@Override
public void processQuery(@NotNull ReferencesSearch.SearchParameters parameters, @NotNull Processor<PsiReference> consumer) {
  final PsiElement target = parameters.getElementToSearch();
  if (!(target instanceof PsiNamedElement)) return;

  final String name = ((PsiNamedElement)target).getName();
  if (name == null || StringUtil.isEmptyOrSpaces(name)) return;

  final SearchScope scope = parameters.getEffectiveSearchScope();

  final SearchRequestCollector collector = parameters.getOptimizer();
  final SearchSession session = collector.getSearchSession();

  collector.searchWord(name, scope, UsageSearchContext.IN_CODE, true, new MyProcessor(target, null, session));
}
项目:intellij-ce-playground    文件:SafeDeleteProcessor.java   
public static void findGenericElementUsages(final PsiElement element, final List<UsageInfo> usages, final PsiElement[] allElementsToDelete) {
  ReferencesSearch.search(element).forEach(new Processor<PsiReference>() {
    @Override
    public boolean process(final PsiReference reference) {
      final PsiElement refElement = reference.getElement();
      if (!isInside(refElement, allElementsToDelete)) {
        usages.add(new SafeDeleteReferenceSimpleDeleteUsageInfo(refElement, element, false));
      }
      return true;
    }
  });
}
项目:intellij-ce-playground    文件:PsiAnnotationMethodReferencesSearcher.java   
@Override
public boolean execute(@NotNull final ReferencesSearch.SearchParameters p, @NotNull final Processor<PsiReference> consumer) {
  final PsiElement refElement = p.getElementToSearch();
  boolean isAnnotation = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
    @Override
    public Boolean compute() {
      return PsiUtil.isAnnotationMethod(refElement);
    }
  });
  if (isAnnotation) {
    final PsiMethod method = (PsiMethod)refElement;
    PsiClass containingClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {
      @Override
      public PsiClass compute() {
        boolean isValueMethod =
          PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.equals(method.getName()) && method.getParameterList().getParametersCount() == 0;
        return isValueMethod ? method.getContainingClass() : null;
      }
    });
    if (containingClass != null) {
      SearchScope scope = ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
        @Override
        public SearchScope compute() {
          return p.getEffectiveSearchScope();
        }
      });
      final Query<PsiReference> query = ReferencesSearch.search(containingClass, scope, p.isIgnoreAccessScope());
      return query.forEach(createImplicitDefaultAnnotationMethodConsumer(consumer));
    }
  }

  return true;
}