Search in sources :

Example 11 with GroovyRecursiveElementVisitor

use of org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor in project intellij-community by JetBrains.

the class GrRefactoringConflictsUtil method analyzeModuleConflicts.

public static void analyzeModuleConflicts(final Project project, final Collection<? extends GroovyPsiElement> scopes, final UsageInfo[] usages, final VirtualFile vFile, final MultiMap<PsiElement, String> conflicts) {
    if (scopes == null)
        return;
    for (final PsiElement scope : scopes) {
        if (scope instanceof PsiPackage)
            return;
    }
    final Module targetModule = ModuleUtilCore.findModuleForFile(vFile, project);
    if (targetModule == null)
        return;
    final GlobalSearchScope resolveScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(targetModule);
    final HashSet<PsiElement> reported = new HashSet<>();
    for (final GroovyPsiElement scope : scopes) {
        scope.accept(new GroovyRecursiveElementVisitor() {

            @Override
            public void visitCodeReferenceElement(@NotNull GrCodeReferenceElement refElement) {
                super.visitCodeReferenceElement(refElement);
                visit(refElement);
            }

            @Override
            public void visitReferenceExpression(@NotNull GrReferenceExpression reference) {
                super.visitReferenceExpression(reference);
                visit(reference);
            }

            private void visit(GrReferenceElement<? extends GroovyPsiElement> reference) {
                final PsiElement resolved = reference.resolve();
                if (resolved != null && !reported.contains(resolved) && !CommonRefactoringUtil.isAncestor(resolved, scopes) && !PsiSearchScopeUtil.isInScope(resolveScope, resolved) && !(resolved instanceof LightElement)) {
                    final String scopeDescription = RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(reference), true);
                    final String message = RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.in.module.2", RefactoringUIUtil.getDescription(resolved, true), scopeDescription, CommonRefactoringUtil.htmlEmphasize(targetModule.getName()));
                    conflicts.putValue(resolved, CommonRefactoringUtil.capitalize(message));
                    reported.add(resolved);
                }
            }
        });
    }
    boolean isInTestSources = ModuleRootManager.getInstance(targetModule).getFileIndex().isInTestSourceContent(vFile);
    NextUsage: for (UsageInfo usage : usages) {
        final PsiElement element = usage.getElement();
        if (element != null && PsiTreeUtil.getParentOfType(element, GrImportStatement.class, false) == null) {
            for (PsiElement scope : scopes) {
                if (PsiTreeUtil.isAncestor(scope, element, false))
                    continue NextUsage;
            }
            final GlobalSearchScope resolveScope1 = element.getResolveScope();
            if (!resolveScope1.isSearchInModuleContent(targetModule, isInTestSources)) {
                final PsiFile usageFile = element.getContainingFile();
                PsiElement container;
                if (usageFile instanceof PsiJavaFile) {
                    container = ConflictsUtil.getContainer(element);
                } else {
                    container = usageFile;
                }
                final String scopeDescription = RefactoringUIUtil.getDescription(container, true);
                final VirtualFile usageVFile = usageFile.getVirtualFile();
                if (usageVFile != null) {
                    Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(usageVFile);
                    if (module != null) {
                        final String message;
                        final PsiElement referencedElement;
                        if (usage instanceof MoveRenameUsageInfo) {
                            referencedElement = ((MoveRenameUsageInfo) usage).getReferencedElement();
                        } else {
                            referencedElement = usage.getElement();
                        }
                        assert referencedElement != null : usage;
                        if (module == targetModule && isInTestSources) {
                            message = RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.from.production.of.module.2", RefactoringUIUtil.getDescription(referencedElement, true), scopeDescription, CommonRefactoringUtil.htmlEmphasize(module.getName()));
                        } else {
                            message = RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.from.module.2", RefactoringUIUtil.getDescription(referencedElement, true), scopeDescription, CommonRefactoringUtil.htmlEmphasize(module.getName()));
                        }
                        conflicts.putValue(referencedElement, CommonRefactoringUtil.capitalize(message));
                    }
                }
            }
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) LightElement(com.intellij.psi.impl.light.LightElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Module(com.intellij.openapi.module.Module) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) UsageInfo(com.intellij.usageView.UsageInfo) HashSet(com.intellij.util.containers.HashSet)

Example 12 with GroovyRecursiveElementVisitor

use of org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor in project intellij-community by JetBrains.

the class CreateParameterForFieldIntention method findCandidates.

private static List<GrField> findCandidates(PsiMethod constructor, final GrTypeDefinition clazz) {
    final List<GrField> usedFields = new ArrayList<>();
    final GrOpenBlock block = constructor instanceof GrMethod ? ((GrMethod) constructor).getBlock() : null;
    if (block == null) {
        return usedFields;
    }
    final PsiManager manager = clazz.getManager();
    block.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
            super.visitReferenceExpression(referenceExpression);
            final PsiElement resolved = referenceExpression.resolve();
            if (resolved instanceof GrField && manager.areElementsEquivalent(((GrField) resolved).getContainingClass(), clazz) && PsiUtil.isAccessedForWriting(referenceExpression)) {
                usedFields.add((GrField) resolved);
            }
        }

        @Override
        public void visitTypeDefinition(@NotNull GrTypeDefinition typeDefinition) {
        }

        @Override
        public void visitClosure(@NotNull GrClosableBlock closure) {
        }
    });
    List<GrField> fields = new ArrayList<>();
    for (final GrField field : clazz.getFields()) {
        if (field.getInitializerGroovy() != null)
            continue;
        if (ContainerUtil.find(usedFields, new Condition<PsiField>() {

            @Override
            public boolean value(PsiField o) {
                return manager.areElementsEquivalent(o, field);
            }
        }) == null) {
            fields.add(field);
        }
    }
    return fields;
}
Also used : Condition(com.intellij.openapi.util.Condition) GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) ArrayList(java.util.ArrayList) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)

Example 13 with GroovyRecursiveElementVisitor

use of org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor in project intellij-community by JetBrains.

the class EachToForIntention method updateReturnStatements.

private static GrForStatement updateReturnStatements(GrForStatement forStatement) {
    GrStatement body = forStatement.getBody();
    assert body != null;
    final Set<String> usedLabels = ContainerUtil.newHashSet();
    final Ref<Boolean> needLabel = Ref.create(false);
    body.accept(new GroovyRecursiveElementVisitor() {

        private int myLoops = 0;

        @Override
        public void visitReturnStatement(@NotNull GrReturnStatement returnStatement) {
            if (returnStatement.getReturnValue() != null)
                return;
            if (myLoops > 0)
                needLabel.set(true);
        }

        @Override
        public void visitLabeledStatement(@NotNull GrLabeledStatement labeledStatement) {
            super.visitLabeledStatement(labeledStatement);
            usedLabels.add(labeledStatement.getName());
        }

        @Override
        public void visitForStatement(@NotNull GrForStatement forStatement) {
            myLoops++;
            super.visitForStatement(forStatement);
            myLoops--;
        }

        @Override
        public void visitWhileStatement(@NotNull GrWhileStatement whileStatement) {
            myLoops++;
            super.visitWhileStatement(whileStatement);
            myLoops--;
        }

        @Override
        public void visitClosure(@NotNull GrClosableBlock closure) {
        //don't go into closures
        }

        @Override
        public void visitAnonymousClassDefinition(@NotNull GrAnonymousClassDefinition anonymousClassDefinition) {
        //don't go into anonymous
        }
    });
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(forStatement.getProject());
    final String continueText;
    if (needLabel.get()) {
        int i = 0;
        String label = OUTER;
        while (usedLabels.contains(label)) {
            label = OUTER + i;
            i++;
        }
        continueText = "continue " + label;
        GrLabeledStatement labeled = (GrLabeledStatement) factory.createStatementFromText(label + ": while (true){}");
        labeled.getStatement().replaceWithStatement(forStatement);
        labeled = forStatement.replaceWithStatement(labeled);
        forStatement = (GrForStatement) labeled.getStatement();
        body = forStatement.getBody();
        assert body != null;
    } else {
        continueText = "continue";
    }
    final GrStatement continueStatement = factory.createStatementFromText(continueText);
    body.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReturnStatement(@NotNull GrReturnStatement returnStatement) {
            if (returnStatement.getReturnValue() == null) {
                returnStatement.replaceWithStatement(continueStatement);
            }
        }

        @Override
        public void visitClosure(@NotNull GrClosableBlock closure) {
        //don't go into closures
        }

        @Override
        public void visitAnonymousClassDefinition(@NotNull GrAnonymousClassDefinition anonymousClassDefinition) {
        //don't go into anonymous
        }
    });
    return forStatement;
}
Also used : GrAnonymousClassDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrReturnStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)

Example 14 with GroovyRecursiveElementVisitor

use of org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor in project intellij-community by JetBrains.

the class MoveGroovyMemberHandler method getAnchor.

@Override
@Nullable
public PsiElement getAnchor(@NotNull final PsiMember member, @NotNull final PsiClass targetClass, Set<PsiMember> membersToMove) {
    if (member instanceof GrField && member.hasModifierProperty(PsiModifier.STATIC)) {
        final List<PsiField> referencedFields = new ArrayList<>();
        final GrExpression psiExpression = ((GrField) member).getInitializerGroovy();
        if (psiExpression != null) {
            psiExpression.accept(new GroovyRecursiveElementVisitor() {

                @Override
                public void visitReferenceExpression(@NotNull final GrReferenceExpression expression) {
                    super.visitReferenceExpression(expression);
                    final PsiElement psiElement = expression.resolve();
                    if (psiElement instanceof GrField) {
                        final GrField grField = (GrField) psiElement;
                        if (grField.getContainingClass() == targetClass && !referencedFields.contains(grField)) {
                            referencedFields.add(grField);
                        }
                    }
                }
            });
        }
        if (!referencedFields.isEmpty()) {
            Collections.sort(referencedFields, (o1, o2) -> -PsiUtilCore.compareElementsByPosition(o1, o2));
            return referencedFields.get(0);
        }
    }
    return null;
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) ArrayList(java.util.ArrayList) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) Nullable(org.jetbrains.annotations.Nullable)

Example 15 with GroovyRecursiveElementVisitor

use of org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor in project intellij-community by JetBrains.

the class UnusedDefInspection method check.

@Override
protected void check(@NotNull final GrControlFlowOwner owner, @NotNull final ProblemsHolder problemsHolder) {
    final Instruction[] flow = owner.getControlFlow();
    final ReachingDefinitionsDfaInstance dfaInstance = new ReachingDefinitionsDfaInstance(flow);
    final ReachingDefinitionsSemilattice lattice = new ReachingDefinitionsSemilattice();
    final DFAEngine<DefinitionMap> engine = new DFAEngine<>(flow, dfaInstance, lattice);
    final List<DefinitionMap> dfaResult = engine.performDFAWithTimeout();
    if (dfaResult == null) {
        return;
    }
    final TIntHashSet unusedDefs = new TIntHashSet();
    for (Instruction instruction : flow) {
        if (instruction instanceof ReadWriteVariableInstruction && ((ReadWriteVariableInstruction) instruction).isWrite()) {
            unusedDefs.add(instruction.num());
        }
    }
    for (int i = 0; i < dfaResult.size(); i++) {
        final Instruction instruction = flow[i];
        if (instruction instanceof ReadWriteVariableInstruction) {
            final ReadWriteVariableInstruction varInst = (ReadWriteVariableInstruction) instruction;
            if (!varInst.isWrite()) {
                final String varName = varInst.getVariableName();
                DefinitionMap e = dfaResult.get(i);
                e.forEachValue(new TObjectProcedure<TIntHashSet>() {

                    @Override
                    public boolean execute(TIntHashSet reaching) {
                        reaching.forEach(new TIntProcedure() {

                            @Override
                            public boolean execute(int defNum) {
                                final String defName = ((ReadWriteVariableInstruction) flow[defNum]).getVariableName();
                                if (varName.equals(defName)) {
                                    unusedDefs.remove(defNum);
                                }
                                return true;
                            }
                        });
                        return true;
                    }
                });
            }
        }
    }
    final Set<PsiElement> checked = ContainerUtil.newHashSet();
    unusedDefs.forEach(new TIntProcedure() {

        @Override
        public boolean execute(int num) {
            final ReadWriteVariableInstruction instruction = (ReadWriteVariableInstruction) flow[num];
            final PsiElement element = instruction.getElement();
            process(element, checked, problemsHolder, GroovyInspectionBundle.message("unused.assignment.tooltip"));
            return true;
        }
    });
    owner.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitVariable(@NotNull GrVariable variable) {
            if (checked.contains(variable) || variable.getInitializerGroovy() != null)
                return;
            if (ReferencesSearch.search(variable, variable.getUseScope()).findFirst() == null) {
                process(variable, checked, problemsHolder, GroovyInspectionBundle.message("unused.variable"));
            }
        }
    });
}
Also used : ReadWriteVariableInstruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction) TIntProcedure(gnu.trove.TIntProcedure) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) Instruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction) ReadWriteVariableInstruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction) ReachingDefinitionsDfaInstance(org.jetbrains.plugins.groovy.lang.psi.dataFlow.reachingDefs.ReachingDefinitionsDfaInstance) TIntHashSet(gnu.trove.TIntHashSet) DFAEngine(org.jetbrains.plugins.groovy.lang.psi.dataFlow.DFAEngine) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) ReachingDefinitionsSemilattice(org.jetbrains.plugins.groovy.lang.psi.dataFlow.reachingDefs.ReachingDefinitionsSemilattice) DefinitionMap(org.jetbrains.plugins.groovy.lang.psi.dataFlow.reachingDefs.DefinitionMap) PsiElement(com.intellij.psi.PsiElement) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Aggregations

GroovyRecursiveElementVisitor (org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor)25 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)14 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)10 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)10 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)8 PsiElement (com.intellij.psi.PsiElement)7 NotNull (org.jetbrains.annotations.NotNull)7 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)6 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)6 GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)5 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)4 GrOpenBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)4 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)4 GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)3 GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)3 TextRange (com.intellij.openapi.util.TextRange)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)2 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)2 UsageInfo (com.intellij.usageView.UsageInfo)2 ArrayList (java.util.ArrayList)2