Search in sources :

Example 41 with PsiElementVisitor

use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.

the class ReturnTypeCanBeDeclaredInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        /* TODO: support functions - see https://github.com/kalessil/phpinspectionsea/pull/320 */
        @Override
        public void visitPhpMethod(@NotNull Method method) {
            final PhpLanguageLevel php = PhpLanguageLevel.get(holder.getProject());
            if (php.atLeast(PhpLanguageLevel.PHP700) && !magicMethods.contains(method.getName())) {
                final boolean isTarget = OpenapiElementsUtil.getReturnType(method) == null;
                if (isTarget) {
                    final PsiElement methodNameNode = NamedElementUtil.getNameIdentifier(method);
                    if (methodNameNode != null) {
                        final boolean supportNullableTypes = php.atLeast(PhpLanguageLevel.PHP710);
                        if (method.isAbstract()) {
                            this.handleAbstractMethod(method, methodNameNode, supportNullableTypes);
                        } else {
                            this.handleMethod(method, methodNameNode, supportNullableTypes);
                        }
                    }
                }
            }
        }

        private void handleAbstractMethod(@NotNull Method method, @NotNull PsiElement target, boolean supportNullableTypes) {
            final PhpDocComment docBlock = method.getDocComment();
            if (docBlock != null && docBlock.getReturnTag() != null) {
                this.handleMethod(method, target, supportNullableTypes);
            }
        }

        private void handleMethod(@NotNull Method method, @NotNull PsiElement target, boolean supportNullableTypes) {
            /* suggest nothing when the type is only partially resolved */
            final PhpType resolvedReturnType = OpenapiResolveUtil.resolveType(method, holder.getProject());
            if (resolvedReturnType == null) {
                return;
            } else if (resolvedReturnType.hasUnknown()) {
                /* adding class interface leading to promise-type for interface method */
                boolean isInfluencedByInterface = resolvedReturnType.size() == 2 && resolvedReturnType.filterUnknown().size() == 1;
                if (!isInfluencedByInterface) {
                    return;
                }
            }
            /* ignore DocBlock, resolve and normalize types instead (DocBlock is involved, but nevertheless) */
            final Set<String> normalizedTypes = resolvedReturnType.filterUnknown().getTypes().stream().map(Types::getType).collect(Collectors.toSet());
            this.checkUnrecognizedGenerator(method, normalizedTypes);
            this.checkReturnStatements(method, normalizedTypes);
            final boolean isVoidAvailable = PhpLanguageLevel.get(holder.getProject()).atLeast(PhpLanguageLevel.PHP710);
            final int typesCount = normalizedTypes.size();
            /* case 1: offer using void */
            if (supportNullableTypes && typesCount == 0 && isVoidAvailable) {
                final PsiElement firstReturn = PsiTreeUtil.findChildOfType(method, PhpReturn.class);
                if (firstReturn == null || ExpressionSemanticUtil.getScope(firstReturn) != method) {
                    final LocalQuickFix fixer = this.isMethodOverridden(method) ? null : new DeclareReturnTypeFix(Types.strVoid);
                    final String message = messagePattern.replace("%t%", Types.strVoid).replace("%n%", fixer == null ? " (please use change signature intention to fix this)" : "");
                    holder.registerProblem(target, MessagesPresentationUtil.prefixWithEa(message), fixer);
                }
            }
            /* case 2: offer using type */
            if (1 == typesCount) {
                final String singleType = normalizedTypes.iterator().next();
                final String suggestedType = isVoidAvailable && voidTypes.contains(singleType) ? Types.strVoid : this.compactType(singleType, method);
                final boolean isLegitBasic = singleType.startsWith("\\") || returnTypes.contains(singleType) || suggestedType.equals("self") || suggestedType.equals("static");
                final boolean isLegitVoid = !isLegitBasic && supportNullableTypes && suggestedType.equals(Types.strVoid);
                if (isLegitBasic || isLegitVoid) {
                    /* false-positive: '@return static' which is gets resolved into current class since 2019.2 */
                    final PhpDocComment docBlock = method.getDocComment();
                    final PhpDocReturnTag tag = docBlock == null ? null : docBlock.getReturnTag();
                    final boolean isStatic = tag != null && Arrays.stream(tag.getChildren()).map(PsiElement::getText).filter(t -> !t.isEmpty()).allMatch(t -> t.equals("static"));
                    final boolean isLegitStatic = isStatic && PhpLanguageLevel.get(holder.getProject()).atLeast(PhpLanguageLevel.PHP800);
                    if (!isStatic || isLegitStatic) {
                        final LocalQuickFix fixer = this.isMethodOverridden(method) ? null : new DeclareReturnTypeFix(isLegitStatic ? "static" : suggestedType);
                        final String message = messagePattern.replace("%t%", isLegitStatic ? "static" : suggestedType).replace("%n%", fixer == null ? " (please use change signature intention to fix this)" : "");
                        holder.registerProblem(target, MessagesPresentationUtil.prefixWithEa(message), fixer);
                    }
                }
            }
            /* case 3: offer using nullable type */
            if (supportNullableTypes && 2 == typesCount && normalizedTypes.contains(Types.strNull)) {
                normalizedTypes.remove(Types.strNull);
                final String nullableType = normalizedTypes.iterator().next();
                final String suggestedType = isVoidAvailable && voidTypes.contains(nullableType) ? Types.strVoid : compactType(nullableType, method);
                final boolean isLegitNullable = nullableType.startsWith("\\") || returnTypes.contains(nullableType) || suggestedType.equals("self");
                final boolean isLegitVoid = !isLegitNullable && suggestedType.equals(Types.strVoid);
                if (isLegitNullable || isLegitVoid) {
                    final String typeHint = isLegitVoid ? suggestedType : '?' + suggestedType;
                    final LocalQuickFix fixer = this.isMethodOverridden(method) ? null : new DeclareReturnTypeFix(typeHint);
                    final String message = messagePattern.replace("%t%", typeHint).replace("%n%", fixer == null ? " (please use change signature intention to fix this)" : "");
                    holder.registerProblem(target, MessagesPresentationUtil.prefixWithEa(message), fixer);
                }
            }
        }

        /* use change signature intention promoter */
        private boolean isMethodOverridden(@NotNull Method method) {
            boolean result = false;
            final PhpClass clazz = method.getContainingClass();
            if (clazz != null && !clazz.isFinal() && !method.isFinal() && !method.getAccess().isPrivate()) {
                final String methodName = method.getName();
                result = InterfacesExtractUtil.getCrawlInheritanceTree(clazz, true).stream().anyMatch(c -> c != clazz && c.findOwnMethodByName(methodName) != null) || OpenapiResolveUtil.resolveChildClasses(clazz.getFQN(), PhpIndex.getInstance(holder.getProject())).stream().anyMatch(c -> c.findOwnMethodByName(methodName) != null);
            }
            return result;
        }

        @NotNull
        private String compactType(@NotNull String type, @NotNull Method method) {
            String result = null;
            if (type.startsWith("\\") || type.equals("static")) {
                /* Strategy 1: respect `@return self` */
                if (LOOKUP_PHPDOC_RETURN_DECLARATIONS) {
                    final PhpDocComment phpDoc = method.getDocComment();
                    final PhpDocReturnTag phpReturn = phpDoc == null ? null : phpDoc.getReturnTag();
                    if (phpReturn != null) {
                        final boolean hasSelfReference = PsiTreeUtil.findChildrenOfType(phpReturn, PhpDocType.class).stream().anyMatch(t -> {
                            final String text = t.getText();
                            return text.equals("self") || text.equals("$this");
                        });
                        if (hasSelfReference) {
                            result = "self";
                        }
                    }
                }
                /* be sure to send back static for avoiding false-positives */
                result = (result == null && type.equals("static")) ? type : result;
                /* Strategy 2: scan imports */
                if (result == null) {
                    PsiElement groupCandidate = method.getContainingClass();
                    groups: while (groupCandidate != null && !(groupCandidate instanceof PsiFile)) {
                        if (groupCandidate instanceof GroupStatement) {
                            final List<PhpUse> imports = new ArrayList<>();
                            /* scan for imports in current group statement */
                            for (final PsiElement child : groupCandidate.getChildren()) {
                                if (child instanceof PhpUseList) {
                                    Collections.addAll(imports, ((PhpUseList) child).getDeclarations());
                                }
                            }
                            /* iterate imports and search for targets */
                            for (final PhpUse imported : imports) {
                                final PhpReference useReference = imported.getTargetReference();
                                if (useReference instanceof ClassReference && type.equals(useReference.getFQN())) {
                                    final String useAlias = imported.getAliasName();
                                    result = useAlias == null ? useReference.getName() : useAlias;
                                    imports.clear();
                                    break groups;
                                }
                            }
                            imports.clear();
                        }
                        groupCandidate = groupCandidate.getParent();
                    }
                }
                /* Strategy 3: relative QN for classes in sub-namespace */
                if (result == null || result.isEmpty()) {
                    final PhpClass clazz = method.getContainingClass();
                    final String nameSpace = null == clazz ? null : clazz.getNamespaceName();
                    if (nameSpace != null && nameSpace.length() > 1 && type.startsWith(nameSpace)) {
                        result = type.replace(nameSpace, "");
                    }
                }
            }
            return result == null ? type : result;
        }

        private void checkUnrecognizedGenerator(@NotNull Method method, @NotNull Set<String> types) {
            if (!types.contains("\\Generator")) {
                final PhpYield yield = PsiTreeUtil.findChildOfType(method, PhpYield.class);
                if (yield != null && ExpressionSemanticUtil.getScope(yield) == method) {
                    types.add("\\Generator");
                    if (PsiTreeUtil.findChildOfType(method, PhpReturn.class) == null) {
                        types.remove(Types.strNull);
                    }
                }
            }
        }

        private void checkReturnStatements(@NotNull Method method, @NotNull Set<String> types) {
            if (!types.isEmpty() && !method.isAbstract()) {
                /* non-implicit null return: omitted last return statement */
                if (!types.contains(Types.strNull) && !types.contains(Types.strVoid)) {
                    final GroupStatement body = ExpressionSemanticUtil.getGroupStatement(method);
                    final PsiElement last = body == null ? null : ExpressionSemanticUtil.getLastStatement(body);
                    if (!(last instanceof PhpReturn) && !OpenapiTypesUtil.isThrowExpression(last)) {
                        types.add(Types.strNull);
                    }
                }
                /* buggy parameter type resolving: no type, but null as default value */
                if (types.size() == 1 && types.contains(Types.strNull)) {
                    final GroupStatement body = ExpressionSemanticUtil.getGroupStatement(method);
                    if (body != null) {
                        final PhpReturn expression = PsiTreeUtil.findChildOfType(body, PhpReturn.class);
                        if (expression != null) {
                            final PsiElement value = ExpressionSemanticUtil.getReturnValue(expression);
                            if (value != null && !PhpLanguageUtil.isNull(value)) {
                                types.remove(Types.strNull);
                            }
                        }
                    }
                }
            }
        }
    };
}
Also used : PhpDocComment(com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment) java.util(java.util) com.jetbrains.php.lang.psi.elements(com.jetbrains.php.lang.psi.elements) PhpTokenTypes(com.jetbrains.php.lang.lexer.PhpTokenTypes) PhpDocType(com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocType) PhpIndex(com.jetbrains.php.PhpIndex) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) PhpDocReturnTag(com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocReturnTag) ProblemDescriptor(com.intellij.codeInspection.ProblemDescriptor) PsiElement(com.intellij.psi.PsiElement) PsiWhiteSpace(com.intellij.psi.PsiWhiteSpace) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) PhpType(com.jetbrains.php.lang.psi.resolve.types.PhpType) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) ProblemsHolder(com.intellij.codeInspection.ProblemsHolder) PhpPsiElementFactory(com.jetbrains.php.lang.psi.PhpPsiElementFactory) BasePhpInspection(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection) PhpLanguageLevel(com.kalessil.phpStorm.phpInspectionsEA.openApi.PhpLanguageLevel) InterfacesExtractUtil(com.kalessil.phpStorm.phpInspectionsEA.utils.hierarhy.InterfacesExtractUtil) OptionsComponent(com.kalessil.phpStorm.phpInspectionsEA.options.OptionsComponent) Collectors(java.util.stream.Collectors) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) com.kalessil.phpStorm.phpInspectionsEA.utils(com.kalessil.phpStorm.phpInspectionsEA.utils) NotNull(org.jetbrains.annotations.NotNull) javax.swing(javax.swing) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) NotNull(org.jetbrains.annotations.NotNull) PhpType(com.jetbrains.php.lang.psi.resolve.types.PhpType) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) PhpDocReturnTag(com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocReturnTag) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) PhpLanguageLevel(com.kalessil.phpStorm.phpInspectionsEA.openApi.PhpLanguageLevel) PhpDocComment(com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment) NotNull(org.jetbrains.annotations.NotNull)

Example 42 with PsiElementVisitor

use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.

the class StaticInvocationViaThisInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        @Override
        public void visitPhpMethodReference(@NotNull MethodReference reference) {
            final String methodName = reference.getName();
            if (methodName != null && !reference.isStatic() && !methodName.startsWith("static")) /* workaround for WI-33569 */
            {
                final PsiElement base = reference.getFirstChild();
                if (base != null && !(base instanceof FunctionReference)) {
                    final PsiElement operator = OpenapiPsiSearchUtil.findResolutionOperator(reference);
                    if (OpenapiTypesUtil.is(operator, PhpTokenTypes.ARROW)) {
                        if (base instanceof Variable && ((Variable) base).getName().equals("this")) {
                            /* $this->static() */
                            final Function scope = ExpressionSemanticUtil.getScope(reference);
                            if (scope instanceof Method && !((Method) scope).isStatic()) {
                                final PsiElement resolved = OpenapiResolveUtil.resolveReference(reference);
                                if (resolved instanceof Method) {
                                    final Method method = (Method) resolved;
                                    if (method.isStatic() && !this.shouldSkip(method)) {
                                        holder.registerProblem(base, String.format(MessagesPresentationUtil.prefixWithEa(messageThisUsed), method.getName()), new TheLocalFix(holder.getProject(), base, operator));
                                    }
                                }
                            }
                        } else {
                            /* <expression>->static() */
                            if (!(base instanceof Variable) || !this.isParameterOrUseVariable((Variable) base)) {
                                final PsiElement resolved = OpenapiResolveUtil.resolveReference(reference);
                                if (resolved instanceof Method) {
                                    final Method method = (Method) resolved;
                                    if (method.isStatic() && !this.shouldSkip(method)) {
                                        holder.registerProblem(reference, String.format(MessagesPresentationUtil.prefixWithEa(messageExpressionUsed), methodName));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private boolean shouldSkip(@NotNull Method method) {
            final String fqn = method.getFQN();
            if (EXCEPT_PHPUNIT_ASSERTIONS && fqn.startsWith("\\PHPUnit")) {
                final String normalized = fqn.indexOf('_') == -1 ? fqn : fqn.replaceAll("_", "\\\\");
                return normalized.startsWith("\\PHPUnit\\Framework\\");
            }
            if (EXCEPT_ELOQUENT_MODELS && fqn.startsWith("\\Illuminate\\Database\\Eloquent\\Model.")) {
                return true;
            }
            return false;
        }

        private boolean isParameterOrUseVariable(@NotNull Variable variable) {
            boolean result = false;
            final String name = variable.getName();
            if (!name.isEmpty()) {
                final Function scope = ExpressionSemanticUtil.getScope(variable);
                if (scope != null) {
                    result = Stream.of(scope.getParameters()).anyMatch(p -> name.equals(p.getName()));
                    if (!result) {
                        final List<Variable> variables = ExpressionSemanticUtil.getUseListVariables(scope);
                        if (variables != null && !variables.isEmpty()) {
                            result = variables.stream().anyMatch(v -> name.equals(v.getName()));
                            variables.clear();
                        }
                    }
                }
            }
            return result;
        }
    };
}
Also used : PhpPsiElementFactory(com.jetbrains.php.lang.psi.PhpPsiElementFactory) BasePhpInspection(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection) com.jetbrains.php.lang.psi.elements(com.jetbrains.php.lang.psi.elements) PhpTokenTypes(com.jetbrains.php.lang.lexer.PhpTokenTypes) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) OptionsComponent(com.kalessil.phpStorm.phpInspectionsEA.options.OptionsComponent) SmartPointerManager(com.intellij.psi.SmartPointerManager) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) com.kalessil.phpStorm.phpInspectionsEA.utils(com.kalessil.phpStorm.phpInspectionsEA.utils) List(java.util.List) Stream(java.util.stream.Stream) ProblemDescriptor(com.intellij.codeInspection.ProblemDescriptor) SmartPsiElementPointer(com.intellij.psi.SmartPsiElementPointer) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) NotNull(org.jetbrains.annotations.NotNull) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) ProblemsHolder(com.intellij.codeInspection.ProblemsHolder) javax.swing(javax.swing) NotNull(org.jetbrains.annotations.NotNull) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 43 with PsiElementVisitor

use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.

the class TraitsPropertiesConflictsInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        @Override
        public void visitPhpClass(@NotNull PhpClass clazz) {
            /* ensure there are traits being used at all */
            final PhpClass[] traits = clazz.getTraits();
            if (traits.length == 0) {
                return;
            }
            /* check conflict with own fields */
            for (final Field ownField : clazz.getOwnFields()) {
                final String ownFieldName = ownField.getName();
                if (!ownFieldName.isEmpty() && !ownField.isConstant() && !this.isDocBlockProperty(ownField, clazz)) {
                    final PhpModifier modifier = ownField.getModifier();
                    if (!modifier.isAbstract() && !this.isAnnotated(ownField)) {
                        final PsiElement ownFieldDefault = OpenapiResolveUtil.resolveDefaultValue(ownField);
                        for (final PhpClass trait : traits) {
                            final Field traitField = OpenapiResolveUtil.resolveField(trait, ownFieldName);
                            if (traitField != null && !this.isDocBlockProperty(traitField, trait)) {
                                final PsiElement traitFieldDefault = OpenapiResolveUtil.resolveDefaultValue(traitField);
                                final boolean isError;
                                if (ownFieldDefault == null || traitFieldDefault == null) {
                                    isError = traitFieldDefault != ownFieldDefault;
                                } else {
                                    isError = !OpenapiEquivalenceUtil.areEqual(traitFieldDefault, ownFieldDefault);
                                }
                                /* error case already covered by the IDEs */
                                final PsiElement ownFieldNameNode = NamedElementUtil.getNameIdentifier(ownField);
                                if (!isError && ownFieldNameNode != null) {
                                    holder.registerProblem(ownFieldNameNode, String.format(MessagesPresentationUtil.prefixWithEa(messagePattern), clazz.getName(), trait.getName(), ownFieldName), ProblemHighlightType.WEAK_WARNING);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            /* check parent class accessibility and map use statements with traits for reporting */
            final Map<PhpClass, PsiElement> useReportTargets = new HashMap<>();
            for (final PsiElement child : clazz.getChildren()) {
                if (child instanceof PhpUseList) {
                    for (final ClassReference reference : PsiTreeUtil.findChildrenOfType(child, ClassReference.class)) {
                        final PsiElement resolved = OpenapiResolveUtil.resolveReference(reference);
                        if (resolved instanceof PhpClass) {
                            useReportTargets.putIfAbsent((PhpClass) resolved, reference);
                        }
                    }
                }
            }
            final PhpClass parent = OpenapiResolveUtil.resolveSuperClass(clazz);
            if (parent == null || useReportTargets.isEmpty()) {
                useReportTargets.clear();
                return;
            }
            /* iterate parent non-private fields to find conflicting properties */
            for (final Field parentField : parent.getFields()) {
                final String parentFieldName = parentField.getName();
                if (!parentFieldName.isEmpty() && !parentField.isConstant() && !this.isDocBlockProperty(parentField, parent)) {
                    final PhpModifier modifier = parentField.getModifier();
                    if (!modifier.isPrivate() && !modifier.isAbstract()) {
                        final PsiElement parentFieldDefault = OpenapiResolveUtil.resolveDefaultValue(parentField);
                        for (final PhpClass trait : traits) {
                            final Field traitField = OpenapiResolveUtil.resolveField(trait, parentFieldName);
                            if (traitField != null && !this.isDocBlockProperty(traitField, trait)) {
                                final PsiElement traitFieldDefault = OpenapiResolveUtil.resolveDefaultValue(traitField);
                                final boolean isError;
                                if (parentFieldDefault == null || traitFieldDefault == null) {
                                    isError = traitFieldDefault != parentFieldDefault;
                                } else {
                                    isError = !OpenapiEquivalenceUtil.areEqual(traitFieldDefault, parentFieldDefault);
                                }
                                final PsiElement reportTarget = useReportTargets.get(trait);
                                if (reportTarget != null) {
                                    holder.registerProblem(reportTarget, String.format(MessagesPresentationUtil.prefixWithEa(messagePattern), clazz.getName(), trait.getName(), parentFieldName), isError ? ProblemHighlightType.GENERIC_ERROR_OR_WARNING : ProblemHighlightType.WEAK_WARNING);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            useReportTargets.clear();
        }

        private boolean isAnnotated(@NotNull Field ownField) {
            final PhpDocTag[] tags = PsiTreeUtil.getChildrenOfType(ownField.getDocComment(), PhpDocTag.class);
            return tags != null && Arrays.stream(tags).anyMatch(t -> !t.getName().equals(t.getName().toLowerCase()));
        }

        private boolean isDocBlockProperty(@NotNull Field field, @NotNull PhpClass clazz) {
            return ExpressionSemanticUtil.getBlockScope(field) != clazz;
        }
    };
}
Also used : Arrays(java.util.Arrays) BasePhpInspection(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection) com.jetbrains.php.lang.psi.elements(com.jetbrains.php.lang.psi.elements) HashMap(java.util.HashMap) PhpDocTag(com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) com.kalessil.phpStorm.phpInspectionsEA.utils(com.kalessil.phpStorm.phpInspectionsEA.utils) Map(java.util.Map) PsiElement(com.intellij.psi.PsiElement) ProblemHighlightType(com.intellij.codeInspection.ProblemHighlightType) NotNull(org.jetbrains.annotations.NotNull) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) ProblemsHolder(com.intellij.codeInspection.ProblemsHolder) HashMap(java.util.HashMap) NotNull(org.jetbrains.annotations.NotNull) PhpDocTag(com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 44 with PsiElementVisitor

use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.

the class DisconnectedForeachInstructionInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        @Override
        public void visitPhpForeach(@NotNull ForeachStatement foreach) {
            final GroupStatement foreachBody = ExpressionSemanticUtil.getGroupStatement(foreach);
            /* ensure foreach structure is ready for inspection */
            if (foreachBody != null) {
                final PsiElement[] statements = foreachBody.getChildren();
                if (statements.length > 0 && Stream.of(statements).anyMatch(s -> OpenapiTypesUtil.is(s, PhpElementTypes.HTML))) {
                    return;
                }
                /* pre-collect introduced and internally used variables */
                final Set<String> allModifiedVariables = this.collectCurrentAndOuterLoopVariables(foreach);
                final Map<PsiElement, Set<String>> instructionDependencies = new HashMap<>();
                /* iteration 1 - investigate what are dependencies and influence */
                for (final PsiElement oneInstruction : statements) {
                    if (oneInstruction instanceof PhpPsiElement && !(oneInstruction instanceof PsiComment)) {
                        final Set<String> individualDependencies = new HashSet<>();
                        instructionDependencies.put(oneInstruction, individualDependencies);
                        investigateInfluence((PhpPsiElement) oneInstruction, individualDependencies, allModifiedVariables);
                    }
                }
                /* iteration 2 - analyse dependencies */
                for (final PsiElement oneInstruction : statements) {
                    if (oneInstruction instanceof PhpPsiElement && !(oneInstruction instanceof PsiComment)) {
                        boolean isDependOnModified = false;
                        /* check if any dependency is overridden */
                        final Set<String> individualDependencies = instructionDependencies.get(oneInstruction);
                        if (individualDependencies != null && !individualDependencies.isEmpty()) {
                            isDependOnModified = individualDependencies.stream().anyMatch(allModifiedVariables::contains);
                            individualDependencies.clear();
                        }
                        /* verify and report if violation detected */
                        if (!isDependOnModified) {
                            final ExpressionType target = getExpressionType(oneInstruction);
                            if (ExpressionType.NEW != target && ExpressionType.ASSIGNMENT != target && ExpressionType.CLONE != target && ExpressionType.INCREMENT != target && ExpressionType.DECREMENT != target && ExpressionType.DOM_ELEMENT_CREATE != target && ExpressionType.ACCUMULATE_IN_ARRAY != target && ExpressionType.CONTROL_STATEMENTS != target) {
                                /* loops, ifs, switches, try's needs to be reported on keyword, others - complete */
                                final PsiElement reportingTarget = oneInstruction instanceof ControlStatement || oneInstruction instanceof Try || oneInstruction instanceof PhpSwitch ? oneInstruction.getFirstChild() : oneInstruction;
                                /* secure exceptions with '<?= ?>' constructions, false-positives with html */
                                if (!OpenapiTypesUtil.isPhpExpressionImpl(oneInstruction) && oneInstruction.getTextLength() > 0) {
                                    /* inner looping termination/continuation should be taken into account */
                                    final PsiElement loopInterrupter = PsiTreeUtil.findChildOfAnyType(oneInstruction, true, PhpBreak.class, PhpContinue.class, PhpReturn.class, OpenapiPlatformUtil.classes.get("PhpThrow"));
                                    /* operating with variables should be taken into account */
                                    final boolean isVariablesUsed = PsiTreeUtil.findChildOfAnyType(oneInstruction, true, (Class) Variable.class) != null;
                                    if (null == loopInterrupter && isVariablesUsed) {
                                        holder.registerProblem(reportingTarget, MessagesPresentationUtil.prefixWithEa(messageDisconnected));
                                    }
                                }
                            }
                            if (SUGGEST_USING_CLONE && (ExpressionType.DOM_ELEMENT_CREATE == target || ExpressionType.NEW == target)) {
                                holder.registerProblem(oneInstruction, MessagesPresentationUtil.prefixWithEa(messageUseClone));
                            }
                        }
                    }
                }
                /* release containers content */
                allModifiedVariables.clear();
                instructionDependencies.values().forEach(Set::clear);
                instructionDependencies.clear();
            }
        }

        private Set<String> collectCurrentAndOuterLoopVariables(@NotNull ForeachStatement foreach) {
            final Set<String> variables = new HashSet<>();
            PsiElement current = foreach;
            while (current != null && !(current instanceof Function) && !(current instanceof PsiFile)) {
                if (current instanceof ForeachStatement) {
                    ((ForeachStatement) current).getVariables().forEach(v -> variables.add(v.getName()));
                }
                current = current.getParent();
            }
            return variables;
        }

        private void investigateInfluence(@Nullable PhpPsiElement oneInstruction, @NotNull Set<String> individualDependencies, @NotNull Set<String> allModifiedVariables) {
            for (final Variable variable : PsiTreeUtil.findChildrenOfType(oneInstruction, Variable.class)) {
                final String variableName = variable.getName();
                PsiElement valueContainer = variable;
                PsiElement parent = variable.getParent();
                while (parent instanceof FieldReference) {
                    valueContainer = parent;
                    parent = parent.getParent();
                }
                /* a special case: `[] = ` and `array() = ` unboxing */
                if (OpenapiTypesUtil.is(parent, PhpElementTypes.ARRAY_VALUE)) {
                    parent = parent.getParent();
                    if (parent instanceof ArrayCreationExpression) {
                        parent = parent.getParent();
                    }
                }
                final PsiElement grandParent = parent.getParent();
                /* writing into variable */
                if (parent instanceof AssignmentExpression) {
                    /* php-specific `list(...) =` , `[...] =` construction */
                    if (parent instanceof MultiassignmentExpression) {
                        final MultiassignmentExpression assignment = (MultiassignmentExpression) parent;
                        if (assignment.getValue() != variable) {
                            allModifiedVariables.add(variableName);
                            individualDependencies.add(variableName);
                            continue;
                        }
                    } else {
                        final AssignmentExpression assignment = (AssignmentExpression) parent;
                        if (assignment.getVariable() == valueContainer) {
                            /* we are modifying the variable */
                            allModifiedVariables.add(variableName);
                            /* self-assignment and field assignment counted as the variable dependent on itself  */
                            if (assignment instanceof SelfAssignmentExpression || valueContainer instanceof FieldReference) {
                                individualDependencies.add(variableName);
                            }
                            /* assignments as call arguments counted as the variable dependent on itself */
                            if (grandParent instanceof ParameterList) {
                                individualDependencies.add(variableName);
                            }
                            continue;
                        }
                    }
                }
                /* adding into an arrays; we both depend and modify the container */
                if (parent instanceof ArrayAccessExpression && valueContainer == ((ArrayAccessExpression) parent).getValue()) {
                    allModifiedVariables.add(variableName);
                    individualDependencies.add(variableName);
                }
                if (parent instanceof ParameterList) {
                    if (grandParent instanceof MethodReference) {
                        /* an object consumes the variable, perhaps modification takes place */
                        final MethodReference reference = (MethodReference) grandParent;
                        final PsiElement referenceOperator = OpenapiPsiSearchUtil.findResolutionOperator(reference);
                        if (OpenapiTypesUtil.is(referenceOperator, PhpTokenTypes.ARROW)) {
                            final PsiElement variableCandidate = reference.getFirstPsiChild();
                            if (variableCandidate instanceof Variable) {
                                allModifiedVariables.add(((Variable) variableCandidate).getName());
                                continue;
                            }
                        }
                    } else if (OpenapiTypesUtil.isFunctionReference(grandParent)) {
                        /* php will create variable, if it is by reference */
                        final FunctionReference reference = (FunctionReference) grandParent;
                        final int position = ArrayUtils.indexOf(reference.getParameters(), variable);
                        if (position != -1) {
                            final PsiElement resolved = OpenapiResolveUtil.resolveReference(reference);
                            if (resolved instanceof Function) {
                                final Parameter[] parameters = ((Function) resolved).getParameters();
                                if (parameters.length > position && parameters[position].isPassByRef()) {
                                    allModifiedVariables.add(variableName);
                                    individualDependencies.add(variableName);
                                    continue;
                                }
                            }
                        }
                    }
                }
                /* increment/decrement are also write operations */
                final ExpressionType type = this.getExpressionType(parent);
                if (ExpressionType.INCREMENT == type || ExpressionType.DECREMENT == type) {
                    allModifiedVariables.add(variableName);
                    individualDependencies.add(variableName);
                    continue;
                }
                /* TODO: lookup for array access and property access */
                individualDependencies.add(variableName);
            }
            /* handle compact function usage */
            for (final FunctionReference reference : PsiTreeUtil.findChildrenOfType(oneInstruction, FunctionReference.class)) {
                if (OpenapiTypesUtil.isFunctionReference(reference)) {
                    final String functionName = reference.getName();
                    if (functionName != null && functionName.equals("compact")) {
                        for (final PsiElement argument : reference.getParameters()) {
                            if (argument instanceof StringLiteralExpression) {
                                final String compactedVariableName = ((StringLiteralExpression) argument).getContents();
                                if (!compactedVariableName.isEmpty()) {
                                    individualDependencies.add(compactedVariableName);
                                }
                            }
                        }
                    }
                }
            }
        }

        @NotNull
        private ExpressionType getExpressionType(@Nullable PsiElement expression) {
            if (expression instanceof PhpBreak || expression instanceof PhpContinue || expression instanceof PhpReturn) {
                return ExpressionType.CONTROL_STATEMENTS;
            }
            /* regular '...;' statements */
            if (OpenapiTypesUtil.isStatementImpl(expression)) {
                return getExpressionType(((Statement) expression).getFirstPsiChild());
            }
            /* unary operations */
            if (expression instanceof UnaryExpression) {
                final PsiElement operation = ((UnaryExpression) expression).getOperation();
                if (OpenapiTypesUtil.is(operation, PhpTokenTypes.opINCREMENT)) {
                    return ExpressionType.INCREMENT;
                }
                if (OpenapiTypesUtil.is(operation, PhpTokenTypes.opDECREMENT)) {
                    return ExpressionType.DECREMENT;
                }
            }
            /* different types of assignments */
            if (expression instanceof AssignmentExpression) {
                final AssignmentExpression assignment = (AssignmentExpression) expression;
                final PsiElement variable = assignment.getVariable();
                if (variable instanceof Variable) {
                    final PsiElement value = assignment.getValue();
                    if (value instanceof NewExpression) {
                        return ExpressionType.NEW;
                    } else if (value instanceof UnaryExpression) {
                        if (OpenapiTypesUtil.is(((UnaryExpression) value).getOperation(), PhpTokenTypes.kwCLONE)) {
                            return ExpressionType.CLONE;
                        }
                    } else if (value instanceof MethodReference) {
                        final MethodReference call = (MethodReference) value;
                        final String methodName = call.getName();
                        if (methodName != null && methodName.equals("createElement")) {
                            final PsiElement resolved = OpenapiResolveUtil.resolveReference(call);
                            if (resolved instanceof Method && ((Method) resolved).getFQN().equals("\\DOMDocument.createElement")) {
                                return ExpressionType.DOM_ELEMENT_CREATE;
                            }
                        }
                    }
                    /* allow all assignations afterwards */
                    return ExpressionType.ASSIGNMENT;
                }
                /* accumulating something in external container */
                if (variable instanceof ArrayAccessExpression) {
                    final ArrayAccessExpression storage = (ArrayAccessExpression) variable;
                    if (null == storage.getIndex() || null == storage.getIndex().getValue()) {
                        return ExpressionType.ACCUMULATE_IN_ARRAY;
                    }
                }
            }
            return ExpressionType.OTHER;
        }
    };
}
Also used : BasePhpInspection(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection) com.jetbrains.php.lang.psi.elements(com.jetbrains.php.lang.psi.elements) PhpTokenTypes(com.jetbrains.php.lang.lexer.PhpTokenTypes) Set(java.util.Set) HashMap(java.util.HashMap) OptionsComponent(com.kalessil.phpStorm.phpInspectionsEA.options.OptionsComponent) HashSet(java.util.HashSet) Nullable(org.jetbrains.annotations.Nullable) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) com.kalessil.phpStorm.phpInspectionsEA.utils(com.kalessil.phpStorm.phpInspectionsEA.utils) Stream(java.util.stream.Stream) Map(java.util.Map) PsiComment(com.intellij.psi.PsiComment) PsiElement(com.intellij.psi.PsiElement) PsiFile(com.intellij.psi.PsiFile) NotNull(org.jetbrains.annotations.NotNull) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) PhpElementTypes(com.jetbrains.php.lang.parser.PhpElementTypes) ProblemsHolder(com.intellij.codeInspection.ProblemsHolder) ArrayUtils(org.apache.commons.lang.ArrayUtils) javax.swing(javax.swing) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) NotNull(org.jetbrains.annotations.NotNull) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) HashSet(java.util.HashSet) PsiComment(com.intellij.psi.PsiComment) Nullable(org.jetbrains.annotations.Nullable) NotNull(org.jetbrains.annotations.NotNull)

Example 45 with PsiElementVisitor

use of com.intellij.psi.PsiElementVisitor in project phpinspectionsea by kalessil.

the class ClassConstantUsageCorrectnessInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        @Override
        public void visitPhpClassConstantReference(@NotNull ClassConstantReference constantReference) {
            final String constantName = constantReference.getName();
            if (constantName != null && constantName.equals("class")) {
                final PsiElement reference = constantReference.getClassReference();
                if (reference instanceof ClassReference) {
                    final ClassReference clazz = (ClassReference) reference;
                    final String referencedQn = reference.getText();
                    final PsiElement resolved = validReferences.contains(referencedQn) ? null : OpenapiResolveUtil.resolveReference(clazz);
                    if (resolved instanceof PhpClass) {
                        /* the resolved class will accumulate case issue in its FQN */
                        final List<String> variants = this.getVariants(clazz, (PhpClass) resolved);
                        if (!variants.isEmpty()) {
                            if (variants.stream().noneMatch(referencedQn::equals)) {
                                holder.registerProblem(reference, MessagesPresentationUtil.prefixWithEa(message));
                            }
                            variants.clear();
                        }
                    }
                }
            }
        }

        @NotNull
        private List<String> getVariants(@NotNull ClassReference reference, @NotNull PhpClass clazz) {
            final List<String> result = new ArrayList<>();
            final String referenceText = reference.getText();
            final String referenceTextLowercase = referenceText.toLowerCase();
            if (referenceText.startsWith("\\")) {
                /* FQN specified, resolve as we might have case issues there */
                final Project project = holder.getProject();
                final Collection<PhpClass> resolved = PhpIndex.getInstance(project).getClassesByFQN(referenceText);
                if (!resolved.isEmpty()) {
                    result.add(resolved.iterator().next().getFQN());
                }
            } else {
                PhpNamespace namespace = null;
                PsiElement current = reference.getParent();
                while (current != null && !(current instanceof PsiFile)) {
                    if (current instanceof PhpNamespace) {
                        namespace = (PhpNamespace) current;
                        break;
                    }
                    current = current.getParent();
                }
                final String classFqn = clazz.getFQN();
                if (referenceText.contains("\\")) {
                    /* RQN specified, check if resolved class in the same NS */
                    final String NsFqn = namespace == null ? null : namespace.getFQN();
                    if (NsFqn != null && !NsFqn.equals("\\")) {
                        final String classFqnLowercase = classFqn.toLowerCase();
                        if (classFqnLowercase.startsWith(NsFqn.toLowerCase()) || classFqnLowercase.endsWith('\\' + referenceTextLowercase)) {
                            result.add(classFqn.substring(classFqn.length() - referenceText.length()));
                        }
                    }
                    /* RQN specified, check if resolved class in aliased NS */
                    final List<PhpUse> uses = new ArrayList<>();
                    if (namespace != null) {
                        final GroupStatement body = namespace.getStatements();
                        if (body != null) {
                            Arrays.stream(body.getStatements()).filter(statement -> statement instanceof PhpUseList).forEach(statement -> Collections.addAll(uses, ((PhpUseList) statement).getDeclarations()));
                        }
                        for (final PhpUse use : uses) {
                            final String alias = use.getAliasName();
                            if (alias != null && referenceTextLowercase.startsWith(alias.toLowerCase())) {
                                final PhpReference targetReference = use.getTargetReference();
                                if (targetReference != null) {
                                    result.add(clazz.getFQN().replace(targetReference.getText(), alias).replaceAll("^\\\\", ""));
                                }
                            }
                        }
                    }
                    uses.clear();
                } else {
                    final List<PhpUse> uses = new ArrayList<>();
                    if (namespace != null) {
                        /* find imports inside know namespace */
                        final GroupStatement body = namespace.getStatements();
                        if (body != null) {
                            Arrays.stream(body.getStatements()).filter(statement -> statement instanceof PhpUseList).forEach(statement -> Collections.addAll(uses, ((PhpUseList) statement).getDeclarations()));
                        }
                    } else {
                        final PsiFile file = reference.getContainingFile();
                        if (file instanceof PhpFile) {
                            /* find imports inside a file without namespace */
                            ((PhpFile) file).getTopLevelDefs().values().stream().filter(definition -> definition instanceof PhpUse).forEach(definition -> uses.add((PhpUse) definition));
                        } else {
                            /* fallback, the most greedy strategy */
                            uses.addAll(PsiTreeUtil.findChildrenOfType(current, PhpUse.class));
                        }
                    }
                    /* imports (incl. aliases) */
                    for (final PhpUse use : uses) {
                        if (use.getFQN().equalsIgnoreCase(classFqn)) {
                            final String alias = use.getAliasName();
                            final PsiElement what = use.getFirstChild();
                            if (alias != null) {
                                /* alias as it is */
                                result.add(alias);
                            } else if (what instanceof ClassReference) {
                                /* resolve the imported class, as its the source for correct naming */
                                final PsiElement resolved = OpenapiResolveUtil.resolveReference((ClassReference) what);
                                if (resolved instanceof PhpClass) {
                                    final PhpClass resolvedImport = (PhpClass) resolved;
                                    final boolean importPrecise = resolvedImport.getFQN().endsWith(what.getText());
                                    if (!importPrecise || !resolvedImport.getName().equals(referenceText)) {
                                        result.add(resolvedImport.getFQN());
                                    }
                                }
                            }
                        } else {
                            final String alias = use.getAliasName();
                            if (alias != null && alias.equalsIgnoreCase(referenceText)) {
                                result.add(alias);
                            }
                        }
                    }
                    uses.clear();
                }
            }
            return result;
        }
    };
}
Also used : java.util(java.util) BasePhpInspection(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection) com.jetbrains.php.lang.psi.elements(com.jetbrains.php.lang.psi.elements) PhpIndex(com.jetbrains.php.PhpIndex) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) PhpFile(com.jetbrains.php.lang.psi.PhpFile) OpenapiResolveUtil(com.kalessil.phpStorm.phpInspectionsEA.utils.OpenapiResolveUtil) MessagesPresentationUtil(com.kalessil.phpStorm.phpInspectionsEA.utils.MessagesPresentationUtil) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) NotNull(org.jetbrains.annotations.NotNull) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) ProblemsHolder(com.intellij.codeInspection.ProblemsHolder) PhpFile(com.jetbrains.php.lang.psi.PhpFile) NotNull(org.jetbrains.annotations.NotNull) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

PsiElementVisitor (com.intellij.psi.PsiElementVisitor)60 PsiElement (com.intellij.psi.PsiElement)54 NotNull (org.jetbrains.annotations.NotNull)49 ProblemsHolder (com.intellij.codeInspection.ProblemsHolder)39 BasePhpElementVisitor (com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor)37 BasePhpInspection (com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection)37 com.jetbrains.php.lang.psi.elements (com.jetbrains.php.lang.psi.elements)27 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)21 Project (com.intellij.openapi.project.Project)19 MessagesPresentationUtil (com.kalessil.phpStorm.phpInspectionsEA.utils.MessagesPresentationUtil)19 PhpTokenTypes (com.jetbrains.php.lang.lexer.PhpTokenTypes)17 Set (java.util.Set)17 com.kalessil.phpStorm.phpInspectionsEA.utils (com.kalessil.phpStorm.phpInspectionsEA.utils)16 HashSet (java.util.HashSet)16 OptionsComponent (com.kalessil.phpStorm.phpInspectionsEA.options.OptionsComponent)15 javax.swing (javax.swing)15 LocalQuickFix (com.intellij.codeInspection.LocalQuickFix)14 PhpType (com.jetbrains.php.lang.psi.resolve.types.PhpType)14 ProblemDescriptor (com.intellij.codeInspection.ProblemDescriptor)12 ProblemHighlightType (com.intellij.codeInspection.ProblemHighlightType)12