Search in sources :

Example 6 with PsiSearchHelper

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

the class SystemBuilder method build.

public ReductionSystem build(final Set<PsiElement> victims) {
    final PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(myManager.getProject());
    ReductionSystem system = new ReductionSystem(myProject, victims, myTypes, myTypeVariableFactory, mySettings);
    for (final PsiElement element : victims) {
        if (element instanceof PsiParameter && ((PsiParameter) element).getDeclarationScope() instanceof PsiMethod) {
            if (!verifyMethod(element, victims, helper)) {
                continue;
            }
        } else if (element instanceof PsiMethod) {
            if (!verifyMethod(element, victims, helper)) {
                continue;
            }
        }
    }
    for (final PsiElement element : victims) {
        PsiType definedType;
        if (element instanceof PsiParameter && ((PsiParameter) element).getDeclarationScope() instanceof PsiMethod) {
            final PsiParameter p = myParameters.get(element);
            if (p != null) {
                setType(element, definedType = defineType(p));
            } else {
                continue;
            }
        } else if (element instanceof PsiMethod) {
            final PsiMethod m = myMethods.get(element);
            if (m != null) {
                system.addSubtypeConstraint(defineType(element), definedType = defineType(m));
            } else {
                continue;
            }
        } else {
            definedType = defineType(element);
        }
        addBoundConstraints(system, definedType, element);
    }
    for (final PsiElement element : victims) {
        if (element instanceof PsiParameter) {
            final PsiElement scope = ((PsiParameter) element).getDeclarationScope();
            if (scope instanceof PsiMethod) {
                final PsiParameter p = myParameters.get(element);
                if (p == null)
                    continue;
            } else /*else if (scope instanceof PsiForeachStatement) {
          addForEachConstraint(system, (PsiForeachStatement)scope);
        }*/
            if (element instanceof PsiMethod) {
                final PsiMethod m = myMethods.get(element);
                if (m == null)
                    continue;
            }
        } else if (element instanceof PsiMethod) {
            final PsiMethod m = myMethods.get(element);
            if (m == null)
                continue;
        }
        addUsage(system, element);
        if (!(element instanceof PsiExpression)) {
            for (PsiReference ref : ReferencesSearch.search(element, getScope(helper, element), true)) {
                final PsiElement elt = ref.getElement();
                if (elt != null) {
                    addUsage(system, elt);
                }
            }
        }
    }
    return system;
}
Also used : PsiSearchHelper(com.intellij.psi.search.PsiSearchHelper)

Example 7 with PsiSearchHelper

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

the class SystemBuilder method addUsage.

private void addUsage(final ReductionSystem system, final PsiElement element) {
    if (element instanceof PsiVariable) {
        final PsiExpression initializer = ((PsiVariable) element).getInitializer();
        if (initializer != null) {
            final PsiExpression core = PsiUtil.deparenthesizeExpression(initializer);
            if (core instanceof PsiArrayInitializerExpression) {
                final PsiExpression[] inits = ((PsiArrayInitializerExpression) core).getInitializers();
                final PsiType type = getType(element);
                for (PsiExpression init : inits) {
                    system.addSubtypeConstraint(evaluateType(init, system).createArrayType(), type);
                }
            } else if (core instanceof PsiNewExpression) {
                final PsiArrayInitializerExpression init = ((PsiNewExpression) core).getArrayInitializer();
                if (init != null) {
                    final PsiExpression[] inits = init.getInitializers();
                    final PsiType type = getType(element);
                    for (PsiExpression init1 : inits) {
                        system.addSubtypeConstraint(evaluateType(init1, system).createArrayType(), type);
                    }
                }
                system.addSubtypeConstraint(evaluateType(core, system), getType(element));
            } else {
                system.addSubtypeConstraint(evaluateType(core, system), getType(element));
            }
        }
        if (element instanceof PsiParameter) {
            PsiParameter parameter = (PsiParameter) element;
            final PsiElement declarationScope = parameter.getDeclarationScope();
            if (declarationScope instanceof PsiMethod) {
                final PsiMethod method = (PsiMethod) declarationScope;
                final PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(myManager.getProject());
                SearchScope scope = getScope(helper, method);
                for (PsiReference ref : ReferencesSearch.search(method, scope, true)) {
                    final PsiElement elt = ref.getElement();
                    if (elt != null) {
                        final PsiCallExpression call = PsiTreeUtil.getParentOfType(elt, PsiCallExpression.class);
                        if (call != null) {
                            PsiExpressionList argList = call.getArgumentList();
                            if (argList != null) {
                                PsiExpression[] args = argList.getExpressions();
                                int index = method.getParameterList().getParameterIndex(parameter);
                                if (index < args.length) {
                                    system.addSubtypeConstraint(evaluateType(args[index], system), myTypes.get(element));
                                }
                            }
                        }
                    }
                }
            } else if (declarationScope instanceof PsiForeachStatement) {
                addForEachConstraint(system, (PsiForeachStatement) declarationScope);
            }
        }
        return;
    } else if (element instanceof PsiMethod) {
        final PsiType reType = getType(element);
        element.accept(new JavaRecursiveElementWalkingVisitor() {

            @Override
            public void visitReturnStatement(final PsiReturnStatement statement) {
                super.visitReturnStatement(statement);
                final PsiExpression retExpr = statement.getReturnValue();
                if (retExpr != null) {
                    system.addSubtypeConstraint(evaluateType(retExpr, system), reType);
                }
            }

            @Override
            public void visitClass(PsiClass aClass) {
            }

            @Override
            public void visitLambdaExpression(PsiLambdaExpression expression) {
            }
        });
        return;
    }
    final PsiElement root = PsiTreeUtil.getParentOfType(element, PsiStatement.class, PsiField.class);
    if (root != null) {
        final PsiAnchor anchor = PsiAnchor.create(root);
        if (!myVisitedConstructions.contains(anchor)) {
            root.accept(new JavaRecursiveElementWalkingVisitor() {

                @Override
                public void visitAssignmentExpression(final PsiAssignmentExpression expression) {
                    super.visitAssignmentExpression(expression);
                    system.addSubtypeConstraint(evaluateType(expression.getRExpression(), system), evaluateType(expression.getLExpression(), system));
                }

                @Override
                public void visitConditionalExpression(final PsiConditionalExpression expression) {
                    super.visitConditionalExpression(expression);
                    system.addSubtypeConstraint(evaluateType(expression.getThenExpression(), system), evaluateType(expression.getElseExpression(), system));
                    system.addSubtypeConstraint(evaluateType(expression.getElseExpression(), system), evaluateType(expression.getThenExpression(), system));
                }

                @Override
                public void visitCallExpression(final PsiCallExpression expression) {
                    super.visitCallExpression(expression);
                    evaluateType(expression, system);
                }

                @Override
                public void visitReturnStatement(final PsiReturnStatement statement) {
                    super.visitReturnStatement(statement);
                    final PsiMethod method = PsiTreeUtil.getParentOfType(statement, PsiMethod.class, true, PsiLambdaExpression.class);
                    if (method != null) {
                        system.addSubtypeConstraint(evaluateType(statement.getReturnValue(), system), getType(method));
                    }
                }

                @Override
                public void visitTypeCastExpression(final PsiTypeCastExpression expression) {
                    super.visitTypeCastExpression(expression);
                    final PsiType operandType = evaluateType(expression.getOperand(), system);
                    final PsiType castType = evaluateType(expression, system);
                    if (operandType == null || castType == null)
                        return;
                    if (Util.bindsTypeVariables(operandType)) {
                        system.addCast(expression, operandType);
                    }
                    if (operandType.getDeepComponentType() instanceof PsiTypeVariable || castType.getDeepComponentType() instanceof PsiTypeVariable) {
                        system.addSubtypeConstraint(operandType, castType);
                    } else {
                        final PsiClassType.ClassResolveResult operandResult = Util.resolveType(operandType);
                        final PsiClassType.ClassResolveResult castResult = Util.resolveType(castType);
                        final PsiClass operandClass = operandResult.getElement();
                        final PsiClass castClass = castResult.getElement();
                        if (operandClass != null && castClass != null) {
                            if (InheritanceUtil.isInheritorOrSelf(operandClass, castClass, true)) {
                                system.addSubtypeConstraint(operandType, castType);
                            }
                        }
                    }
                }

                @Override
                public void visitVariable(final PsiVariable variable) {
                    super.visitVariable(variable);
                    final PsiExpression init = variable.getInitializer();
                    if (init != null) {
                        system.addSubtypeConstraint(evaluateType(init, system), getType(variable));
                    }
                }

                @Override
                public void visitNewExpression(final PsiNewExpression expression) {
                    super.visitNewExpression(expression);
                    final PsiArrayInitializerExpression init = expression.getArrayInitializer();
                    if (init != null) {
                        final PsiExpression[] inits = init.getInitializers();
                        final PsiType type = getType(expression);
                        for (PsiExpression init1 : inits) {
                            system.addSubtypeConstraint(evaluateType(init1, system).createArrayType(), type);
                        }
                    }
                }

                @Override
                public void visitReferenceExpression(final PsiReferenceExpression expression) {
                    final PsiExpression qualifierExpression = expression.getQualifierExpression();
                    if (qualifierExpression != null) {
                        qualifierExpression.accept(this);
                    }
                }
            });
            myVisitedConstructions.add(anchor);
        }
    }
}
Also used : PsiSearchHelper(com.intellij.psi.search.PsiSearchHelper) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope)

Example 8 with PsiSearchHelper

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

the class TestLocationDataRule method collectRelativeLocations.

@NotNull
protected static List<Location> collectRelativeLocations(Project project, VirtualFile file) {
    if (DumbService.isDumb(project))
        return Collections.emptyList();
    final List<Location> locations = new ArrayList<>();
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    if (fileIndex.isInContent(file) && !fileIndex.isInSource(file) && !fileIndex.isInLibraryClasses(file)) {
        final VirtualFile parent = file.getParent();
        final VirtualFile contentRoot = fileIndex.getContentRootForFile(file);
        if (contentRoot != null && parent != null) {
            final String relativePath = VfsUtilCore.getRelativePath(parent, contentRoot, '/');
            if (relativePath != null) {
                final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(project);
                final List<String> words = StringUtil.getWordsIn(relativePath);
                // put longer strings first
                Collections.sort(words, (o1, o2) -> o2.length() - o1.length());
                final GlobalSearchScope testScope = GlobalSearchScopesCore.projectTestScope(project);
                Set<PsiFile> resultFiles = null;
                for (String word : words) {
                    if (word.length() < 5) {
                        continue;
                    }
                    final Set<PsiFile> files = new THashSet<>();
                    searchHelper.processAllFilesWithWordInLiterals(word, testScope, new CommonProcessors.CollectProcessor<>(files));
                    if (resultFiles == null) {
                        resultFiles = files;
                    } else {
                        resultFiles.retainAll(files);
                    }
                    if (resultFiles.isEmpty())
                        break;
                }
                if (resultFiles != null) {
                    for (Iterator<PsiFile> iterator = resultFiles.iterator(); iterator.hasNext(); ) {
                        if (!VfsUtilCore.isAncestor(contentRoot, iterator.next().getVirtualFile(), true)) {
                            iterator.remove();
                        }
                    }
                    final String fileName = file.getName();
                    final String nameWithoutExtension = file.getNameWithoutExtension();
                    for (PsiFile resultFile : resultFiles) {
                        if (resultFile instanceof PsiClassOwner) {
                            final PsiClass[] classes = ((PsiClassOwner) resultFile).getClasses();
                            if (classes.length > 0) {
                                ContainerUtil.addIfNotNull(locations, getLocation(project, fileName, nameWithoutExtension, classes[0]));
                            }
                        }
                    }
                }
            }
        }
    }
    return locations;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) THashSet(gnu.trove.THashSet) PsiSearchHelper(com.intellij.psi.search.PsiSearchHelper) ProjectFileIndex(com.intellij.openapi.roots.ProjectFileIndex) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) CommonProcessors(com.intellij.util.CommonProcessors) PsiMemberParameterizedLocation(com.intellij.execution.junit2.PsiMemberParameterizedLocation) PsiLocation(com.intellij.execution.PsiLocation) MethodLocation(com.intellij.execution.junit2.info.MethodLocation) Location(com.intellij.execution.Location) NotNull(org.jetbrains.annotations.NotNull)

Example 9 with PsiSearchHelper

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

the class UnusedSymbolUtil method processUsages.

// return false if can't process usages (weird member of too may usages) or processor returned false
public static boolean processUsages(@NotNull Project project, @NotNull PsiFile containingFile, @NotNull PsiMember member, @NotNull ProgressIndicator progress, @Nullable PsiFile ignoreFile, @NotNull Processor<UsageInfo> usageInfoProcessor) {
    String name = member.getName();
    if (name == null) {
        log("* " + member.getName() + " no name; false");
        return false;
    }
    SearchScope useScope = member.getUseScope();
    PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(project);
    if (useScope instanceof GlobalSearchScope) {
        // some classes may have references from within XML outside dependent modules, e.g. our actions
        if (member instanceof PsiClass) {
            useScope = GlobalSearchScope.projectScope(project).uniteWith((GlobalSearchScope) useScope);
        }
        // if we've resolved all references, find usages will be fast
        PsiSearchHelper.SearchCostResult cheapEnough = RefResolveService.ENABLED && RefResolveService.getInstance(project).isUpToDate() ? PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES : searchHelper.isCheapEnoughToSearch(name, (GlobalSearchScope) useScope, ignoreFile, progress);
        if (cheapEnough == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) {
            log("* " + member.getName() + " too many usages; false");
            return false;
        }
        //if count is 0 there is no usages since we've called myRefCountHolder.isReferenced() before
        if (cheapEnough == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES && !canBeReferencedViaWeirdNames(member, containingFile)) {
            log("* " + member.getName() + " 0 usages; true");
            return true;
        }
        if (member instanceof PsiMethod) {
            String propertyName = PropertyUtil.getPropertyName(member);
            if (propertyName != null) {
                SearchScope fileScope = containingFile.getUseScope();
                if (fileScope instanceof GlobalSearchScope && searchHelper.isCheapEnoughToSearch(propertyName, (GlobalSearchScope) fileScope, ignoreFile, progress) == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) {
                    log("* " + member.getName() + " too many prop usages; false");
                    return false;
                }
            }
        }
    }
    FindUsagesOptions options;
    if (member instanceof PsiPackage) {
        options = new JavaPackageFindUsagesOptions(useScope);
        options.isSearchForTextOccurrences = true;
    } else if (member instanceof PsiClass) {
        options = new JavaClassFindUsagesOptions(useScope);
        options.isSearchForTextOccurrences = true;
    } else if (member instanceof PsiMethod) {
        PsiMethod method = (PsiMethod) member;
        options = new JavaMethodFindUsagesOptions(useScope);
        options.isSearchForTextOccurrences = method.isConstructor();
    } else if (member instanceof PsiVariable) {
        options = new JavaVariableFindUsagesOptions(useScope);
        options.isSearchForTextOccurrences = false;
    } else {
        options = new FindUsagesOptions(useScope);
        options.isSearchForTextOccurrences = true;
    }
    options.isUsages = true;
    return JavaFindUsagesHelper.processElementUsages(member, options, usageInfoProcessor);
}
Also used : PsiSearchHelper(com.intellij.psi.search.PsiSearchHelper) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope)

Example 10 with PsiSearchHelper

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

the class DeprecatedIsStillUsedInspection method checkMember.

private static void checkMember(@NotNull PsiMember member, @NotNull PsiIdentifier identifier, @NotNull ProblemsHolder holder) {
    if (!(member instanceof PsiDocCommentOwner) || !isDeprecated((PsiDocCommentOwner) member)) {
        return;
    }
    PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(member.getProject());
    String name = member.getName();
    if (name != null && hasUsages(member, name, searchHelper, member.getResolveScope())) {
        holder.registerProblem(identifier, "Deprecated member '" + name + "' is still used");
    }
}
Also used : PsiSearchHelper(com.intellij.psi.search.PsiSearchHelper)

Aggregations

PsiSearchHelper (com.intellij.psi.search.PsiSearchHelper)16 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)11 SearchScope (com.intellij.psi.search.SearchScope)5 ProgressManager (com.intellij.openapi.progress.ProgressManager)4 NotNull (org.jetbrains.annotations.NotNull)4 Project (com.intellij.openapi.project.Project)3 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 THashSet (gnu.trove.THashSet)3 AnalysisScope (com.intellij.analysis.AnalysisScope)2 com.intellij.codeInspection (com.intellij.codeInspection)2 GlobalInspectionContextBase (com.intellij.codeInspection.ex.GlobalInspectionContextBase)2 Logger (com.intellij.openapi.diagnostic.Logger)2 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)2 ToolExtensionPoints (com.intellij.ToolExtensionPoints)1 GroupNames (com.intellij.codeInsight.daemon.GroupNames)1 HighlightInfoType (com.intellij.codeInsight.daemon.impl.HighlightInfoType)1 HighlightUtilBase (com.intellij.codeInsight.daemon.impl.analysis.HighlightUtilBase)1 EntryPointsManager (com.intellij.codeInspection.ex.EntryPointsManager)1 JobDescriptor (com.intellij.codeInspection.ex.JobDescriptor)1 com.intellij.codeInspection.reference (com.intellij.codeInspection.reference)1