Search in sources :

Example 81 with LocalSearchScope

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

the class InlineMethodProcessor method prepareBlock.

private BlockData prepareBlock(PsiReferenceExpression ref, final PsiSubstitutor callSubstitutor, final PsiExpressionList argumentList, final InlineUtil.TailCallType tailCallType) throws IncorrectOperationException {
    final PsiCodeBlock block = myMethodCopy.getBody();
    if (callSubstitutor != PsiSubstitutor.EMPTY) {
        substituteMethodTypeParams(block, callSubstitutor);
    }
    final PsiStatement[] originalStatements = block.getStatements();
    PsiLocalVariable resultVar = null;
    PsiType returnType = callSubstitutor.substitute(myMethod.getReturnType());
    String resultName = null;
    final int applicabilityLevel = PsiUtil.getApplicabilityLevel(myMethod, callSubstitutor, argumentList);
    if (returnType != null && !PsiType.VOID.equals(returnType) && tailCallType == InlineUtil.TailCallType.None) {
        resultName = myJavaCodeStyle.propertyNameToVariableName("result", VariableKind.LOCAL_VARIABLE);
        resultName = myJavaCodeStyle.suggestUniqueVariableName(resultName, block.getFirstChild(), true);
        PsiDeclarationStatement declaration = myFactory.createVariableDeclarationStatement(resultName, returnType, null);
        declaration = (PsiDeclarationStatement) block.addAfter(declaration, null);
        resultVar = (PsiLocalVariable) declaration.getDeclaredElements()[0];
    }
    PsiParameter[] parms = myMethodCopy.getParameterList().getParameters();
    PsiLocalVariable[] parmVars = new PsiLocalVariable[parms.length];
    for (int i = parms.length - 1; i >= 0; i--) {
        PsiParameter parm = parms[i];
        String parmName = parm.getName();
        String name = parmName;
        name = myJavaCodeStyle.variableNameToPropertyName(name, VariableKind.PARAMETER);
        name = myJavaCodeStyle.propertyNameToVariableName(name, VariableKind.LOCAL_VARIABLE);
        if (!name.equals(parmName)) {
            name = myJavaCodeStyle.suggestUniqueVariableName(name, block.getFirstChild(), true);
        }
        RefactoringUtil.renameVariableReferences(parm, name, new LocalSearchScope(myMethodCopy.getBody()), true);
        PsiType paramType = parm.getType();
        @NonNls String defaultValue;
        if (paramType instanceof PsiEllipsisType) {
            final PsiEllipsisType ellipsisType = (PsiEllipsisType) paramType;
            paramType = callSubstitutor.substitute(ellipsisType.toArrayType());
            if (applicabilityLevel == MethodCandidateInfo.ApplicabilityLevel.VARARGS) {
                defaultValue = "new " + ((PsiArrayType) paramType).getComponentType().getCanonicalText() + "[]{}";
            } else {
                defaultValue = PsiTypesUtil.getDefaultValueOfType(paramType);
            }
        } else {
            defaultValue = PsiTypesUtil.getDefaultValueOfType(paramType);
        }
        PsiExpression initializer = myFactory.createExpressionFromText(defaultValue, null);
        PsiDeclarationStatement declaration = myFactory.createVariableDeclarationStatement(name, GenericsUtil.getVariableTypeByExpressionType(callSubstitutor.substitute(paramType)), initializer);
        declaration = (PsiDeclarationStatement) block.addAfter(declaration, null);
        parmVars[i] = (PsiLocalVariable) declaration.getDeclaredElements()[0];
        PsiUtil.setModifierProperty(parmVars[i], PsiModifier.FINAL, parm.hasModifierProperty(PsiModifier.FINAL));
    }
    PsiLocalVariable thisVar = null;
    PsiClass containingClass = myMethod.getContainingClass();
    if (!myMethod.hasModifierProperty(PsiModifier.STATIC) && containingClass != null) {
        PsiType thisType = GenericsUtil.getVariableTypeByExpressionType(myFactory.createType(containingClass, callSubstitutor));
        String[] names = myJavaCodeStyle.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, thisType).names;
        String thisVarName = names[0];
        thisVarName = myJavaCodeStyle.suggestUniqueVariableName(thisVarName, myMethod.getFirstChild(), true);
        PsiExpression initializer = myFactory.createExpressionFromText("null", null);
        PsiDeclarationStatement declaration = myFactory.createVariableDeclarationStatement(thisVarName, thisType, initializer);
        declaration = (PsiDeclarationStatement) block.addAfter(declaration, null);
        thisVar = (PsiLocalVariable) declaration.getDeclaredElements()[0];
    }
    String lockName = null;
    if (thisVar != null) {
        lockName = thisVar.getName();
    } else if (myMethod.hasModifierProperty(PsiModifier.STATIC) && containingClass != null) {
        lockName = containingClass.getQualifiedName() + ".class";
    }
    if (lockName != null && syncNeeded(ref)) {
        PsiSynchronizedStatement synchronizedStatement = (PsiSynchronizedStatement) myFactory.createStatementFromText("synchronized(" + lockName + "){}", block);
        synchronizedStatement = (PsiSynchronizedStatement) CodeStyleManager.getInstance(myProject).reformat(synchronizedStatement);
        synchronizedStatement = (PsiSynchronizedStatement) block.add(synchronizedStatement);
        final PsiCodeBlock synchronizedBody = synchronizedStatement.getBody();
        for (final PsiStatement originalStatement : originalStatements) {
            synchronizedBody.add(originalStatement);
            originalStatement.delete();
        }
    }
    if (resultName != null || tailCallType == InlineUtil.TailCallType.Simple) {
        PsiReturnStatement[] returnStatements = PsiUtil.findReturnStatements(myMethodCopy);
        for (PsiReturnStatement returnStatement : returnStatements) {
            final PsiExpression returnValue = returnStatement.getReturnValue();
            if (returnValue == null)
                continue;
            PsiStatement statement;
            if (tailCallType == InlineUtil.TailCallType.Simple) {
                if (returnValue instanceof PsiExpression && returnStatement.getNextSibling() == myMethodCopy.getBody().getLastBodyElement()) {
                    PsiExpressionStatement exprStatement = (PsiExpressionStatement) myFactory.createStatementFromText("a;", null);
                    exprStatement.getExpression().replace(returnValue);
                    returnStatement.getParent().addBefore(exprStatement, returnStatement);
                    statement = myFactory.createStatementFromText("return;", null);
                } else {
                    statement = (PsiStatement) returnStatement.copy();
                }
            } else {
                statement = myFactory.createStatementFromText(resultName + "=0;", null);
                statement = (PsiStatement) myCodeStyleManager.reformat(statement);
                PsiAssignmentExpression assignment = (PsiAssignmentExpression) ((PsiExpressionStatement) statement).getExpression();
                assignment.getRExpression().replace(returnValue);
            }
            returnStatement.replace(statement);
        }
    }
    return new BlockData(block, thisVar, parmVars, resultVar);
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) NonNls(org.jetbrains.annotations.NonNls)

Example 82 with LocalSearchScope

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

the class ExtractMethodObjectProcessor method findUsages.

@NotNull
protected UsageInfo[] findUsages() {
    final ArrayList<UsageInfo> result = new ArrayList<>();
    final PsiClass containingClass = getMethod().getContainingClass();
    final SearchScope scope = PsiUtilCore.getVirtualFile(containingClass) == null ? new LocalSearchScope(containingClass) : GlobalSearchScope.projectScope(myProject);
    PsiReference[] refs = ReferencesSearch.search(getMethod(), scope, false).toArray(PsiReference.EMPTY_ARRAY);
    for (PsiReference ref : refs) {
        final PsiElement element = ref.getElement();
        if (element != null && element.isValid()) {
            result.add(new UsageInfo(element));
        }
    }
    if (isCreateInnerClass()) {
        final Set<PsiMethod> usedMethods = new LinkedHashSet<>();
        getMethod().accept(new JavaRecursiveElementWalkingVisitor() {

            @Override
            public void visitMethodCallExpression(PsiMethodCallExpression expression) {
                super.visitMethodCallExpression(expression);
                final PsiMethod method = expression.resolveMethod();
                if (method != null) {
                    usedMethods.add(method);
                }
            }
        });
        for (PsiMethod usedMethod : usedMethods) {
            if (usedMethod.hasModifierProperty(PsiModifier.PRIVATE) && (!usedMethod.hasModifierProperty(PsiModifier.STATIC) || myExtractProcessor.isStatic())) {
                PsiMethod toMove = usedMethod;
                for (PsiReference reference : ReferencesSearch.search(usedMethod)) {
                    if (!PsiTreeUtil.isAncestor(getMethod(), reference.getElement(), false)) {
                        toMove = null;
                        break;
                    }
                }
                if (toMove != null) {
                    myUsages.add(new MethodToMoveUsageInfo(toMove));
                }
            }
        }
    }
    UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]);
    return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) UsageInfo(com.intellij.usageView.UsageInfo) NotNull(org.jetbrains.annotations.NotNull)

Example 83 with LocalSearchScope

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

the class FieldCanBeLocalInspectionBase method doCheckClass.

private void doCheckClass(final PsiClass aClass, ProblemsHolder holder, final List<String> excludeAnnos, boolean ignoreFieldsUsedInMultipleMethods) {
    if (aClass.isInterface())
        return;
    final PsiField[] fields = aClass.getFields();
    final Set<PsiField> candidates = new LinkedHashSet<>();
    for (PsiField field : fields) {
        if (AnnotationUtil.isAnnotated(field, excludeAnnos)) {
            continue;
        }
        if (field.hasModifierProperty(PsiModifier.PRIVATE) && !(field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL))) {
            candidates.add(field);
        }
    }
    removeFieldsReferencedFromInitializers(aClass, candidates);
    if (candidates.isEmpty())
        return;
    final Set<PsiField> usedFields = new THashSet<>();
    removeReadFields(aClass, candidates, usedFields, ignoreFieldsUsedInMultipleMethods);
    if (candidates.isEmpty())
        return;
    final ImplicitUsageProvider[] implicitUsageProviders = Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);
    for (final PsiField field : candidates) {
        if (usedFields.contains(field) && !hasImplicitReadOrWriteUsage(field, implicitUsageProviders)) {
            if (!ReferencesSearch.search(field, new LocalSearchScope(aClass)).forEach(reference -> {
                final PsiElement element = reference.getElement();
                if (element instanceof PsiReferenceExpression) {
                    final PsiElement qualifier = ((PsiReferenceExpression) element).getQualifier();
                    return qualifier == null || qualifier instanceof PsiThisExpression && ((PsiThisExpression) qualifier).getQualifier() == null;
                }
                return true;
            })) {
                continue;
            }
            final String message = InspectionsBundle.message("inspection.field.can.be.local.problem.descriptor");
            final ArrayList<LocalQuickFix> fixes = new ArrayList<>();
            SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(field, qualifiedName -> {
                final LocalQuickFix quickFix = SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix(InspectionGadgetsBundle.message("add.0.to.ignore.if.annotated.by.list.quickfix", qualifiedName), QuickFixBundle.message("fix.add.special.annotation.family"), EXCLUDE_ANNOS, qualifiedName, field);
                fixes.add(quickFix);
                return true;
            });
            final LocalQuickFix fix = createFix();
            if (fix != null) {
                fixes.add(fix);
            }
            holder.registerProblem(field.getNameIdentifier(), message, fixes.toArray(new LocalQuickFix[fixes.size()]));
        }
    }
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) SpecialAnnotationsUtilBase(com.intellij.codeInspection.util.SpecialAnnotationsUtilBase) GroupNames(com.intellij.codeInsight.daemon.GroupNames) JDOMExternalizableStringList(com.intellij.openapi.util.JDOMExternalizableStringList) java.util(java.util) PsiDocTagValue(com.intellij.psi.javadoc.PsiDocTagValue) NonNls(org.jetbrains.annotations.NonNls) THashSet(gnu.trove.THashSet) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) InspectionGadgetsBundle(com.siyeh.InspectionGadgetsBundle) Comparing(com.intellij.openapi.util.Comparing) PsiUtil(com.intellij.psi.util.PsiUtil) ImplicitUsageProvider(com.intellij.codeInsight.daemon.ImplicitUsageProvider) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) ProblemsHolder(com.intellij.codeInspection.ProblemsHolder) QuickFixBundle(com.intellij.codeInsight.daemon.QuickFixBundle) Extensions(com.intellij.openapi.extensions.Extensions) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) InspectionsBundle(com.intellij.codeInspection.InspectionsBundle) PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) BaseJavaBatchLocalInspectionTool(com.intellij.codeInspection.BaseJavaBatchLocalInspectionTool) AnnotationUtil(com.intellij.codeInsight.AnnotationUtil) com.intellij.psi(com.intellij.psi) WriteExternalException(com.intellij.openapi.util.WriteExternalException) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) Element(org.jdom.Element) com.intellij.psi.controlFlow(com.intellij.psi.controlFlow) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) THashSet(gnu.trove.THashSet) ImplicitUsageProvider(com.intellij.codeInsight.daemon.ImplicitUsageProvider)

Example 84 with LocalSearchScope

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

the class JavaTargetElementEvaluator method getSearchScope.

@Override
@Nullable
public SearchScope getSearchScope(Editor editor, @NotNull final PsiElement element) {
    final PsiReferenceExpression referenceExpression = editor != null ? findReferenceExpression(editor) : null;
    if (referenceExpression != null && element instanceof PsiMethod) {
        final PsiClass[] memberClass = getClassesWithMember(referenceExpression, (PsiMember) element);
        if (memberClass != null && memberClass.length == 1) {
            return CachedValuesManager.getCachedValue(memberClass[0], () -> {
                final List<PsiClass> classesToSearch = ContainerUtil.newArrayList(memberClass);
                classesToSearch.addAll(ClassInheritorsSearch.search(memberClass[0]).findAll());
                final Set<PsiClass> supers = new HashSet<>();
                for (PsiClass psiClass : classesToSearch) {
                    supers.addAll(InheritanceUtil.getSuperClasses(psiClass));
                }
                final List<PsiElement> elements = new ArrayList<>();
                elements.addAll(classesToSearch);
                elements.addAll(supers);
                elements.addAll(FunctionalExpressionSearch.search(memberClass[0]).findAll());
                return new CachedValueProvider.Result<SearchScope>(new LocalSearchScope(PsiUtilCore.toPsiElementArray(elements)), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
            });
        }
    }
    return super.getSearchScope(editor, element);
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Nullable(org.jetbrains.annotations.Nullable)

Example 85 with LocalSearchScope

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

the class JavaIntroduceParameterObjectDelegate method collectInternalUsages.

@Override
public <M1 extends PsiNamedElement, P1 extends ParameterInfo> ReadWriteAccessDetector.Access collectInternalUsages(Collection<FixableUsageInfo> usages, PsiMethod overridingMethod, IntroduceParameterObjectClassDescriptor<M1, P1> classDescriptor, P1 parameterInfo, String mergedParamName) {
    final LocalSearchScope localSearchScope = new LocalSearchScope(overridingMethod);
    final PsiParameter[] params = overridingMethod.getParameterList().getParameters();
    final PsiParameter parameter = params[parameterInfo.getOldIndex()];
    final ReadWriteAccessDetector detector = ReadWriteAccessDetector.findDetector(parameter);
    assert detector != null;
    final String setter = classDescriptor.getSetterName(parameterInfo, overridingMethod);
    final String getter = classDescriptor.getGetterName(parameterInfo, overridingMethod);
    final ReadWriteAccessDetector.Access[] accessor = new ReadWriteAccessDetector.Access[] { null };
    ReferencesSearch.search(parameter, localSearchScope).forEach(reference -> {
        final PsiElement refElement = reference.getElement();
        if (refElement instanceof PsiReferenceExpression) {
            final PsiReferenceExpression paramUsage = (PsiReferenceExpression) refElement;
            final ReadWriteAccessDetector.Access access = detector.getExpressionAccess(refElement);
            if (access == ReadWriteAccessDetector.Access.Read) {
                usages.add(new ReplaceParameterReferenceWithCall(paramUsage, mergedParamName, getter));
                if (accessor[0] == null) {
                    accessor[0] = ReadWriteAccessDetector.Access.Read;
                }
            } else {
                if (access == ReadWriteAccessDetector.Access.ReadWrite) {
                    usages.add(new ReplaceParameterIncrementDecrement(paramUsage, mergedParamName, setter, getter));
                } else {
                    usages.add(new ReplaceParameterAssignmentWithCall(paramUsage, mergedParamName, setter, getter));
                }
                accessor[0] = ReadWriteAccessDetector.Access.Write;
            }
        }
        return true;
    });
    return accessor[0];
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ReadWriteAccessDetector(com.intellij.codeInsight.highlighting.ReadWriteAccessDetector)

Aggregations

LocalSearchScope (com.intellij.psi.search.LocalSearchScope)113 SearchScope (com.intellij.psi.search.SearchScope)31 NotNull (org.jetbrains.annotations.NotNull)22 PsiElement (com.intellij.psi.PsiElement)19 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)19 Project (com.intellij.openapi.project.Project)18 Nullable (org.jetbrains.annotations.Nullable)13 ArrayList (java.util.ArrayList)12 VirtualFile (com.intellij.openapi.vfs.VirtualFile)11 UsageInfo (com.intellij.usageView.UsageInfo)11 TextRange (com.intellij.openapi.util.TextRange)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)9 com.intellij.psi (com.intellij.psi)8 PsiReference (com.intellij.psi.PsiReference)8 PsiFile (com.intellij.psi.PsiFile)7 ReferencesSearch (com.intellij.psi.search.searches.ReferencesSearch)7 AnalysisScope (com.intellij.analysis.AnalysisScope)6 Processor (com.intellij.util.Processor)6 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)5 Ref (com.intellij.openapi.util.Ref)4