下面列出了怎么用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;
}
@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();
}
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);
}
@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();
}
@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;
}
/**
* 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));
}
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;
}
@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);
}
@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();
}
@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();
}
@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();
}
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;
}
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);
}
@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);
}
@Nullable
@Override
public SearchScope getAdditionalUseScope(@Nonnull PsiElement element) {
SearchScope useScope = element.getUseScope();
if (useScope instanceof LocalSearchScope) return null;
return ScratchesSearchScope.getScratchesScope(element.getProject());
}
@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;
}
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();
}
});
}
@NotNull
@Override
public SearchScope getUseScope() {
PsiElement scopeElement = Scope.getFirstScopeParent(this);
return scopeElement == null ? super.getUseScope() : new LocalSearchScope(scopeElement);
}
@Nonnull
@Override
public SearchScope getUseScope()
{
return new LocalSearchScope(getParent().getParent());
}
@Nonnull
@Override
public SearchScope getUseScope()
{
return new LocalSearchScope(getParent().getParent());
}
@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;
}
@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;
}
}
@Override
protected boolean isInFileOnly() {
return super.isInFileOnly() ||
PsiSearchHelper.SERVICE.getInstance(myPsiElement.getProject()).getUseScope(myPsiElement) instanceof LocalSearchScope;
}
protected SearchScope getReferencesSearchScope(VirtualFile file) {
return file == null || ProjectRootManager.getInstance(myProject).getFileIndex().isInContent(file)
? ProjectScope.getProjectScope(myElementToRename.getProject())
: new LocalSearchScope(myElementToRename.getContainingFile());
}
@Override
protected SearchScope getReferencesSearchScope(VirtualFile file) {
PsiFile currentFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
return currentFile != null ? new LocalSearchScope(currentFile)
: ProjectScope.getProjectScope(myProject);
}
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;
}