Search in sources :

Example 6 with BaseInspectionVisitor

use of org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor in project intellij-community by JetBrains.

the class GroovyUntypedAccessInspection method buildVisitor.

@Override
@NotNull
protected BaseInspectionVisitor buildVisitor() {
    return new BaseInspectionVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression refExpr) {
            super.visitReferenceExpression(refExpr);
            if (PsiUtil.isThisOrSuperRef(refExpr))
                return;
            GroovyResolveResult resolveResult = refExpr.advancedResolve();
            PsiElement resolved = resolveResult.getElement();
            if (resolved != null) {
                if (GrHighlightUtil.isDeclarationAssignment(refExpr) || resolved instanceof PsiPackage)
                    return;
            } else {
                GrExpression qualifier = refExpr.getQualifierExpression();
                if (qualifier == null && GrHighlightUtil.isDeclarationAssignment(refExpr))
                    return;
            }
            final PsiType refExprType = refExpr.getType();
            if (refExprType == null) {
                if (resolved != null) {
                    registerError(refExpr);
                }
            } else if (refExprType instanceof PsiClassType && ((PsiClassType) refExprType).resolve() == null) {
                registerError(refExpr);
            }
        }
    };
}
Also used : PsiClassType(com.intellij.psi.PsiClassType) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) BaseInspectionVisitor(org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor) PsiPackage(com.intellij.psi.PsiPackage) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) NotNull(org.jetbrains.annotations.NotNull) PsiElement(com.intellij.psi.PsiElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) PsiType(com.intellij.psi.PsiType) NotNull(org.jetbrains.annotations.NotNull)

Example 7 with BaseInspectionVisitor

use of org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor in project intellij-community by JetBrains.

the class GrFinalVariableAccessInspection method buildVisitor.

@NotNull
@Override
protected BaseInspectionVisitor buildVisitor() {
    return new BaseInspectionVisitor() {

        @Override
        public void visitMethod(@NotNull GrMethod method) {
            super.visitMethod(method);
            final GrOpenBlock block = method.getBlock();
            if (block != null) {
                processLocalVars(block);
            }
            if (method.isConstructor()) {
                processFieldsInConstructors(method);
            }
        }

        @Override
        public void visitFile(@NotNull GroovyFileBase file) {
            super.visitFile(file);
            if (file instanceof GroovyFile && file.isScript()) {
                processLocalVars(file);
            }
        }

        @Override
        public void visitField(@NotNull GrField field) {
            super.visitField(field);
            final GrExpression initializer = field.getInitializerGroovy();
            if (initializer != null) {
                processLocalVars(initializer);
            }
            if (field.hasModifierProperty(PsiModifier.FINAL)) {
                if (!isFieldInitialized(field)) {
                    registerError(field.getNameIdentifierGroovy(), GroovyBundle.message("variable.0.might.not.have.been.initialized", field.getName()), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
                }
            }
        }

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression ref) {
            super.visitReferenceExpression(ref);
            final PsiElement resolved = ref.resolve();
            if (resolved instanceof GrField && ((GrField) resolved).hasModifierProperty(PsiModifier.FINAL)) {
                final GrField field = (GrField) resolved;
                final PsiClass containingClass = field.getContainingClass();
                if (PsiUtil.isLValue(ref)) {
                    if (containingClass == null || !PsiTreeUtil.isAncestor(containingClass, ref, true)) {
                        registerError(ref, GroovyBundle.message("cannot.assign.a.value.to.final.field.0", field.getName()), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
                    }
                } else if (PsiUtil.isUsedInIncOrDec(ref)) {
                    if (containingClass == null || !isInsideConstructorOrInitializer(containingClass, ref, field.hasModifierProperty(PsiModifier.STATIC))) {
                        registerError(ref, GroovyBundle.message("cannot.assign.a.value.to.final.field.0", field.getName()), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
                    }
                }
            } else if (resolved instanceof GrParameter && ((GrParameter) resolved).getDeclarationScope() instanceof GrMethod && ((GrParameter) resolved).hasModifierProperty(PsiModifier.FINAL) && PsiUtil.isUsedInIncOrDec(ref)) {
                registerError(ref, GroovyBundle.message("cannot.assign.a.value.to.final.parameter.0", ((GrParameter) resolved).getName()), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
            }
        }

        @Override
        public void visitClassInitializer(@NotNull GrClassInitializer initializer) {
            super.visitClassInitializer(initializer);
            processLocalVars(initializer.getBlock());
            processFieldsInClassInitializer(initializer);
        }

        private void processFieldsInConstructors(@NotNull GrMethod constructor) {
            final GrOpenBlock block = constructor.getBlock();
            if (block == null)
                return;
            final GrTypeDefinition clazz = (GrTypeDefinition) constructor.getContainingClass();
            if (clazz == null)
                return;
            final GrClassInitializer[] initializers = clazz.getInitializers();
            final List<GrField> fields = getFinalFields(clazz);
            Set<GrVariable> initializedFields = ContainerUtil.newHashSet();
            appendFieldInitializedInDeclaration(false, fields, initializedFields);
            appendFieldsInitializedInClassInitializer(initializers, null, false, fields, initializedFields);
            appendInitializationFromChainedConstructors(constructor, fields, initializedFields);
            final Instruction[] flow = buildFlowForField(block);
            final Map<String, GrVariable> variables = buildVarMap(fields, false);
            highlightInvalidWriteAccess(flow, variables, initializedFields);
        }

        private void processFieldsInClassInitializer(@NotNull GrClassInitializer initializer) {
            final GrTypeDefinition clazz = (GrTypeDefinition) initializer.getContainingClass();
            if (clazz == null)
                return;
            final boolean isStatic = initializer.isStatic();
            final GrClassInitializer[] initializers = clazz.getInitializers();
            final List<GrField> fields = getFinalFields(clazz);
            Set<GrVariable> initializedFields = ContainerUtil.newHashSet();
            appendFieldInitializedInDeclaration(isStatic, fields, initializedFields);
            appendFieldsInitializedInClassInitializer(initializers, initializer, isStatic, fields, initializedFields);
            final Instruction[] flow = buildFlowForField(initializer.getBlock());
            final Map<String, GrVariable> variables = buildVarMap(fields, isStatic);
            highlightInvalidWriteAccess(flow, variables, initializedFields);
        }

        private void processLocalVars(@NotNull GroovyPsiElement scope) {
            final MultiMap<PsiElement, GrVariable> scopes = collectVariables(scope);
            for (final Map.Entry<PsiElement, Collection<GrVariable>> entry : scopes.entrySet()) {
                final PsiElement scopeToProcess = entry.getKey();
                final Set<GrVariable> forInParameters = ContainerUtil.newHashSet();
                final Map<String, GrVariable> variables = ContainerUtil.newHashMap();
                for (final GrVariable var : entry.getValue()) {
                    variables.put(var.getName(), var);
                    if (var instanceof GrParameter && ((GrParameter) var).getDeclarationScope() instanceof GrForStatement) {
                        forInParameters.add(var);
                    }
                }
                final Instruction[] flow = getFlow(scopeToProcess);
                highlightInvalidWriteAccess(flow, variables, forInParameters);
            }
        }

        private void highlightInvalidWriteAccess(@NotNull Instruction[] flow, @NotNull Map<String, GrVariable> variables, @NotNull Set<GrVariable> initializedVariables) {
            final List<ReadWriteVariableInstruction> result = InvalidWriteAccessSearcher.findInvalidWriteAccess(flow, variables, initializedVariables);
            if (result == null)
                return;
            for (final ReadWriteVariableInstruction instruction : result) {
                if (variables.containsKey(instruction.getVariableName())) {
                    registerError(instruction.getElement(), GroovyBundle.message("cannot.assign.a.value.to.final.field.0", instruction.getVariableName()), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
                }
            }
        }
    };
}
Also used : BaseInspectionVisitor(org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) Instruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction) ReadWriteVariableInstruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction) NotNull(org.jetbrains.annotations.NotNull) ReadWriteVariableInstruction(org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) 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) MultiMap(com.intellij.util.containers.MultiMap) NotNull(org.jetbrains.annotations.NotNull)

Example 8 with BaseInspectionVisitor

use of org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor in project intellij-community by JetBrains.

the class GrMethodMayBeStaticInspection method buildVisitor.

@NotNull
@Override
protected BaseInspectionVisitor buildVisitor() {
    return new BaseInspectionVisitor() {

        @Override
        public void visitMethod(@NotNull GrMethod method) {
            if (checkMethod(method)) {
                final GrModifierFix modifierFix = new GrModifierFix(method, PsiModifier.STATIC, false, true, descriptor -> {
                    final PsiElement element = descriptor.getPsiElement();
                    final PsiElement parent = element.getParent();
                    assert parent instanceof GrMethod : "element: " + element + ", parent:" + parent;
                    return ((GrMethod) parent).getModifierList();
                });
                registerError(method.getNameIdentifierGroovy(), message("method.may.be.static"), new LocalQuickFix[] { modifierFix }, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
            }
        }
    };
}
Also used : BaseInspectionVisitor(org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor) GrModifierFix(org.jetbrains.plugins.groovy.codeInspection.bugs.GrModifierFix) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) NotNull(org.jetbrains.annotations.NotNull) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 9 with BaseInspectionVisitor

use of org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor in project intellij-community by JetBrains.

the class DelegatesToInspection method buildVisitor.

@NotNull
@Override
protected BaseInspectionVisitor buildVisitor() {
    return new BaseInspectionVisitor() {

        @Override
        public void visitAnnotation(@NotNull GrAnnotation annotation) {
            checkTarget(annotation);
            checkDelegatesTo(annotation);
        }

        private void checkTarget(GrAnnotation annotation) {
            if (!GroovyCommonClassNames.GROOVY_LANG_DELEGATES_TO_TARGET.equals(annotation.getQualifiedName()))
                return;
            final PsiElement owner = annotation.getParent().getParent();
            if (!(owner instanceof GrParameter))
                return;
            final boolean isTargetDeclared = annotation.findDeclaredAttributeValue("value") != null;
            String targetName = GrAnnotationUtil.inferStringAttribute(annotation, "value");
            final GrParameterList parameterList = DefaultGroovyMethods.asType(owner.getParent(), GrParameterList.class);
            for (GrParameter parameter : parameterList.getParameters()) {
                final PsiAnnotation delegatesTo = parameter.getModifierList().findAnnotation(GroovyCommonClassNames.GROOVY_LANG_DELEGATES_TO);
                if (delegatesTo != null) {
                    if (isTargetDeclared) {
                        final String curTarget = GrAnnotationUtil.inferStringAttribute(delegatesTo, "target");
                        if (curTarget != null && curTarget.equals(targetName)) {
                            //target is used
                            return;
                        }
                    } else {
                        if (delegatesTo.findDeclaredAttributeValue("target") == null && delegatesTo.findDeclaredAttributeValue("value") == null) {
                            // target is used
                            return;
                        }
                    }
                }
            }
            registerError(annotation.getClassReference(), GroovyInspectionBundle.message("target.annotation.is.unused"), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
        }

        private void checkDelegatesTo(GrAnnotation annotation) {
            if (!GroovyCommonClassNames.GROOVY_LANG_DELEGATES_TO.equals(annotation.getQualifiedName()))
                return;
            final PsiElement owner = annotation.getParent().getParent();
            if (!(owner instanceof GrParameter))
                return;
            final PsiAnnotationMemberValue targetPair = annotation.findDeclaredAttributeValue("target");
            if (targetPair == null)
                return;
            String targetName = GrAnnotationUtil.inferStringAttribute(annotation, "target");
            final GrParameterList parameterList = DefaultGroovyMethods.asType(owner.getParent(), GrParameterList.class);
            for (GrParameter parameter : parameterList.getParameters()) {
                final PsiAnnotation target = parameter.getModifierList().findAnnotation(GroovyCommonClassNames.GROOVY_LANG_DELEGATES_TO_TARGET);
                if (target != null) {
                    final String curTarget = GrAnnotationUtil.inferStringAttribute(target, "value");
                    if (curTarget != null && curTarget.equals(targetName)) {
                        //target is used
                        return;
                    }
                }
            }
            registerError(targetPair, GroovyInspectionBundle.message("target.0.does.not.exist", targetName != null ? targetName : "?"), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
        }
    };
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) BaseInspectionVisitor(org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor) GrAnnotation(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation) PsiAnnotation(com.intellij.psi.PsiAnnotation) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) NotNull(org.jetbrains.annotations.NotNull) PsiElement(com.intellij.psi.PsiElement) PsiAnnotationMemberValue(com.intellij.psi.PsiAnnotationMemberValue) NotNull(org.jetbrains.annotations.NotNull)

Example 10 with BaseInspectionVisitor

use of org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor in project intellij-community by JetBrains.

the class ChangeToOperatorInspection method buildVisitor.

@NotNull
@Override
protected BaseInspectionVisitor buildVisitor() {
    return new BaseInspectionVisitor() {

        @Override
        public void visitMethodCallExpression(@NotNull GrMethodCallExpression methodCall) {
            final String methodName = getMethodName(methodCall);
            if (methodName == null)
                return;
            Transformation transformation = TRANSFORMATIONS.get(methodName);
            if (transformation == null)
                return;
            PsiElement highlightElement = getHighlightElement(methodCall);
            if (highlightElement == null)
                return;
            if (transformation.couldApply(methodCall, getOptions())) {
                registerError(highlightElement, message("replace.with.operator.message", methodName), new LocalQuickFix[] { getFix(transformation, methodName) }, GENERIC_ERROR_OR_WARNING);
            }
        }
    };
}
Also used : Transformation(org.jetbrains.plugins.groovy.codeInspection.changeToOperator.transformations.Transformation) BaseInspectionVisitor(org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) NotNull(org.jetbrains.annotations.NotNull) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

NotNull (org.jetbrains.annotations.NotNull)15 BaseInspectionVisitor (org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor)15 PsiElement (com.intellij.psi.PsiElement)11 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)5 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)4 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)4 GrCodeReferenceElement (org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement)3 PsiAnnotation (com.intellij.psi.PsiAnnotation)2 PsiType (com.intellij.psi.PsiType)2 GroovyFileBase (org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase)2 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)2 GrMethodCallExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression)2 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)2 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)2 LocalQuickFix (com.intellij.codeInspection.LocalQuickFix)1 CompilerConfiguration (com.intellij.compiler.CompilerConfiguration)1 HierarchicalMethodSignature (com.intellij.psi.HierarchicalMethodSignature)1 PsiAnnotationMemberValue (com.intellij.psi.PsiAnnotationMemberValue)1 PsiClass (com.intellij.psi.PsiClass)1 PsiClassType (com.intellij.psi.PsiClassType)1