Search in sources :

Example 16 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class PatternValidator method checkExpression.

private void checkExpression(PsiExpression expression, final PsiAnnotation[] annotations, ProblemsHolder holder) {
    if (annotations.length == 0)
        return;
    final PsiAnnotation psiAnnotation = annotations[0];
    // cache compiled pattern with annotation
    CachedValue<Pattern> p = psiAnnotation.getUserData(COMPLIED_PATTERN);
    if (p == null) {
        final CachedValueProvider<Pattern> provider = () -> {
            final String pattern = AnnotationUtilEx.calcAnnotationValue(psiAnnotation, "value");
            Pattern p1 = null;
            if (pattern != null) {
                try {
                    p1 = Pattern.compile(pattern);
                } catch (PatternSyntaxException e) {
                // pattern stays null
                }
            }
            return CachedValueProvider.Result.create(p1, (Object[]) annotations);
        };
        p = CachedValuesManager.getManager(expression.getProject()).createCachedValue(provider, false);
        psiAnnotation.putUserData(COMPLIED_PATTERN, p);
    }
    final Pattern pattern = p.getValue();
    if (pattern == null)
        return;
    List<PsiExpression> nonConstantElements = new SmartList<>();
    final Object result = new SubstitutedExpressionEvaluationHelper(expression.getProject()).computeExpression(expression, myConfiguration.getAdvancedConfiguration().getDfaOption(), false, nonConstantElements);
    final String o = result == null ? null : String.valueOf(result);
    if (o != null) {
        if (!pattern.matcher(o).matches()) {
            if (annotations.length > 1) {
                // the last element contains the element's actual annotation
                final String fqn = annotations[annotations.length - 1].getQualifiedName();
                assert fqn != null;
                final String name = StringUtil.getShortName(fqn);
                holder.registerProblem(expression, MessageFormat.format("Expression ''{0}'' doesn''t match ''{1}'' pattern: {2}", o, name, pattern.pattern()));
            } else {
                holder.registerProblem(expression, MessageFormat.format("Expression ''{0}'' doesn''t match pattern: {1}", o, pattern.pattern()));
            }
        }
    } else if (CHECK_NON_CONSTANT_VALUES) {
        for (PsiExpression expr : nonConstantElements) {
            final PsiElement e;
            if (expr instanceof PsiReferenceExpression) {
                e = ((PsiReferenceExpression) expr).resolve();
            } else if (expr instanceof PsiMethodCallExpression) {
                e = ((PsiMethodCallExpression) expr).getMethodExpression().resolve();
            } else {
                e = expr;
            }
            final PsiModifierListOwner owner = e instanceof PsiModifierListOwner ? (PsiModifierListOwner) e : null;
            LocalQuickFix quickFix;
            if (owner != null && PsiUtilEx.isLanguageAnnotationTarget(owner)) {
                PsiAnnotation[] resolvedAnnos = AnnotationUtilEx.getAnnotationFrom(owner, myConfiguration.getAdvancedConfiguration().getPatternAnnotationPair(), true);
                if (resolvedAnnos.length == 2 && annotations.length == 2 && Comparing.strEqual(resolvedAnnos[1].getQualifiedName(), annotations[1].getQualifiedName())) {
                    // both target and source annotated indirectly with the same anno
                    return;
                }
                final String classname = myConfiguration.getAdvancedConfiguration().getSubstAnnotationPair().first;
                quickFix = AnnotateFix.canApplyOn(owner) ? new AnnotateFix(classname) : new IntroduceVariableFix();
            } else {
                quickFix = new IntroduceVariableFix();
            }
            holder.registerProblem(expr, "Unsubstituted expression", quickFix);
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) SubstitutedExpressionEvaluationHelper(org.intellij.plugins.intelliLang.util.SubstitutedExpressionEvaluationHelper) SmartList(com.intellij.util.SmartList) AnnotateFix(org.intellij.plugins.intelliLang.util.AnnotateFix) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 17 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class PluginXmlDomInspection method annotateExtension.

private static void annotateExtension(Extension extension, DomElementAnnotationHolder holder) {
    final ExtensionPoint extensionPoint = extension.getExtensionPoint();
    if (extensionPoint == null)
        return;
    final GenericAttributeValue<PsiClass> interfaceAttribute = extensionPoint.getInterface();
    if (DomUtil.hasXml(interfaceAttribute)) {
        final PsiClass value = interfaceAttribute.getValue();
        if (value != null && value.isDeprecated()) {
            holder.createProblem(extension, ProblemHighlightType.LIKE_DEPRECATED, "Deprecated EP '" + extensionPoint.getEffectiveQualifiedName() + "'", null);
            return;
        }
    }
    if (ExtensionPoints.ERROR_HANDLER.equals(extensionPoint.getEffectiveQualifiedName()) && extension.exists()) {
        String implementation = extension.getXmlTag().getAttributeValue("implementation");
        if (ITNReporter.class.getName().equals(implementation)) {
            IdeaPlugin plugin = extension.getParentOfType(IdeaPlugin.class, true);
            if (plugin != null) {
                Vendor vendor = plugin.getVendor();
                if (DomUtil.hasXml(vendor) && PluginManagerMain.isDevelopedByJetBrains(vendor.getValue())) {
                    LocalQuickFix fix = new RemoveDomElementQuickFix(extension);
                    holder.createProblem(extension, ProblemHighlightType.LIKE_UNUSED_SYMBOL, "Exceptions from plugins developed by JetBrains are reported via ITNReporter automatically," + " there is no need to specify it explicitly", null, fix).highlightWholeElement();
                }
            }
        }
    }
    final List<? extends DomAttributeChildDescription> descriptions = extension.getGenericInfo().getAttributeChildrenDescriptions();
    for (DomAttributeChildDescription attributeDescription : descriptions) {
        final GenericAttributeValue attributeValue = attributeDescription.getDomAttributeValue(extension);
        if (attributeValue == null || !DomUtil.hasXml(attributeValue))
            continue;
        // IconsReferencesContributor
        if ("icon".equals(attributeDescription.getXmlElementName())) {
            annotateResolveProblems(holder, attributeValue);
        }
        final PsiElement declaration = attributeDescription.getDeclaration(extension.getManager().getProject());
        if (declaration instanceof PsiField) {
            PsiField psiField = (PsiField) declaration;
            if (psiField.isDeprecated()) {
                holder.createProblem(attributeValue, ProblemHighlightType.LIKE_DEPRECATED, "Deprecated attribute '" + attributeDescription.getName() + "'", null).highlightWholeElement();
            }
        }
    }
}
Also used : LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) DomAttributeChildDescription(com.intellij.util.xml.reflect.DomAttributeChildDescription) ITNReporter(com.intellij.diagnostic.ITNReporter)

Example 18 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class BaseInspectionVisitor method registerErrorAtRange.

protected final void registerErrorAtRange(@NotNull PsiElement startLocation, @NotNull PsiElement endLocation, Object... infos) {
    if (startLocation.getTextLength() == 0 && startLocation == endLocation) {
        return;
    }
    final LocalQuickFix[] fixes = createAndInitFixes(infos);
    final String description = inspection.buildErrorString(infos);
    final ProblemDescriptor problemDescriptor = holder.getManager().createProblemDescriptor(startLocation, endLocation, description, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, onTheFly, fixes);
    holder.registerProblem(problemDescriptor);
}
Also used : ProblemDescriptor(com.intellij.codeInspection.ProblemDescriptor) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix)

Example 19 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class GroovyTypeCheckVisitor method processAssignment.

private void processAssignment(@NotNull PsiType expectedType, @NotNull GrExpression expression, @NotNull PsiElement toHighlight, @NotNull @PropertyKey(resourceBundle = GroovyBundle.BUNDLE) String messageKey, @NotNull PsiElement context, @NotNull ApplicableTo position) {
    {
        // check if  current assignment is constructor call
        final GrListOrMap initializer = getTupleInitializer(expression);
        if (initializer != null) {
            processConstructorCall(new GrListOrMapInfo(initializer));
            return;
        }
    }
    if (PsiUtil.isRawClassMemberAccess(expression))
        return;
    if (checkForImplicitEnumAssigning(expectedType, expression, expression))
        return;
    final PsiType actualType = expression.getType();
    if (actualType == null)
        return;
    final ConversionResult result = TypesUtil.canAssign(expectedType, actualType, context, position);
    if (result == ConversionResult.OK)
        return;
    final List<LocalQuickFix> fixes = ContainerUtil.newArrayList();
    {
        fixes.add(new GrCastFix(expectedType, expression));
        final String varName = getLValueVarName(toHighlight);
        if (varName != null) {
            fixes.add(new GrChangeVariableType(actualType, varName));
        }
    }
    final String message = GroovyBundle.message(messageKey, actualType.getPresentableText(), expectedType.getPresentableText());
    registerError(toHighlight, message, fixes.toArray(new LocalQuickFix[fixes.size()]), result == ConversionResult.ERROR ? ProblemHighlightType.GENERIC_ERROR : ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
Also used : ConversionResult(org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.ConversionResult) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) GrListOrMap(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString)

Example 20 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class GroovyTypeCheckVisitorHelper method genCastFixes.

@NotNull
public static LocalQuickFix[] genCastFixes(@NotNull GrSignature signature, @NotNull PsiType[] argumentTypes, @Nullable GrArgumentList argumentList) {
    if (argumentList == null)
        return LocalQuickFix.EMPTY_ARRAY;
    final List<GrExpression> args = getExpressionArgumentsOfCall(argumentList);
    if (args == null)
        return LocalQuickFix.EMPTY_ARRAY;
    final List<Pair<Integer, PsiType>> allErrors = new ArrayList<>();
    final List<GrClosureSignature> signatures = GrClosureSignatureUtil.generateSimpleSignatures(signature);
    for (GrClosureSignature closureSignature : signatures) {
        final GrClosureSignatureUtil.MapResultWithError<PsiType> map = GrClosureSignatureUtil.mapSimpleSignatureWithErrors(closureSignature, argumentTypes, id, argumentList, 1);
        if (map != null) {
            final List<Pair<Integer, PsiType>> errors = map.getErrors();
            for (Pair<Integer, PsiType> error : errors) {
                if (!(error.first == 0 && PsiImplUtil.hasNamedArguments(argumentList))) {
                    allErrors.add(error);
                }
            }
        }
    }
    final ArrayList<LocalQuickFix> fixes = new ArrayList<>();
    for (Pair<Integer, PsiType> error : allErrors) {
        if (args.size() > error.first && error.second != null) {
            fixes.add(new ParameterCastFix(error.first, error.second, args.get(error.first)));
        }
    }
    return fixes.toArray(new LocalQuickFix[fixes.size()]);
}
Also used : ArrayList(java.util.ArrayList) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrClosureSignatureUtil(org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil) ParameterCastFix(org.jetbrains.plugins.groovy.codeInspection.assignment.ParameterCastFix) GrClosureSignature(org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrClosureSignature) Pair(com.intellij.openapi.util.Pair) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

LocalQuickFix (com.intellij.codeInspection.LocalQuickFix)59 NotNull (org.jetbrains.annotations.NotNull)20 PsiElement (com.intellij.psi.PsiElement)16 Nullable (org.jetbrains.annotations.Nullable)11 IntentionAction (com.intellij.codeInsight.intention.IntentionAction)10 ProblemDescriptor (com.intellij.codeInspection.ProblemDescriptor)10 ASTNode (com.intellij.lang.ASTNode)6 Project (com.intellij.openapi.project.Project)6 VirtualFile (com.intellij.openapi.vfs.VirtualFile)6 XmlTag (com.intellij.psi.xml.XmlTag)6 PsiFile (com.intellij.psi.PsiFile)5 PsiReference (com.intellij.psi.PsiReference)5 ArrayList (java.util.ArrayList)5 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)4 LocalQuickFixProvider (com.intellij.codeInspection.LocalQuickFixProvider)3 QuickFixWrapper (com.intellij.codeInspection.ex.QuickFixWrapper)3 Pair (com.intellij.openapi.util.Pair)3 TextRange (com.intellij.openapi.util.TextRange)3 XmlAttributeDescriptor (com.intellij.xml.XmlAttributeDescriptor)3 XmlElementDescriptor (com.intellij.xml.XmlElementDescriptor)3