类com.intellij.psi.search.LocalSearchScope源码实例Demo

下面列出了怎么用com.intellij.psi.search.LocalSearchScope的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public boolean execute(@Nonnull final AllTypesSearch.SearchParameters queryParameters, @Nonnull final Processor<? super DotNetTypeDeclaration> consumer)
{
	SearchScope scope = queryParameters.getScope();

	if(scope instanceof GlobalSearchScope)
	{
		return processAllClassesInGlobalScope((GlobalSearchScope) scope, consumer, queryParameters);
	}

	PsiElement[] scopeRoots = ((LocalSearchScope) scope).getScope();
	for(final PsiElement scopeRoot : scopeRoots)
	{
		if(!processScopeRootForAllClasses(scopeRoot, consumer))
		{
			return false;
		}
	}
	return true;
}
 
源代码2 项目: consulo-csharp   文件: CSharpLocalVariableImpl.java
@Nonnull
@Override
public SearchScope getUseScope()
{
	PsiElement parent = getParent();
	if(parent instanceof CSharpLocalVariableDeclarationStatement)
	{
		return new LocalSearchScope(parent.getParent());
	}
	else if(parent instanceof CSharpForeachStatementImpl ||
			parent instanceof CSharpUsingStatementImpl ||
			parent instanceof CSharpFixedStatementImpl ||
			parent instanceof CSharpForStatementImpl ||
			parent instanceof CSharpCatchStatementImpl)
	{
		return new LocalSearchScope(parent);
	}
	LOG.error("Global usage scope for local variable, parent: " + parent.getClass().getName());
	return super.getUseScope();
}
 
源代码3 项目: consulo   文件: AnalysisScope.java
public boolean contains(@Nonnull VirtualFile file) {
  if (myFilesSet == null) {
    if (myType == CUSTOM) {
      // optimization
      if (myScope instanceof GlobalSearchScope) return ((GlobalSearchScope)myScope).contains(file);
      if (myScope instanceof LocalSearchScope) return ((LocalSearchScope)myScope).isInScope(file);
    }
    if (myType == PROJECT) {  //optimization
      final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
      return index.isInContent(file) && (myIncludeTestSource || !index.isInTestSourceContent(file));
    }
    initFilesSet();
  }

  return myFilesSet.contains(file);
}
 
源代码4 项目: consulo   文件: PsiElement2UsageTargetAdapter.java
@Override
public void highlightUsages(@Nonnull PsiFile file, @Nonnull Editor editor, boolean clearHighlights) {
  PsiElement target = getElement();

  if (file instanceof PsiCompiledFile) file = ((PsiCompiledFile)file).getDecompiledPsiFile();

  Project project = target.getProject();
  final FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager();
  final FindUsagesHandler handler = findUsagesManager.getFindUsagesHandler(target, true);

  // in case of injected file, use host file to highlight all occurrences of the target in each injected file
  PsiFile context = InjectedLanguageManager.getInstance(project).getTopLevelFile(file);
  SearchScope searchScope = new LocalSearchScope(context);
  Collection<PsiReference> refs = handler == null ? ReferencesSearch.search(target, searchScope, false).findAll() : handler.findReferencesToHighlight(target, searchScope);

  new HighlightUsagesHandler.DoHighlightRunnable(new ArrayList<>(refs), project, target, editor, context, clearHighlights).run();
}
 
源代码5 项目: consulo   文件: MemberInplaceRenamer.java
@Override
protected boolean appendAdditionalElement(Collection<PsiReference> refs, Collection<Pair<PsiElement, TextRange>> stringUsages) {
  boolean showChooser = super.appendAdditionalElement(refs, stringUsages);
  PsiNamedElement variable = getVariable();
  if (variable != null) {
    final PsiElement substituted = getSubstituted();
    if (substituted != null) {
      appendAdditionalElement(stringUsages, variable, substituted);
      RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(substituted);
      final HashMap<PsiElement, String> allRenames = new HashMap<PsiElement, String>();
      PsiFile currentFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
      processor.prepareRenaming(substituted, "", allRenames, new LocalSearchScope(currentFile));
      for (PsiElement element : allRenames.keySet()) {
        appendAdditionalElement(stringUsages, variable, element);
      }
    }
  }
  return showChooser;
}
 
源代码6 项目: intellij   文件: BuildReferenceSearcher.java
/**
 * Search for package-local references.<br>
 * Returns null if the resulting scope is empty
 */
@Nullable
private static SearchScope limitScopeToFile(SearchScope scope, PsiFile file) {
  if (scope instanceof LocalSearchScope) {
    return ((LocalSearchScope) scope).isInScope(file.getVirtualFile())
        ? new LocalSearchScope(file)
        : null;
  }
  return scope.intersectWith(new LocalSearchScope(file));
}
 
源代码7 项目: intellij   文件: GlobReferenceSearcher.java
private static boolean inScope(SearchParameters queryParameters, BuildFile buildFile) {
  SearchScope scope = queryParameters.getScopeDeterminedByUser();
  if (scope instanceof GlobalSearchScope) {
    return ((GlobalSearchScope) scope).contains(buildFile.getVirtualFile());
  }
  return ((LocalSearchScope) scope).isInScope(buildFile.getVirtualFile());
}
 
@NotNull
@Override
protected IncrementableSet<SourceTargetPair> resolveRelationships() {
    PsiElement psiElement = getBaseElement();
    IncrementableSet<SourceTargetPair> incrementableSet = new IncrementableSet<>();

    for (DiagramNode<PsiElement> node : getNodes()) {
        PsiElement callee = node.getIdentifyingElement();

        Collection<PsiReference> all = ReferencesSearch.search(callee, new LocalSearchScope
                (psiElement)).findAll();

        for (PsiReference psiReference : all) {
            if (!(psiReference instanceof CompositePsiElement)) {
                continue;
            }
            PsiElement caller = PsiUtils.getRootPsiElement((PsiClass) psiElement, (CompositePsiElement) psiReference);

            if (caller == null) {
                continue;
            }

            incrementableSet.increment(new SourceTargetPair(caller, callee));
        }
    }
    return incrementableSet;
}
 
源代码9 项目: consulo-csharp   文件: CSharpParameterImpl.java
@Nonnull
@Override
public SearchScope getUseScope()
{
	PsiElement parent = getParent();
	if(parent instanceof DotNetParameterList)
	{
		return new LocalSearchScope(parent.getParent());
	}
	return super.getUseScope();
}
 
@RequiredReadAction
@Nonnull
public static LocalSearchScope createLocalScope(@Nonnull DotNetTypeDeclaration parent)
{
	DotNetTypeDeclaration type = selectCompositeOrSelfType(parent);
	if(type instanceof CSharpCompositeTypeDeclaration)
	{
		return new LocalSearchScope(((CSharpCompositeTypeDeclaration) type).getTypeDeclarations());
	}
	else
	{
		return new LocalSearchScope(parent);
	}
}
 
@RequiredReadAction
public static boolean mayRenameInplace(@Nonnull PsiElement elementToRename, @Nullable final PsiElement nameSuggestionContext)
{
	if(nameSuggestionContext != null && nameSuggestionContext.getContainingFile() != elementToRename.getContainingFile())
	{
		return false;
	}
	if(elementToRename instanceof CSharpTupleVariable || elementToRename instanceof CSharpTupleElementImpl)
	{
		return true;
	}
	if(elementToRename instanceof DotNetNamespaceAsElement)
	{
		return true;
	}
	if(!(elementToRename instanceof CSharpLocalVariable) && !(elementToRename instanceof DotNetParameter) && !(elementToRename instanceof
			CSharpLambdaParameter))
	{
		return false;
	}
	SearchScope useScope = PsiSearchHelper.getInstance(elementToRename.getProject()).getUseScope(elementToRename);
	if(!(useScope instanceof LocalSearchScope))
	{
		return false;
	}
	PsiElement[] scopeElements = ((LocalSearchScope) useScope).getScope();
	if(scopeElements.length > 1)
	{
		return false;    // ... and badly scoped resource variables
	}
	PsiFile containingFile = elementToRename.getContainingFile();
	return PsiTreeUtil.isAncestor(containingFile, scopeElements[0], false);
}
 
源代码12 项目: intellij-haxe   文件: HaxePsiFieldImpl.java
@NotNull
@Override
public SearchScope getUseScope() {
  final PsiElement localVar = UsefulPsiTreeUtil.getParentOfType(this, HaxeLocalVarDeclaration.class);
  if (localVar != null) {
    final PsiElement outerBlock = UsefulPsiTreeUtil.getParentOfType(localVar, HaxeBlockStatement.class);
    if (outerBlock != null) {
      return new LocalSearchScope(outerBlock);
    }
  }
  return super.getUseScope();
}
 
源代码13 项目: intellij-haxe   文件: HaxeMethodPsiMixinImpl.java
@NotNull
@Override
public SearchScope getUseScope() {
  if(this instanceof HaxeLocalFunctionDeclaration) {
    final PsiElement outerBlock = UsefulPsiTreeUtil.getParentOfType(this, HaxeBlockStatement.class);
    if(outerBlock != null) {
      return new LocalSearchScope(outerBlock);
    }
  }
  return super.getUseScope();
}
 
源代码14 项目: intellij-haxe   文件: HaxeNamedElementImpl.java
@NotNull
@Override
public SearchScope getUseScope() {
  final HaxeComponentType type = HaxeComponentType.typeOf(getParent());
  final HaxeComponent component = PsiTreeUtil.getParentOfType(getParent(), HaxeComponent.class, true);
  if (type == null || component == null) {
    return super.getUseScope();
  }
  if (type == HaxeComponentType.FUNCTION || type == HaxeComponentType.PARAMETER || type == HaxeComponentType.VARIABLE) {
    return new LocalSearchScope(component.getParent());
  }
  return super.getUseScope();
}
 
源代码15 项目: intellij-haxe   文件: HaxePullUpHelper.java
private boolean willBeUsedInSubclass(PsiElement member, PsiClass superclass, PsiClass subclass) {
  for (PsiReference ref : ReferencesSearch.search(member, new LocalSearchScope(subclass), false)) {
    PsiElement element = ref.getElement();
    if (!RefactoringHierarchyUtil.willBeInTargetClass(element, myMembersToMove, superclass, false)) {
      return true;
    }
  }
  return false;
}
 
源代码16 项目: intellij-xquery   文件: XQueryPsiImplUtil.java
public static SearchScope getUseScope(XQueryVarName element) {
    XQueryFunctionDecl function = PsiTreeUtil.getParentOfType(element, XQueryFunctionDecl.class, true);
    if (function != null) {
        return new LocalSearchScope(function);
    }
    XQueryQueryBody queryBody = PsiTreeUtil.getParentOfType(element, XQueryQueryBody.class, true);
    if (queryBody != null) {
        return new LocalSearchScope(queryBody);
    }
    return ResolveScopeManager.getElementUseScope(element);
}
 
源代码17 项目: consulo   文件: IdentifierHighlighterPass.java
@Nonnull
private static Couple<Collection<TextRange>> getUsages(@Nonnull PsiElement target, PsiElement psiElement, boolean withDeclarations, boolean detectAccess) {
  List<TextRange> readRanges = new ArrayList<>();
  List<TextRange> writeRanges = new ArrayList<>();
  final ReadWriteAccessDetector detector = detectAccess ? ReadWriteAccessDetector.findDetector(target) : null;
  final FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(target.getProject())).getFindUsagesManager();
  final FindUsagesHandler findUsagesHandler = findUsagesManager.getFindUsagesHandler(target, true);
  final LocalSearchScope scope = new LocalSearchScope(psiElement);
  Collection<PsiReference> refs = findUsagesHandler != null
                                  ? findUsagesHandler.findReferencesToHighlight(target, scope)
                                  : ReferencesSearch.search(target, scope).findAll();
  for (PsiReference psiReference : refs) {
    if (psiReference == null) {
      LOG.error("Null reference returned, findUsagesHandler=" + findUsagesHandler + "; target=" + target + " of " + target.getClass());
      continue;
    }
    List<TextRange> destination;
    if (detector == null || detector.getReferenceAccess(target, psiReference) == ReadWriteAccessDetector.Access.Read) {
      destination = readRanges;
    }
    else {
      destination = writeRanges;
    }
    HighlightUsagesHandler.collectRangesToHighlight(psiReference, destination);
  }

  if (withDeclarations) {
    final TextRange declRange = HighlightUsagesHandler.getNameIdentifierRange(psiElement.getContainingFile(), target);
    if (declRange != null) {
      if (detector != null && detector.isDeclarationWriteAccess(target)) {
        writeRanges.add(declRange);
      }
      else {
        readRanges.add(declRange);
      }
    }
  }

  return Couple.<Collection<TextRange>>of(readRanges, writeRanges);
}
 
源代码18 项目: consulo   文件: ScratchFileServiceImpl.java
@Nullable
@Override
public SearchScope getAdditionalUseScope(@Nonnull PsiElement element) {
  SearchScope useScope = element.getUseScope();
  if (useScope instanceof LocalSearchScope) return null;
  return ScratchesSearchScope.getScratchesScope(element.getProject());
}
 
源代码19 项目: consulo   文件: InplaceRefactoring.java
@Nullable
protected PsiElement checkLocalScope() {
  final SearchScope searchScope = PsiSearchHelper.SERVICE.getInstance(myElementToRename.getProject()).getUseScope(myElementToRename);
  if (searchScope instanceof LocalSearchScope) {
    final PsiElement[] elements = ((LocalSearchScope)searchScope).getScope();
    return PsiTreeUtil.findCommonParent(elements);
  }

  return null;
}
 
源代码20 项目: consulo   文件: 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();
    }
  });
}
 
源代码21 项目: bamboo-soy   文件: VariableDefinitionMixin.java
@NotNull
@Override
public SearchScope getUseScope() {
  PsiElement scopeElement = Scope.getFirstScopeParent(this);
  return scopeElement == null ? super.getUseScope() : new LocalSearchScope(scopeElement);
}
 
源代码22 项目: consulo-csharp   文件: CSharpLambdaParameterImpl.java
@Nonnull
@Override
public SearchScope getUseScope()
{
	return new LocalSearchScope(getParent().getParent());
}
 
@Nonnull
@Override
public SearchScope getUseScope()
{
	return new LocalSearchScope(getParent().getParent());
}
 
源代码24 项目: intellij-haxe   文件: HaxePullUpHelper.java
@Nullable
private PsiStatement hasCommonInitializer(PsiStatement commonInitializer, PsiMethod subConstructor, PsiField field, ArrayList<PsiElement> statementsToRemove) {
  final PsiCodeBlock body = subConstructor.getBody();
  if (body == null) return null;
  final PsiStatement[] statements = body.getStatements();

  // Algorithm: there should be only one write usage of field in a subConstructor,
  // and in that usage field must be a target of top-level assignment, and RHS of assignment
  // should be the same as commonInitializer if latter is non-null.
  //
  // There should be no usages before that initializer, and there should be
  // no write usages afterwards.
  PsiStatement commonInitializerCandidate = null;
  for (PsiStatement statement : statements) {
    final HashSet<PsiStatement> collectedStatements = new HashSet<PsiStatement>();
    collectPsiStatements(statement, collectedStatements);
    boolean doLookup = true;
    for (PsiStatement collectedStatement : collectedStatements) {
      if (collectedStatement instanceof PsiExpressionStatement) {
        final PsiExpression expression = ((PsiExpressionStatement)collectedStatement).getExpression();
        if (expression instanceof PsiAssignmentExpression) {
          final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression;
          final PsiExpression lExpression = assignmentExpression.getLExpression();
          if (lExpression instanceof PsiReferenceExpression) {
            final PsiReferenceExpression lRef = (PsiReferenceExpression)lExpression;
            if (lRef.getQualifierExpression() == null || lRef.getQualifierExpression() instanceof PsiThisExpression) {
              final PsiElement resolved = lRef.resolve();
              if (resolved == field) {
                doLookup = false;
                if (commonInitializerCandidate == null) {
                  final PsiExpression initializer = assignmentExpression.getRExpression();
                  if (initializer == null) return null;
                  if (commonInitializer == null) {
                    final IsMovableInitializerVisitor visitor = new IsMovableInitializerVisitor();
                    statement.accept(visitor);
                    if (visitor.isMovable()) {
                      ChangeContextUtil.encodeContextInfo(statement, true);
                      PsiStatement statementCopy = (PsiStatement)statement.copy();
                      ChangeContextUtil.clearContextInfo(statement);
                      statementsToRemove.add(statement);
                      commonInitializerCandidate = statementCopy;
                    }
                    else {
                      return null;
                    }
                  }
                  else {
                    if (PsiEquivalenceUtil.areElementsEquivalent(commonInitializer, statement)) {
                      statementsToRemove.add(statement);
                      commonInitializerCandidate = commonInitializer;
                    }
                    else {
                      return null;
                    }
                  }
                }
                else if (!PsiEquivalenceUtil.areElementsEquivalent(commonInitializerCandidate, statement)){
                  return null;
                }
              }
            }
          }
        }
      }
    }
    if (doLookup) {
      final PsiReference[] references =
        ReferencesSearch.search(field, new LocalSearchScope(statement), false).toArray(new PsiReference[0]);
      if (commonInitializerCandidate == null && references.length > 0) {
        return null;
      }

      for (PsiReference reference : references) {
        if (RefactoringUtil.isAssignmentLHS(reference.getElement())) return null;
      }
    }
  }
  return commonInitializerCandidate;
}
 
源代码25 项目: consulo   文件: AnalysisScope.java
@Nonnull
public SearchScope toSearchScope() {
  switch (myType) {
    case CUSTOM:
      return myScope;
    case DIRECTORY:
      return GlobalSearchScopesCore.directoryScope((PsiDirectory)myElement, true);
    case FILE:
      return new LocalSearchScope(myElement);
    case INVALID:
      return LocalSearchScope.EMPTY;
    case MODULE:
      GlobalSearchScope moduleScope = GlobalSearchScope.moduleScope(myModule);
      return myIncludeTestSource ? moduleScope : GlobalSearchScope.notScope(GlobalSearchScopesCore.projectTestScope(myModule.getProject())).intersectWith(moduleScope);
    case MODULES:
      SearchScope scope = GlobalSearchScope.EMPTY_SCOPE;
      for (Module module : myModules) {
        scope = scope.union(GlobalSearchScope.moduleScope(module));
      }
      return scope;
    case PROJECT:
      return myIncludeTestSource ? GlobalSearchScope.projectScope(myProject) : GlobalSearchScopesCore.projectProductionScope(myProject);
    case VIRTUAL_FILES:
      return new GlobalSearchScope() {
        @Override
        public boolean contains(@Nonnull VirtualFile file) {
          return myFilesSet.contains(file);
        }

        @Override
        public int compare(@Nonnull VirtualFile file1, @Nonnull VirtualFile file2) {
          return 0;
        }

        @Override
        public boolean isSearchInModuleContent(@Nonnull Module aModule) {
          return false;
        }

        @Override
        public boolean isSearchInLibraries() {
          return false;
        }
      };
    default:
      LOG.error("invalid type " + myType);
      return GlobalSearchScope.EMPTY_SCOPE;
  }
}
 
源代码26 项目: consulo   文件: CommonFindUsagesDialog.java
@Override
protected boolean isInFileOnly() {
  return super.isInFileOnly() ||
         PsiSearchHelper.SERVICE.getInstance(myPsiElement.getProject()).getUseScope(myPsiElement) instanceof LocalSearchScope;
}
 
源代码27 项目: consulo   文件: InplaceRefactoring.java
protected SearchScope getReferencesSearchScope(VirtualFile file) {
  return file == null || ProjectRootManager.getInstance(myProject).getFileIndex().isInContent(file)
         ? ProjectScope.getProjectScope(myElementToRename.getProject())
         : new LocalSearchScope(myElementToRename.getContainingFile());
}
 
源代码28 项目: consulo   文件: MemberInplaceRenamer.java
@Override
protected SearchScope getReferencesSearchScope(VirtualFile file) {
  PsiFile currentFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
  return currentFile != null ? new LocalSearchScope(currentFile)
                             : ProjectScope.getProjectScope(myProject);
}
 
源代码29 项目: CppTools   文件: CppReferencesSearcher.java
private boolean doFindRefsInCppCode(final PsiFile psiFile, PsiElement target, ReferencesSearch.SearchParameters params,
                                    GlobalSearchScope globalScope, final Processor<PsiReference> processor) {
  final Project project = psiFile.getProject();
  final String commandName = project.getUserData(ourKey);
  final int offset;
  VirtualFile file;

  if (target instanceof CppFile) {
    offset = FindUsagesCommand.MAGIC_FILE_OFFSET;
    file = ((CppFile)target).getVirtualFile();
  } else {
    VirtualFile actionStartFile = null;
    int actionStartOffset = -1;
    
    final PsiFile actionStartPsiFile = project.getUserData(ourFileKey);
    if (actionStartPsiFile != null) {
      actionStartFile = actionStartPsiFile.getVirtualFile();
      final Integer integer = project.getUserData(ourOffsetKey);
      if (integer != null) actionStartOffset = integer.intValue();
    }
    
    if (actionStartOffset != -1) {
      offset = actionStartOffset;
      file = actionStartFile;
    } else {
      file = psiFile.getVirtualFile();
      offset = target.getTextOffset();
    }
  }

  final FindUsagesCommand findUsagesCommand = new FindUsagesCommand(
    file.getPath(),
    offset,
    RENAME_ACTION_TEXT.equals(commandName)
  );
  findUsagesCommand.setDoInfiniteBlockingWithCancelledCheck(true);

  findUsagesCommand.post(psiFile.getProject());

  if (!findUsagesCommand.hasReadyResult()) return true;

  final int count = findUsagesCommand.getUsageCount();
  if (count == 0) return true;

  final boolean scopeIsLocal = params.getScope() instanceof LocalSearchScope;
  final Set<VirtualFile> localScope = scopeIsLocal ? new HashSet<VirtualFile>() : null;

  if (scopeIsLocal) {
    for(PsiElement e: ((LocalSearchScope)params.getScope()).getScope()) {
      localScope.add(e.getContainingFile().getVirtualFile());
    }
  }

  for(final FileUsage fu:findUsagesCommand.getUsagesList().files) {
    final VirtualFile usagefile = fu.findVirtualFile();
    if ((globalScope != null && !globalScope.contains(usagefile)) ||
        localScope != null && !localScope.contains(usagefile)
      ) {
      continue;
    }


    Runnable runnable = new Runnable() {
      public void run() {
        final PsiFile usageFile = psiFile.getManager().findFile( usagefile );

        for(final OurUsage u:fu.usageList) {
          final PsiElement psiElement = usageFile.findElementAt(u.getStart());

          if (psiElement != null) {
            final PsiElement parentElement = psiElement.getParent();
            if (parentElement instanceof CppElement || parentElement instanceof CppKeyword /*operator*/) {
              final PsiReference reference = parentElement.getReference();
              if (reference != null) processor.process( reference );
            }
          }
        }
      }
    };

    ApplicationManager.getApplication().runReadAction(runnable);
  }
  return false;
}
 
 类所在包
 同包方法