Search in sources :

Example 31 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project android by JetBrains.

the class AndroidInspectionsTest method doClassInstantiatedTest.

private void doClassInstantiatedTest(String d) throws IOException {
    createManifest();
    doGlobalInspectionTest(myUnusedDeclarationToolWrapper, d, new AnalysisScope(myModule));
}
Also used : AnalysisScope(com.intellij.analysis.AnalysisScope)

Example 32 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project android 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();
    // Running a single inspection that's not lint? If so don't run lint
    if (localTools.isEmpty() && globalTools.size() == 1) {
        Tools tool = globalTools.get(0);
        if (!tool.getShortName().startsWith(LINT_INSPECTION_PREFIX)) {
            return;
        }
    }
    if (!ProjectFacetManager.getInstance(project).hasFacets(AndroidFacet.ID)) {
        return;
    }
    List<Issue> issues = AndroidLintExternalAnnotator.getIssuesFromInspections(project, null);
    if (issues.size() == 0) {
        return;
    }
    // If running a single check by name, turn it on if it's off by default.
    if (localTools.isEmpty() && globalTools.size() == 1) {
        Tools tool = globalTools.get(0);
        String id = tool.getShortName().substring(LINT_INSPECTION_PREFIX.length());
        Issue issue = new LintIdeIssueRegistry().getIssue(id);
        if (issue != null && !issue.isEnabledByDefault()) {
            issues = Collections.singletonList(issue);
            issue.setEnabledByDefault(true);
            // And turn it back off again in cleanup
            myEnabledIssue = issue;
        }
    }
    final Map<Issue, Map<File, List<ProblemData>>> problemMap = new HashMap<>();
    AnalysisScope scope = context.getRefManager().getScope();
    if (scope == null) {
        scope = AndroidLintLintBaselineInspection.ourRerunScope;
        if (scope == null) {
            return;
        }
    }
    final LintIdeClient client = LintIdeClient.forBatch(project, problemMap, scope, issues);
    final LintDriver lint = new LintDriver(new LintIdeIssueRegistry(), client);
    final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    if (indicator != null) {
        ProgressWrapper.unwrap(indicator).setText("Running Android Lint");
    }
    EnumSet<Scope> lintScope;
    //noinspection ConstantConditions
    if (!LintIdeProject.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 = ReadAction.compute(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(() -> {
                        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) {
                                    if (virtualFile instanceof StringsVirtualFile) {
                                        StringsVirtualFile f = (StringsVirtualFile) virtualFile;
                                        if (!modules.contains(f.getFacet().getModule())) {
                                            modules.add(f.getFacet().getModule());
                                        }
                                    } else {
                                        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 LintIdeRequest(client, project, files, modules, false);
    request.setScope(lintScope);
    // Baseline analysis?
    myBaseline = null;
    for (Module module : modules) {
        AndroidModuleModel model = AndroidModuleModel.get(module);
        if (model != null) {
            GradleVersion version = model.getModelVersion();
            if (version != null && version.isAtLeast(2, 3, 0, "beta", 2, true)) {
                LintOptions options = model.getAndroidProject().getLintOptions();
                try {
                    File baselineFile = options.getBaselineFile();
                    if (baselineFile != null && !AndroidLintLintBaselineInspection.ourSkipBaselineNextRun) {
                        if (!baselineFile.isAbsolute()) {
                            String path = module.getProject().getBasePath();
                            if (path != null) {
                                baselineFile = new File(FileUtil.toSystemDependentName(path), baselineFile.getPath());
                            }
                        }
                        myBaseline = new LintBaseline(client, baselineFile);
                        lint.setBaseline(myBaseline);
                        if (!baselineFile.isFile()) {
                            myBaseline.setWriteOnClose(true);
                        } else if (AndroidLintLintBaselineInspection.ourUpdateBaselineNextRun) {
                            myBaseline.setRemoveFixed(true);
                            myBaseline.setWriteOnClose(true);
                        }
                    }
                } catch (Throwable unsupported) {
                // During 2.3 development some builds may have this method, others may not
                }
            }
            break;
        }
    }
    lint.analyze(request);
    AndroidLintLintBaselineInspection.clearNextRunState();
    myResults = problemMap;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) StringsVirtualFile(com.android.tools.idea.editors.strings.StringsVirtualFile) Issue(com.android.tools.lint.detector.api.Issue) HashMap(com.intellij.util.containers.HashMap) LintOptions(com.android.builder.model.LintOptions) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) AnalysisScope(com.intellij.analysis.AnalysisScope) LintRequest(com.android.tools.lint.client.api.LintRequest) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PsiFile(com.intellij.psi.PsiFile) GradleVersion(com.android.ide.common.repository.GradleVersion) PsiElement(com.intellij.psi.PsiElement) LintDriver(com.android.tools.lint.client.api.LintDriver) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ModuleWithDependenciesScope(com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope) Tools(com.intellij.codeInspection.ex.Tools) LintBaseline(com.android.tools.lint.client.api.LintBaseline) com.android.tools.idea.lint(com.android.tools.idea.lint) 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) Scope(com.android.tools.lint.detector.api.Scope) AnalysisScope(com.intellij.analysis.AnalysisScope) StringsVirtualFile(com.android.tools.idea.editors.strings.StringsVirtualFile) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) Module(com.intellij.openapi.module.Module) HashMap(com.intellij.util.containers.HashMap) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) StringsVirtualFile(com.android.tools.idea.editors.strings.StringsVirtualFile)

Example 33 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project android by JetBrains.

the class ResourceTypeInspection method processValuesFlownTo.

@NotNull
private static InspectionResult processValuesFlownTo(@NotNull final PsiExpression argument, @NotNull PsiElement scope, @NotNull PsiManager manager, @NotNull final Function<PsiExpression, InspectionResult> processor) {
    SliceAnalysisParams params = new SliceAnalysisParams();
    params.dataFlowToThis = true;
    params.scope = new AnalysisScope(new LocalSearchScope(scope), manager.getProject());
    SliceLanguageSupportProvider languageSlicing = LanguageSlicing.getProvider(argument);
    assert languageSlicing != null;
    SliceRootNode rootNode = new SliceRootNode(manager.getProject(), new DuplicateMap(), languageSlicing.createRootUsage(argument, params));
    @SuppressWarnings("unchecked") Collection<? extends AbstractTreeNode> children = rootNode.getChildren().iterator().next().getChildren();
    for (AbstractTreeNode child : children) {
        SliceUsage usage = (SliceUsage) child.getValue();
        if (usage == null) {
            continue;
        }
        PsiElement element = usage.getElement();
        if (element instanceof PsiExpression) {
            // If we report an error, use the current expression being evaluated. This will mark the error in the argument as opposed to using
            // the original field or variable declaration.
            InspectionResult result = processor.fun((PsiExpression) element).useErrorNode(argument);
            if (result.isInvalid()) {
                return result;
            }
        }
    }
    return !children.isEmpty() ? InspectionResult.valid() : InspectionResult.uncertain();
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) AbstractTreeNode(com.intellij.ide.util.treeView.AbstractTreeNode) AnalysisScope(com.intellij.analysis.AnalysisScope) NotNull(org.jetbrains.annotations.NotNull)

Example 34 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project android by JetBrains.

the class InferSupportAnnotationsTest method doTest.

private void doTest(boolean annotateLocalVariables, String summary, VirtualFile... files) throws Exception {
    if (!InferSupportAnnotationsAction.ENABLED) {
        System.out.println("Ignoring " + this.getClass().getSimpleName() + ": Functionality disabled");
        return;
    }
    String annotationsJar = getTestDataPath() + "/infer/data.jar";
    VirtualFile aLib = LocalFileSystem.getInstance().findFileByPath(annotationsJar);
    if (aLib != null) {
        final VirtualFile file = JarFileSystem.getInstance().getJarRootForLocalFile(aLib);
        if (file != null) {
            ModuleRootModificationUtil.addModuleLibrary(myModule, file.getUrl());
        }
    }
    InferSupportAnnotations inference = new InferSupportAnnotations(annotateLocalVariables, getProject());
    AnalysisScope scope;
    if (files.length > 0) {
        configureByFiles(null, files);
        scope = new AnalysisScope(getProject(), Arrays.asList(files));
        for (int i = 0; i < InferSupportAnnotationsAction.MAX_PASSES; i++) {
            for (VirtualFile virtualFile : files) {
                PsiFile psiFile = getPsiManager().findFile(virtualFile);
                assertNotNull(psiFile);
                inference.collect(psiFile);
            }
        }
    } else {
        configureByFile(INFER_PATH + "before" + getTestName(false) + ".java");
        inference.collect(getFile());
        scope = new AnalysisScope(getFile());
    }
    if (summary != null) {
        List<UsageInfo> infos = Lists.newArrayList();
        inference.collect(infos, scope);
        String s = InferSupportAnnotations.generateReport(infos.toArray(UsageInfo.EMPTY_ARRAY));
        s = StringUtil.trimStart(s, "INFER SUPPORT ANNOTATIONS REPORT\n" + "================================\n" + "\n");
        assertEquals(summary, s.trim());
    }
    if (files.length == 0) {
        inference.apply(getProject());
        checkResultByFile(INFER_PATH + "after" + getTestName(false) + ".java");
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) AnalysisScope(com.intellij.analysis.AnalysisScope) PsiFile(com.intellij.psi.PsiFile) UsageInfo(com.intellij.usageView.UsageInfo)

Example 35 with AnalysisScope

use of com.intellij.analysis.AnalysisScope in project android by JetBrains.

the class AndroidLintTest method testImlFileOutsideContentRoot.

public void testImlFileOutsideContentRoot() throws Exception {
    myFixture.copyFileToProject(SdkConstants.FN_ANDROID_MANIFEST_XML, "additionalModules/module1/" + SdkConstants.FN_ANDROID_MANIFEST_XML);
    myFixture.copyFileToProject(SdkConstants.FN_ANDROID_MANIFEST_XML, "additionalModules/module2/" + SdkConstants.FN_ANDROID_MANIFEST_XML);
    final String testDir = BASE_PATH_GLOBAL + "apiCheck1";
    myFixture.copyFileToProject(testDir + "/MyActivity.java", "additionalModules/module1/src/p1/p2/MyActivity.java");
    doGlobalInspectionTest(new AndroidLintNewApiInspection(), testDir, new AnalysisScope(getProject()));
}
Also used : AnalysisScope(com.intellij.analysis.AnalysisScope)

Aggregations

AnalysisScope (com.intellij.analysis.AnalysisScope)56 Module (com.intellij.openapi.module.Module)14 VirtualFile (com.intellij.openapi.vfs.VirtualFile)13 JavaAnalysisScope (com.intellij.analysis.JavaAnalysisScope)12 Project (com.intellij.openapi.project.Project)12 NotNull (org.jetbrains.annotations.NotNull)10 PsiPackage (com.intellij.psi.PsiPackage)8 File (java.io.File)8 CyclicDependenciesBuilder (com.intellij.cyclicDependencies.CyclicDependenciesBuilder)7 PsiElement (com.intellij.psi.PsiElement)6 LocalSearchScope (com.intellij.psi.search.LocalSearchScope)6 Nullable (org.jetbrains.annotations.Nullable)6 AnalysisUIOptions (com.intellij.analysis.AnalysisUIOptions)5 BaseAnalysisActionDialog (com.intellij.analysis.BaseAnalysisActionDialog)5 PsiFile (com.intellij.psi.PsiFile)4 SearchScope (com.intellij.psi.search.SearchScope)4 HashMap (com.intellij.util.containers.HashMap)4 LintDriver (com.android.tools.lint.client.api.LintDriver)3 LintRequest (com.android.tools.lint.client.api.LintRequest)3 Issue (com.android.tools.lint.detector.api.Issue)3