Search in sources :

Example 1 with GrNamedElement

use of org.jetbrains.plugins.groovy.lang.psi.GrNamedElement 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 2 with GrNamedElement

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

the class GrPackageInspection method getElementToHighlight.

@Nullable
private static PsiElement getElementToHighlight(GroovyFile file) {
    GrPackageDefinition packageDefinition = file.getPackageDefinition();
    if (packageDefinition != null)
        return packageDefinition;
    PsiClass[] classes = file.getClasses();
    for (PsiClass aClass : classes) {
        if (!(aClass instanceof SyntheticElement) && aClass instanceof GrTypeDefinition) {
            return ((GrTypeDefinition) aClass).getNameIdentifierGroovy();
        }
    }
    GrTopStatement[] statements = file.getTopStatements();
    if (statements.length > 0) {
        GrTopStatement first = statements[0];
        if (first instanceof GrNamedElement)
            return ((GrNamedElement) first).getNameIdentifierGroovy();
        return first;
    }
    return null;
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrNamedElement(org.jetbrains.plugins.groovy.lang.psi.GrNamedElement) PsiClass(com.intellij.psi.PsiClass) GrPackageDefinition(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition) SyntheticElement(com.intellij.psi.SyntheticElement) GrTopStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with GrNamedElement

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

the class ConvertParameterToMapEntryIntention method processIntention.

@Override
protected void processIntention(@NotNull final PsiElement element, @NotNull final Project project, Editor editor) throws IncorrectOperationException {
    // Method or closure to be refactored
    final GrParametersOwner owner = PsiTreeUtil.getParentOfType(element, GrParametersOwner.class);
    final Collection<PsiElement> occurrences = new ArrayList<>();
    // Find all referenced expressions
    final boolean success = collectOwnerOccurrences(project, owner, occurrences);
    if (!success)
        return;
    // Checking for Groovy files only
    final boolean isClosure = owner instanceof GrClosableBlock;
    if (!checkOwnerOccurrences(project, occurrences, isClosure))
        return;
    // To add or not to add new parameter for map entries
    final GrParameter firstParam = getFirstParameter(owner);
    switch(analyzeForNamedArguments(owner, occurrences)) {
        case ERROR:
            {
                final GrNamedElement namedElement = getReferencedElement(owner);
                LOG.assertTrue(namedElement != null);
                final String msg = GroovyIntentionsBundle.message("wrong.first.parameter.type", isClosure ? CLOSURE_CAPTION_CAP : METHOD_CAPTION_CAP, namedElement.getName(), firstParam.getName());
                showErrorMessage(msg, project);
                return;
            }
        case MUST_BE_MAP:
            {
                if (firstParam == getAppropriateParameter(element)) {
                    final String msg = GroovyIntentionsBundle.message("convert.cannot.itself");
                    showErrorMessage(msg, project);
                    return;
                }
                performRefactoring(element, owner, occurrences, false, null, false);
                break;
            }
        case IS_NOT_MAP:
            {
                if (!ApplicationManager.getApplication().isUnitTestMode()) {
                    final String[] possibleNames = generateValidNames(MY_POSSIBLE_NAMES, firstParam);
                    final GroovyMapParameterDialog dialog = new GroovyMapParameterDialog(project, possibleNames, true) {

                        @Override
                        protected void doOKAction() {
                            String name = getEnteredName();
                            MultiMap<PsiElement, String> conflicts = new MultiMap<>();
                            assert name != null;
                            GroovyValidationUtil.validateNewParameterName(firstParam, conflicts, name);
                            if (isClosure) {
                                findClosureConflictUsages(conflicts, occurrences);
                            }
                            if (reportConflicts(conflicts, project)) {
                                performRefactoring(element, owner, occurrences, createNewFirst(), name, specifyTypeExplicitly());
                            }
                            super.doOKAction();
                        }
                    };
                    dialog.show();
                } else {
                    //todo add statictics manager
                    performRefactoring(element, owner, occurrences, true, (new GroovyValidationUtil.ParameterNameSuggester("attrs", firstParam)).generateName(), true);
                }
                break;
            }
    }
}
Also used : GrParametersOwner(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner) ArrayList(java.util.ArrayList) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) MultiMap(com.intellij.util.containers.MultiMap) GrNamedElement(org.jetbrains.plugins.groovy.lang.psi.GrNamedElement)

Example 4 with GrNamedElement

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

the class GroovyLineMarkerProvider method collectOverridingMethods.

private static void collectOverridingMethods(@NotNull final Set<PsiMethod> methods, @NotNull Collection<LineMarkerInfo> result) {
    final Set<PsiElement> overridden = new HashSet<>();
    Set<PsiClass> classes = new THashSet<>();
    for (PsiMethod method : methods) {
        ProgressManager.checkCanceled();
        final PsiClass parentClass = method.getContainingClass();
        if (parentClass != null && !CommonClassNames.JAVA_LANG_OBJECT.equals(parentClass.getQualifiedName())) {
            classes.add(parentClass);
        }
    }
    for (final PsiClass aClass : classes) {
        AllOverridingMethodsSearch.search(aClass).forEach(pair -> {
            ProgressManager.checkCanceled();
            final PsiMethod superMethod = pair.getFirst();
            if (isCorrectTarget(superMethod) && isCorrectTarget(pair.getSecond())) {
                if (methods.remove(superMethod)) {
                    overridden.add(PsiImplUtil.handleMirror(superMethod));
                }
            }
            return !methods.isEmpty();
        });
    }
    for (PsiElement element : overridden) {
        final Icon icon = AllIcons.Gutter.OverridenMethod;
        element = PsiImplUtil.handleMirror(element);
        PsiElement range = element instanceof GrNamedElement ? ((GrNamedElement) element).getNameIdentifierGroovy() : element;
        final MarkerType type = element instanceof GrField ? GroovyMarkerTypes.OVERRIDEN_PROPERTY_TYPE : GroovyMarkerTypes.GR_OVERRIDEN_METHOD;
        LineMarkerInfo info = new LineMarkerInfo<>(range, range.getTextRange(), icon, Pass.LINE_MARKERS, type.getTooltip(), type.getNavigationHandler(), GutterIconRenderer.Alignment.RIGHT);
        result.add(info);
    }
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) LineMarkerInfo(com.intellij.codeInsight.daemon.LineMarkerInfo) GrNamedElement(org.jetbrains.plugins.groovy.lang.psi.GrNamedElement) MethodSignatureBackedByPsiMethod(com.intellij.psi.util.MethodSignatureBackedByPsiMethod) MarkerType(com.intellij.codeInsight.daemon.impl.MarkerType) THashSet(gnu.trove.THashSet) HashSet(com.intellij.util.containers.HashSet) THashSet(gnu.trove.THashSet)

Aggregations

GrNamedElement (org.jetbrains.plugins.groovy.lang.psi.GrNamedElement)4 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)2 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)2 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)2 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)2 HighlightDisplayKey (com.intellij.codeInsight.daemon.HighlightDisplayKey)1 LineMarkerInfo (com.intellij.codeInsight.daemon.LineMarkerInfo)1 MarkerType (com.intellij.codeInsight.daemon.impl.MarkerType)1 InspectionProfile (com.intellij.codeInspection.InspectionProfile)1 UnusedDeclarationInspectionBase (com.intellij.codeInspection.deadCode.UnusedDeclarationInspectionBase)1 ProjectFileIndex (com.intellij.openapi.roots.ProjectFileIndex)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 PsiClass (com.intellij.psi.PsiClass)1 SyntheticElement (com.intellij.psi.SyntheticElement)1 MethodSignatureBackedByPsiMethod (com.intellij.psi.util.MethodSignatureBackedByPsiMethod)1 HashSet (com.intellij.util.containers.HashSet)1 MultiMap (com.intellij.util.containers.MultiMap)1 THashSet (gnu.trove.THashSet)1 ArrayList (java.util.ArrayList)1 NotNull (org.jetbrains.annotations.NotNull)1