Search in sources :

Example 36 with SearchScope

use of com.intellij.psi.search.SearchScope in project intellij-community by JetBrains.

the class AnnotatedElementsSearcher method execute.

@Override
public boolean execute(@NotNull final AnnotatedElementsSearch.Parameters p, @NotNull final Processor<PsiModifierListOwner> consumer) {
    final PsiClass annClass = p.getAnnotationClass();
    if (!annClass.isAnnotationType())
        throw new IllegalArgumentException("Annotation type should be passed to annotated members search but got: " + annClass);
    String annotationFQN = ApplicationManager.getApplication().runReadAction(new Computable<String>() {

        @Override
        public String compute() {
            return annClass.getQualifiedName();
        }
    });
    if (annotationFQN == null)
        throw new IllegalArgumentException("FQN is null for " + annClass);
    final PsiManager psiManager = ApplicationManager.getApplication().runReadAction(new Computable<PsiManager>() {

        @Override
        public PsiManager compute() {
            return annClass.getManager();
        }
    });
    final SearchScope useScope = p.getScope();
    final Class<? extends PsiModifierListOwner>[] types = p.getTypes();
    for (final PsiAnnotation ann : getAnnotationCandidates(annClass, useScope, psiManager.getProject())) {
        final PsiModifierListOwner candidate = ApplicationManager.getApplication().runReadAction(new Computable<PsiModifierListOwner>() {

            @Override
            public PsiModifierListOwner compute() {
                PsiElement parent = ann.getContext();
                if (!(parent instanceof PsiModifierList)) {
                    // Can be a PsiNameValuePair, if annotation is used to annotate annotation parameters
                    return null;
                }
                final PsiElement owner = parent.getParent();
                if (!isInstanceof(owner, types)) {
                    return null;
                }
                if (p.isApproximate()) {
                    return (PsiModifierListOwner) owner;
                }
                final PsiJavaCodeReferenceElement ref = ann.getNameReferenceElement();
                if (ref == null || !psiManager.areElementsEquivalent(ref.resolve(), annClass)) {
                    return null;
                }
                return (PsiModifierListOwner) owner;
            }
        });
        if (candidate != null && !consumer.process(candidate)) {
            return false;
        }
    }
    return true;
}
Also used : GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope)

Example 37 with SearchScope

use of com.intellij.psi.search.SearchScope in project intellij-community by JetBrains.

the class JavaCompilingVisitor method buildDescendants.

private static List<PsiClass> buildDescendants(String className, boolean includeSelf, OptimizingSearchHelper searchHelper, CompileContext context) {
    if (!searchHelper.doOptimizing())
        return Collections.emptyList();
    final SearchScope scope = context.getOptions().getScope();
    if (!(scope instanceof GlobalSearchScope))
        return Collections.emptyList();
    final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(context.getProject());
    final PsiClass[] classes = cache.getClassesByName(className, (GlobalSearchScope) scope);
    final List<PsiClass> results = new ArrayList<>();
    final Processor<PsiClass> processor = aClass -> {
        results.add(aClass);
        return true;
    };
    for (PsiClass aClass : classes) {
        ClassInheritorsSearch.search(aClass, scope, true).forEach(processor);
    }
    if (includeSelf) {
        Collections.addAll(results, classes);
    }
    return results;
}
Also used : MalformedPatternException(com.intellij.structuralsearch.MalformedPatternException) CommentMatchingStrategy(com.intellij.structuralsearch.impl.matcher.strategies.CommentMatchingStrategy) ExprMatchingStrategy(com.intellij.structuralsearch.impl.matcher.strategies.ExprMatchingStrategy) JavaDocMatchingStrategy(com.intellij.structuralsearch.impl.matcher.strategies.JavaDocMatchingStrategy) NonNls(org.jetbrains.annotations.NonNls) SearchScope(com.intellij.psi.search.SearchScope) com.intellij.structuralsearch.impl.matcher.handlers(com.intellij.structuralsearch.impl.matcher.handlers) com.intellij.structuralsearch.impl.matcher.filters(com.intellij.structuralsearch.impl.matcher.filters) ArrayList(java.util.ArrayList) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) RegExpPredicate(com.intellij.structuralsearch.impl.matcher.predicates.RegExpPredicate) Matcher(java.util.regex.Matcher) JavaCompiledPattern(com.intellij.structuralsearch.impl.matcher.JavaCompiledPattern) PsiShortNamesCache(com.intellij.psi.search.PsiShortNamesCache) DocValuesIterator(com.intellij.structuralsearch.impl.matcher.iterators.DocValuesIterator) NodeIterator(com.intellij.dupLocator.iterators.NodeIterator) MatchingStrategy(com.intellij.structuralsearch.impl.matcher.strategies.MatchingStrategy) SSRBundle(com.intellij.structuralsearch.SSRBundle) CompiledPattern(com.intellij.structuralsearch.impl.matcher.CompiledPattern) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiDocTag(com.intellij.psi.javadoc.PsiDocTag) Nullable(org.jetbrains.annotations.Nullable) PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) List(java.util.List) Processor(com.intellij.util.Processor) com.intellij.psi(com.intellij.psi) ClassInheritorsSearch(com.intellij.psi.search.searches.ClassInheritorsSearch) UnsupportedPatternException(com.intellij.structuralsearch.UnsupportedPatternException) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) PsiShortNamesCache(com.intellij.psi.search.PsiShortNamesCache) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) ArrayList(java.util.ArrayList)

Example 38 with SearchScope

use of com.intellij.psi.search.SearchScope in project kotlin by JetBrains.

the class AndroidLintGlobalInspectionContext method performPreRunActivities.

@Override
public void performPreRunActivities(@NotNull List<Tools> globalTools, @NotNull List<Tools> localTools, @NotNull final GlobalInspectionContext context) {
    final Project project = context.getProject();
    if (!ProjectFacetManager.getInstance(project).hasFacets(AndroidFacet.ID)) {
        return;
    }
    final List<Issue> issues = AndroidLintExternalAnnotator.getIssuesFromInspections(project, null);
    if (issues.size() == 0) {
        return;
    }
    final Map<Issue, Map<File, List<ProblemData>>> problemMap = new HashMap<Issue, Map<File, List<ProblemData>>>();
    final AnalysisScope scope = context.getRefManager().getScope();
    if (scope == null) {
        return;
    }
    final IntellijLintClient client = IntellijLintClient.forBatch(project, problemMap, scope, issues);
    final LintDriver lint = new LintDriver(new IntellijLintIssueRegistry(), client);
    final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    if (indicator != null) {
        ProgressWrapper.unwrap(indicator).setText("Running Android Lint");
    }
    EnumSet<Scope> lintScope;
    //noinspection ConstantConditions
    if (!IntellijLintProject.SUPPORT_CLASS_FILES) {
        lintScope = EnumSet.copyOf(Scope.ALL);
        // Can't run class file based checks
        lintScope.remove(Scope.CLASS_FILE);
        lintScope.remove(Scope.ALL_CLASS_FILES);
        lintScope.remove(Scope.JAVA_LIBRARIES);
    } else {
        lintScope = Scope.ALL;
    }
    List<VirtualFile> files = null;
    final List<Module> modules = Lists.newArrayList();
    int scopeType = scope.getScopeType();
    switch(scopeType) {
        case AnalysisScope.MODULE:
            {
                SearchScope searchScope = scope.toSearchScope();
                if (searchScope instanceof ModuleWithDependenciesScope) {
                    ModuleWithDependenciesScope s = (ModuleWithDependenciesScope) searchScope;
                    if (!s.isSearchInLibraries()) {
                        modules.add(s.getModule());
                    }
                }
                break;
            }
        case AnalysisScope.FILE:
        case AnalysisScope.VIRTUAL_FILES:
        case AnalysisScope.UNCOMMITTED_FILES:
            {
                files = Lists.newArrayList();
                SearchScope searchScope = scope.toSearchScope();
                if (searchScope instanceof LocalSearchScope) {
                    final LocalSearchScope localSearchScope = (LocalSearchScope) searchScope;
                    final PsiElement[] elements = localSearchScope.getScope();
                    final List<VirtualFile> finalFiles = files;
                    ApplicationManager.getApplication().runReadAction(new Runnable() {

                        @Override
                        public void run() {
                            for (PsiElement element : elements) {
                                if (element instanceof PsiFile) {
                                    // should be the case since scope type is FILE
                                    Module module = ModuleUtilCore.findModuleForPsiElement(element);
                                    if (module != null && !modules.contains(module)) {
                                        modules.add(module);
                                    }
                                    VirtualFile virtualFile = ((PsiFile) element).getVirtualFile();
                                    if (virtualFile != null) {
                                        finalFiles.add(virtualFile);
                                    }
                                }
                            }
                        }
                    });
                } else {
                    final List<VirtualFile> finalList = files;
                    scope.accept(new PsiElementVisitor() {

                        @Override
                        public void visitFile(PsiFile file) {
                            VirtualFile virtualFile = file.getVirtualFile();
                            if (virtualFile != null) {
                                finalList.add(virtualFile);
                            }
                        }
                    });
                }
                if (files.isEmpty()) {
                    files = null;
                } else {
                    // Lint will compute it lazily based on actual files in the request
                    lintScope = null;
                }
                break;
            }
        case AnalysisScope.PROJECT:
            {
                modules.addAll(Arrays.asList(ModuleManager.getInstance(project).getModules()));
                break;
            }
        case AnalysisScope.CUSTOM:
        case AnalysisScope.MODULES:
        case AnalysisScope.DIRECTORY:
            {
                // Handled by the getNarrowedComplementaryScope case below
                break;
            }
        case AnalysisScope.INVALID:
            break;
        default:
            Logger.getInstance(this.getClass()).warn("Unexpected inspection scope " + scope + ", " + scopeType);
    }
    if (modules.isEmpty()) {
        for (Module module : ModuleManager.getInstance(project).getModules()) {
            if (scope.containsModule(module)) {
                modules.add(module);
            }
        }
        if (modules.isEmpty() && files != null) {
            for (VirtualFile file : files) {
                Module module = ModuleUtilCore.findModuleForFile(file, project);
                if (module != null && !modules.contains(module)) {
                    modules.add(module);
                }
            }
        }
        if (modules.isEmpty()) {
            AnalysisScope narrowed = scope.getNarrowedComplementaryScope(project);
            for (Module module : ModuleManager.getInstance(project).getModules()) {
                if (narrowed.containsModule(module)) {
                    modules.add(module);
                }
            }
        }
    }
    LintRequest request = new IntellijLintRequest(client, project, files, modules, false);
    request.setScope(lintScope);
    lint.analyze(request);
    myResults = problemMap;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Issue(com.android.tools.klint.detector.api.Issue) HashMap(com.intellij.util.containers.HashMap) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) AnalysisScope(com.intellij.analysis.AnalysisScope) LintRequest(com.android.tools.klint.client.api.LintRequest) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) LintDriver(com.android.tools.klint.client.api.LintDriver) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ModuleWithDependenciesScope(com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope) Project(com.intellij.openapi.project.Project) ModuleWithDependenciesScope(com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) AnalysisScope(com.intellij.analysis.AnalysisScope) Scope(com.android.tools.klint.detector.api.Scope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) HashMap(com.intellij.util.containers.HashMap)

Example 39 with SearchScope

use of com.intellij.psi.search.SearchScope in project intellij-plugins by JetBrains.

the class DartServerFindUsagesHandler method processElementUsages.

@Override
public boolean processElementUsages(@NotNull final PsiElement elementToSearch, @NotNull final Processor<UsageInfo> processor, @NotNull final FindUsagesOptions options) {
    final SearchScope scope = options.searchScope;
    final Project project = ReadAction.compute(this::getProject);
    final DartAnalysisServerService service = DartAnalysisServerService.getInstance(project);
    final ReadActionConsumer<SearchResult> searchResultProcessor = new ReadActionConsumer<SearchResult>() {

        @Override
        public void consumeInReadAction(SearchResult result) {
            if (result.getKind().equals(SearchResultKind.DECLARATION))
                return;
            final Location location = result.getLocation();
            final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(location.getFile()));
            if (vFile == null)
                return;
            if (!scope.contains(vFile))
                return;
            final PsiFile psiFile = elementToSearch.getManager().findFile(vFile);
            if (psiFile == null)
                return;
            final int offset = service.getConvertedOffset(vFile, location.getOffset());
            final int length = service.getConvertedOffset(vFile, location.getOffset() + location.getLength()) - offset;
            final TextRange range = TextRange.create(offset, offset + length);
            final boolean potentialUsage = result.isPotential();
            final PsiElement usageElement = getUsagePsiElement(psiFile, range);
            final UsageInfo usageInfo = usageElement == null ? null : getUsageInfo(usageElement, range, potentialUsage);
            if (usageInfo != null && usageInfo.getElement() != null && (!(scope instanceof LocalSearchScope) || PsiSearchScopeUtil.isInScope((LocalSearchScope) scope, usageInfo.getElement()))) {
                processor.process(usageInfo);
            }
        }
    };
    final VirtualFile file = ReadAction.compute(() -> elementToSearch.getContainingFile().getVirtualFile());
    final int offset = elementToSearch.getTextRange().getStartOffset();
    service.search_findElementReferences(file, offset, searchResultProcessor);
    return true;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) SearchResult(org.dartlang.analysis.server.protocol.SearchResult) TextRange(com.intellij.openapi.util.TextRange) Project(com.intellij.openapi.project.Project) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) PsiFile(com.intellij.psi.PsiFile) DartAnalysisServerService(com.jetbrains.lang.dart.analyzer.DartAnalysisServerService) PsiElement(com.intellij.psi.PsiElement) UsageInfo(com.intellij.usageView.UsageInfo) Location(org.dartlang.analysis.server.protocol.Location)

Example 40 with SearchScope

use of com.intellij.psi.search.SearchScope in project intellij-plugins by JetBrains.

the class CucumberJavaMethodUsageSearcher method processQuery.

@Override
public void processQuery(@NotNull final MethodReferencesSearch.SearchParameters p, @NotNull final Processor<PsiReference> consumer) {
    SearchScope scope = p.getEffectiveSearchScope();
    if (!(scope instanceof GlobalSearchScope)) {
        return;
    }
    final PsiMethod method = p.getMethod();
    final PsiAnnotation stepAnnotation = CucumberJavaUtil.getCucumberStepAnnotation(method);
    final String regexp = stepAnnotation != null ? CucumberJavaUtil.getPatternFromStepDefinition(stepAnnotation) : null;
    if (regexp == null) {
        return;
    }
    final String word = CucumberUtil.getTheBiggestWordToSearchByIndex(regexp);
    if (StringUtil.isEmpty(word)) {
        return;
    }
    final GlobalSearchScope restrictedScope = GlobalSearchScope.getScopeRestrictedByFileTypes((GlobalSearchScope) scope, GherkinFileType.INSTANCE);
    ReferencesSearch.search(new ReferencesSearch.SearchParameters(method, restrictedScope, false, p.getOptimizer())).forEach(consumer);
}
Also used : GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiMethod(com.intellij.psi.PsiMethod) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) PsiAnnotation(com.intellij.psi.PsiAnnotation)

Aggregations

SearchScope (com.intellij.psi.search.SearchScope)90 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)39 LocalSearchScope (com.intellij.psi.search.LocalSearchScope)36 Project (com.intellij.openapi.project.Project)21 NotNull (org.jetbrains.annotations.NotNull)21 VirtualFile (com.intellij.openapi.vfs.VirtualFile)18 PsiElement (com.intellij.psi.PsiElement)16 PsiClass (com.intellij.psi.PsiClass)8 Processor (com.intellij.util.Processor)8 com.intellij.psi (com.intellij.psi)6 PsiMethod (com.intellij.psi.PsiMethod)6 HashMap (com.intellij.util.containers.HashMap)6 ClassInheritorsSearch (com.intellij.psi.search.searches.ClassInheritorsSearch)5 Nullable (org.jetbrains.annotations.Nullable)5 AnalysisScope (com.intellij.analysis.AnalysisScope)4 ProgressManager (com.intellij.openapi.progress.ProgressManager)4 TextRange (com.intellij.openapi.util.TextRange)4 PsiFile (com.intellij.psi.PsiFile)4 PsiSearchHelper (com.intellij.psi.search.PsiSearchHelper)4 QueryExecutor (com.intellij.util.QueryExecutor)4