Search in sources :

Example 36 with GrImportStatement

use of org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement in project intellij-community by JetBrains.

the class GroovyPostHighlightingPass method doCollectInformation.

@Override
public void doCollectInformation(@NotNull final ProgressIndicator progress) {
    ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
    VirtualFile virtualFile = myFile.getViewProvider().getVirtualFile();
    if (!fileIndex.isInContent(virtualFile)) {
        return;
    }
    final InspectionProfile profile = InspectionProjectProfileManager.getInstance(myProject).getCurrentProfile();
    final HighlightDisplayKey unusedDefKey = HighlightDisplayKey.find(GroovyUnusedDeclarationInspection.SHORT_NAME);
    final boolean deadCodeEnabled = profile.isToolEnabled(unusedDefKey, myFile);
    final UnusedDeclarationInspectionBase deadCodeInspection = (UnusedDeclarationInspectionBase) profile.getUnwrappedTool(UnusedDeclarationInspectionBase.SHORT_NAME, myFile);
    final GlobalUsageHelper usageHelper = new GlobalUsageHelper() {

        @Override
        public boolean isCurrentFileAlreadyChecked() {
            return false;
        }

        @Override
        public boolean isLocallyUsed(@NotNull PsiNamedElement member) {
            return false;
        }

        @Override
        public boolean shouldCheckUsages(@NotNull PsiMember member) {
            return deadCodeInspection == null || !deadCodeInspection.isEntryPoint(member);
        }
    };
    final List<HighlightInfo> unusedDeclarations = new ArrayList<>();
    final Map<GrParameter, Boolean> usedParams = new HashMap<>();
    myFile.accept(new PsiRecursiveElementWalkingVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            if (element instanceof GrReferenceExpression && !((GrReferenceElement) element).isQualified()) {
                GroovyResolveResult[] results = ((GrReferenceExpression) element).multiResolve(false);
                if (results.length == 0) {
                    results = ((GrReferenceExpression) element).multiResolve(true);
                }
                for (GroovyResolveResult result : results) {
                    PsiElement resolved = result.getElement();
                    if (resolved instanceof GrParameter && resolved.getContainingFile() == myFile) {
                        usedParams.put((GrParameter) resolved, Boolean.TRUE);
                    }
                }
            }
            if (deadCodeEnabled && element instanceof GrNamedElement && element instanceof PsiModifierListOwner && !UnusedSymbolUtil.isImplicitUsage(element.getProject(), (PsiModifierListOwner) element, progress) && !GroovySuppressableInspectionTool.isElementToolSuppressedIn(element, GroovyUnusedDeclarationInspection.SHORT_NAME)) {
                PsiElement nameId = ((GrNamedElement) element).getNameIdentifierGroovy();
                if (nameId.getNode().getElementType() == GroovyTokenTypes.mIDENT) {
                    String name = ((GrNamedElement) element).getName();
                    if (element instanceof GrTypeDefinition && !UnusedSymbolUtil.isClassUsed(myProject, element.getContainingFile(), (GrTypeDefinition) element, progress, usageHelper)) {
                        HighlightInfo highlightInfo = UnusedSymbolUtil.createUnusedSymbolInfo(nameId, "Class " + name + " is unused", HighlightInfoType.UNUSED_SYMBOL);
                        QuickFixAction.registerQuickFixAction(highlightInfo, QuickFixFactory.getInstance().createSafeDeleteFix(element), unusedDefKey);
                        ContainerUtil.addIfNotNull(unusedDeclarations, highlightInfo);
                    } else if (element instanceof GrMethod) {
                        GrMethod method = (GrMethod) element;
                        if (!UnusedSymbolUtil.isMethodReferenced(method.getProject(), method.getContainingFile(), method, progress, usageHelper)) {
                            String message = (method.isConstructor() ? "Constructor" : "Method") + " " + name + " is unused";
                            HighlightInfo highlightInfo = UnusedSymbolUtil.createUnusedSymbolInfo(nameId, message, HighlightInfoType.UNUSED_SYMBOL);
                            QuickFixAction.registerQuickFixAction(highlightInfo, QuickFixFactory.getInstance().createSafeDeleteFix(method), unusedDefKey);
                            ContainerUtil.addIfNotNull(unusedDeclarations, highlightInfo);
                        }
                    } else if (element instanceof GrField && isFieldUnused((GrField) element, progress, usageHelper)) {
                        HighlightInfo highlightInfo = UnusedSymbolUtil.createUnusedSymbolInfo(nameId, "Property " + name + " is unused", HighlightInfoType.UNUSED_SYMBOL);
                        QuickFixAction.registerQuickFixAction(highlightInfo, QuickFixFactory.getInstance().createSafeDeleteFix(element), unusedDefKey);
                        ContainerUtil.addIfNotNull(unusedDeclarations, highlightInfo);
                    } else if (element instanceof GrParameter) {
                        if (!usedParams.containsKey(element)) {
                            usedParams.put((GrParameter) element, Boolean.FALSE);
                        }
                    }
                }
            }
            super.visitElement(element);
        }
    });
    final Set<GrImportStatement> unusedImports = new HashSet<>(PsiUtil.getValidImportStatements(myFile));
    unusedImports.removeAll(GroovyImportUtil.findUsedImports(myFile));
    myUnusedImports = unusedImports;
    if (deadCodeEnabled) {
        for (GrParameter parameter : usedParams.keySet()) {
            if (usedParams.get(parameter))
                continue;
            PsiElement scope = parameter.getDeclarationScope();
            if (scope instanceof GrMethod) {
                GrMethod method = (GrMethod) scope;
                if (methodMayHaveUnusedParameters(method)) {
                    PsiElement identifier = parameter.getNameIdentifierGroovy();
                    HighlightInfo highlightInfo = UnusedSymbolUtil.createUnusedSymbolInfo(identifier, "Parameter " + parameter.getName() + " is unused", HighlightInfoType.UNUSED_SYMBOL);
                    QuickFixAction.registerQuickFixAction(highlightInfo, GroovyQuickFixFactory.getInstance().createRemoveUnusedGrParameterFix(parameter), unusedDefKey);
                    ContainerUtil.addIfNotNull(unusedDeclarations, highlightInfo);
                }
            } else if (scope instanceof GrClosableBlock) {
            //todo Max Medvedev
            }
        }
    }
    myUnusedDeclarations = unusedDeclarations;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) NotNull(org.jetbrains.annotations.NotNull) GrNamedElement(org.jetbrains.plugins.groovy.lang.psi.GrNamedElement) InspectionProfile(com.intellij.codeInspection.InspectionProfile) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) UnusedDeclarationInspectionBase(com.intellij.codeInspection.deadCode.UnusedDeclarationInspectionBase) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) ProjectFileIndex(com.intellij.openapi.roots.ProjectFileIndex)

Example 37 with GrImportStatement

use of org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement in project intellij-community by JetBrains.

the class GroovyPostHighlightingPass method doApplyInformationToEditor.

@Override
public void doApplyInformationToEditor() {
    if (myUnusedDeclarations == null || myUnusedImports == null) {
        return;
    }
    AnnotationHolder annotationHolder = new AnnotationHolderImpl(new AnnotationSession(myFile));
    List<HighlightInfo> infos = new ArrayList<>(myUnusedDeclarations);
    for (GrImportStatement unusedImport : myUnusedImports) {
        Annotation annotation = annotationHolder.createWarningAnnotation(calculateRangeToUse(unusedImport), GroovyInspectionBundle.message("unused.import"));
        annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
        annotation.registerFix(GroovyQuickFixFactory.getInstance().createOptimizeImportsFix(false));
        infos.add(HighlightInfo.fromAnnotation(annotation));
    }
    UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, myFile.getTextLength(), infos, getColorsScheme(), getId());
    if (myUnusedImports != null && !myUnusedImports.isEmpty()) {
        IntentionAction fix = GroovyQuickFixFactory.getInstance().createOptimizeImportsFix(true);
        if (fix.isAvailable(myProject, myEditor, myFile) && myFile.isWritable()) {
            fix.invoke(myProject, myEditor, myFile);
        }
    }
}
Also used : AnnotationSession(com.intellij.lang.annotation.AnnotationSession) AnnotationHolder(com.intellij.lang.annotation.AnnotationHolder) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) Annotation(com.intellij.lang.annotation.Annotation)

Example 38 with GrImportStatement

use of org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement in project intellij-community by JetBrains.

the class GrImportStatementImpl method getAliasNameElement.

@Nullable
@Override
public PsiElement getAliasNameElement() {
    GrImportStatementStub stub = getStub();
    if (stub != null) {
        String alias = stub.getAliasName();
        if (alias == null)
            return null;
        GrImportStatement imp = GroovyPsiElementFactory.getInstance(getProject()).createImportStatementFromText("import A as " + alias);
        return imp.getAliasNameElement();
    }
    return findChildByType(GroovyTokenTypes.mIDENT);
}
Also used : GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrImportStatementStub(org.jetbrains.plugins.groovy.lang.psi.stubs.GrImportStatementStub) Nullable(org.jetbrains.annotations.Nullable)

Example 39 with GrImportStatement

use of org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement in project intellij-community by JetBrains.

the class GroovyShellLanguageConsoleView method processCode.

protected void processCode() {
    GroovyShellCodeFragment groovyFile = getGroovyFile();
    for (GrTopStatement statement : groovyFile.getTopStatements()) {
        if (statement instanceof GrImportStatement) {
            groovyFile.addImportsFromString(importToString((GrImportStatement) statement));
        } else if (statement instanceof GrMethod) {
            groovyFile.addVariable(((GrMethod) statement).getName(), generateClosure((GrMethod) statement));
        } else if (statement instanceof GrAssignmentExpression) {
            GrAssignmentExpression assignment = (GrAssignmentExpression) statement;
            GrExpression left = assignment.getLValue();
            if (left instanceof GrReferenceExpression && !((GrReferenceExpression) left).isQualified()) {
                groovyFile.addVariable(((GrReferenceExpression) left).getReferenceName(), assignment.getRValue());
            }
        } else if (statement instanceof GrTypeDefinition) {
            groovyFile.addTypeDefinition(prepareTypeDefinition((GrTypeDefinition) statement));
        }
    }
    PsiType scriptType = groovyFile.getInferredScriptReturnType();
    if (scriptType != null) {
        groovyFile.addVariable("_", scriptType);
    }
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrAssignmentExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrTopStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) PsiType(com.intellij.psi.PsiType)

Example 40 with GrImportStatement

use of org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement in project intellij-community by JetBrains.

the class GroovyMoveClassToInnerHandler method removeRedundantImports.

@Override
public void removeRedundantImports(PsiFile targetClassFile) {
    if (targetClassFile instanceof GroovyFile) {
        GroovyFile file = (GroovyFile) targetClassFile;
        final Set<GrImportStatement> usedImports = GroovyImportUtil.findUsedImports(file);
        final List<GrImportStatement> validImports = org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.getValidImportStatements(file);
        for (GrImportStatement importStatement : validImports) {
            if (!usedImports.contains(importStatement)) {
                file.removeImport(importStatement);
            }
        }
    }
}
Also used : GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Aggregations

GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)49 GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)15 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)11 NotNull (org.jetbrains.annotations.NotNull)9 GrReferenceElement (org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)9 PsiElement (com.intellij.psi.PsiElement)7 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)6 GrPackageDefinition (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition)6 TextRange (com.intellij.openapi.util.TextRange)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)4 UsageInfo (com.intellij.usageView.UsageInfo)4 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)4 GrTopStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement)4 GrCodeReferenceElement (org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement)4 ASTNode (com.intellij.lang.ASTNode)3 Document (com.intellij.openapi.editor.Document)3 PsiFile (com.intellij.psi.PsiFile)3 GroovyScriptClass (org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass)3 DaemonCodeAnalyzerImpl (com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl)2 IntentionAction (com.intellij.codeInsight.intention.IntentionAction)2