Java Code Examples for com.intellij.lang.annotation.Annotation#registerFix()

The following examples show how to use com.intellij.lang.annotation.Annotation#registerFix() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotatorUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
static void addError(
    AnnotationHolder holder, SpecModelValidationError error, List<IntentionAction> fixes) {
  PsiElement errorElement = (PsiElement) error.element;
  Annotation errorAnnotation =
      holder.createErrorAnnotation(
          Optional.of(errorElement)
              .filter(element -> element instanceof PsiClass || element instanceof PsiMethod)
              .map(PsiNameIdentifierOwner.class::cast)
              .map(PsiNameIdentifierOwner::getNameIdentifier)
              .orElse(errorElement),
          error.message);
  if (!fixes.isEmpty()) {
    for (IntentionAction fix : fixes) {
      errorAnnotation.registerFix(fix);
    }
  }
}
 
Example 2
Source File: LatteAnnotator.java    From intellij-latte with MIT License 6 votes vote down vote up
private void checkNetteAttr(@NotNull LatteNetteAttr element, @NotNull AnnotationHolder holder) {
	PsiElement attrName = element.getAttrName();
	String tagName = attrName.getText();
	boolean prefixed = false;

	if (tagName.startsWith("n:inner-")) {
		prefixed = true;
		tagName = tagName.substring(8);
	} else if (tagName.startsWith("n:tag-")) {
		prefixed = true;
		tagName = tagName.substring(6);
	} else {
		tagName = tagName.substring(2);
	}

	Project project = element.getProject();
	LatteTagSettings macro = LatteConfiguration.getInstance(project).getTag(tagName);
	if (macro == null || macro.getType() == LatteTagSettings.Type.UNPAIRED) {
		Annotation annotation = holder.createErrorAnnotation(attrName, "Unknown attribute tag " + attrName.getText());
		annotation.registerFix(new AddCustomPairMacro(tagName));
		if (!prefixed) annotation.registerFix(new AddCustomAttrOnlyMacro(tagName));

	} else if (prefixed && macro.getType() != LatteTagSettings.Type.PAIR && macro.getType() != LatteTagSettings.Type.AUTO_EMPTY) {
		holder.createErrorAnnotation(attrName, "Attribute tag n:" + tagName + " can not be used with prefix.");
	}
}
 
Example 3
Source File: InflateViewAnnotator.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) {

    InflateContainer inflateContainer = matchInflate(psiElement);
    if(inflateContainer == null) {
        return;
    }

    Annotation inflateLocal = annotationHolder.createWeakWarningAnnotation(psiElement, null);
    inflateLocal.setHighlightType(null);
    inflateLocal.registerFix(new InflateLocalVariableAction(inflateContainer.getPsiLocalVariable(), inflateContainer.getXmlFile()));

    Annotation inflateThis = annotationHolder.createWeakWarningAnnotation(psiElement, null);
    inflateThis.setHighlightType(null);
    inflateThis.registerFix(new InflateThisExpressionAction(inflateContainer.getPsiLocalVariable(), inflateContainer.getXmlFile()));

}
 
Example 4
Source File: HaxeSemanticAnnotator.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
static public void check(final PsiIdentifier identifier, final HaxeAnnotationHolder holder) {
  if (identifier == null) return;
  final String typeName = identifier.getText();
  if (!HaxeClassModel.isValidClassName(typeName)) {
    Annotation annotation = holder.createErrorAnnotation(identifier, "Type name must start by upper case");
    annotation.registerFix(new HaxeFixer("Change name") {
      @Override
      public void run() {
        HaxeDocumentModel.fromElement(identifier).replaceElementText(
          identifier,
          typeName.substring(0, 1).toUpperCase() + typeName.substring(1)
        );
      }
    });
  }
}
 
Example 5
Source File: UnusedParameterOrStateAnnotator.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder annotationHolder) {
  if (element instanceof TemplateBlockMixin) {
    // Abort if values are passed with data="...", parameter are sometimes defined for the sake
    // of added documentation even when not technically used directly in the template body.
    if (element.getText().contains("data=")) {
      return;
    }

    Collection<? extends Variable> variables = Streams
        .concat(ParamUtils.getParamDefinitions(element).stream(),
            ParamUtils.getStateDefinitions(element).stream()).collect(
            ImmutableList.toImmutableList());

    Set<String> usedVariableIdentifiers =
        PsiTreeUtil.findChildrenOfType(element, IdentifierElement.class)
            .stream()
            .map(IdentifierElement::getReferences)
            .flatMap(Arrays::stream)
            .map(PsiReference::getCanonicalText)
            .collect(ImmutableSet.toImmutableSet());

    for (Variable variable : variables) {
      if (!usedVariableIdentifiers.contains(variable.name)) {
        Annotation annotation = annotationHolder
            .createAnnotation(((TemplateBlockMixin) element).isElementBlock() ?
                    HighlightSeverity.WEAK_WARNING : HighlightSeverity.ERROR,
                variable.element.getTextRange(),
                variableType(variable) + " " + variable.name + " is unused.");
        annotation.registerFix(isParameter(variable)
            ? new RemoveUnusedParameterFix(variable.name)
            : new RemoveUnusedStateVarFix(variable.name));
      }
    }
  }
}
 
Example 6
Source File: LoadStatementAnnotator.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void validateImportTarget(@Nullable StringLiteral target) {
  if (target == null) {
    return;
  }
  String targetString = target.getStringContents();
  if (targetString == null
      || targetString.startsWith(":")
      || targetString.startsWith("//")
      || targetString.startsWith("@")
      || targetString.length() < 2) {
    return;
  }
  if (targetString.startsWith("/")) {
    Annotation annotation =
        markWarning(
            target, "Deprecated load syntax; loaded Starlark module should by in label format.");
    InspectionManager inspectionManager = InspectionManager.getInstance(target.getProject());
    ProblemDescriptor descriptor =
        inspectionManager.createProblemDescriptor(
            target,
            annotation.getMessage(),
            DeprecatedLoadQuickFix.INSTANCE,
            ProblemHighlightType.LIKE_DEPRECATED,
            true);
    annotation.registerFix(DeprecatedLoadQuickFix.INSTANCE, null, null, descriptor);
    return;
  }
  markError(target, "Invalid load syntax: missing Starlark module.");
}
 
Example 7
Source File: ESLintExternalAnnotator.java    From eslint-plugin with MIT License 5 votes vote down vote up
@Override
public void apply(@NotNull PsiFile file, ExternalLintAnnotationResult<Result> annotationResult, @NotNull AnnotationHolder holder) {
    if (annotationResult == null) {
        return;
    }
    InspectionProjectProfileManager inspectionProjectProfileManager = InspectionProjectProfileManager.getInstance(file.getProject());
    SeverityRegistrar severityRegistrar = inspectionProjectProfileManager.getSeverityRegistrar();
    HighlightDisplayKey inspectionKey = getHighlightDisplayKeyByClass();
    EditorColorsScheme colorsScheme = annotationResult.input.colorsScheme;

    Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
    if (document == null) {
        return;
    }
    ESLintProjectComponent component = annotationResult.input.project.getComponent(ESLintProjectComponent.class);
    for (VerifyMessage warn : annotationResult.result.warns) {
        HighlightSeverity severity = getHighlightSeverity(warn, component.treatAsWarnings);
        TextAttributes forcedTextAttributes = JSLinterUtil.getTextAttributes(colorsScheme, severityRegistrar, severity);
        Annotation annotation = createAnnotation(holder, file, document, warn, severity, forcedTextAttributes, false);
        if (annotation != null) {
            int offset = StringUtil.lineColToOffset(document.getText(), warn.line - 1, warn.column);
            PsiElement lit = PsiUtil.getElementAtOffset(file, offset);
            BaseActionFix actionFix = Fixes.getFixForRule(warn.ruleId, lit);
            if (actionFix != null) {
                annotation.registerFix(actionFix, null, inspectionKey);
            }
            annotation.registerFix(new SuppressActionFix(warn.ruleId, lit), null, inspectionKey);
            annotation.registerFix(new SuppressLineActionFix(warn.ruleId, lit), null, inspectionKey);
        }
    }
}
 
Example 8
Source File: HaxeExpressionEvaluatorContext.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
public Annotation addError(PsiElement element, String error, HaxeFixer... fixers) {
  if (holder == null) return createDummyAnnotation();
  Annotation annotation = holder.createErrorAnnotation(element, error);
  for (HaxeFixer fixer : fixers) {
    annotation.registerFix(fixer);
  }
  return annotation;
}
 
Example 9
Source File: HaxeExpressionEvaluatorContext.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
public Annotation addWarning(PsiElement element, String error, HaxeFixer... fixers) {
  if (holder == null) return createDummyAnnotation();
  Annotation annotation = holder.createWarningAnnotation(element, error);
  for (HaxeFixer fixer : fixers) {
    annotation.registerFix(fixer);
  }
  return annotation;
}
 
Example 10
Source File: HaxeAnnotation.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public Annotation toAnnotation() {
  String tooltip = this.tooltip;
  if (null == tooltip && null != message && !message.isEmpty()) {
    tooltip = XmlStringUtil.wrapInHtml(XmlStringUtil.escapeString(message));
  }
  Annotation anno = new Annotation(range.getStartOffset(), range.getEndOffset(), severity, message, tooltip);

  for (IntentionAction action : intentions) {
    anno.registerFix(action);
  }
  return anno;
}
 
Example 11
Source File: HaxeColorAnnotator.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private static void annotateCompilationExpression(PsiElement node, AnnotationHolder holder) {
  final Set<String> definitions = HaxeProjectSettings.getInstance(node.getProject()).getUserCompilerDefinitionsAsSet();
  final String nodeText = node.getText();
  for (Pair<String, Integer> pair : HaxeStringUtil.getWordsWithOffset(nodeText)) {
    final String word = pair.getFirst();
    final int offset = pair.getSecond();
    final int absoluteOffset = node.getTextOffset() + offset;
    final TextRange range = new TextRange(absoluteOffset, absoluteOffset + word.length());
    final Annotation annotation = holder.createInfoAnnotation(range, null);
    final String attributeName = definitions.contains(word) ? HaxeSyntaxHighlighterColors.HAXE_DEFINED_VAR
                                                            : HaxeSyntaxHighlighterColors.HAXE_UNDEFINED_VAR;
    annotation.setTextAttributes(TextAttributesKey.find(attributeName));
    annotation.registerFix(new HaxeDefineIntention(word, definitions.contains(word)), range);
  }
}
 
Example 12
Source File: HaxeSemanticAnnotator.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public static void check(
  final HaxeTypeCheckExpr expr,
  final HaxeAnnotationHolder holder
) {
  final PsiElement[] children = expr.getChildren();
  if (children.length == 2) {
    final HaxeGenericResolver resolver = HaxeGenericResolverUtil.generateResolverFromScopeParents(expr);
    final ResultHolder statementResult = HaxeTypeResolver.getPsiElementType(children[0], expr, resolver);
    ResultHolder assertionResult = SpecificTypeReference.getUnknown(expr).createHolder();
    if (children[1] instanceof HaxeTypeOrAnonymous) {
      assertionResult = HaxeTypeResolver.getTypeFromTypeOrAnonymous((HaxeTypeOrAnonymous)children[1]);
      ResultHolder resolveResult = resolver.resolve(assertionResult.getType().toStringWithoutConstant());
      if (null != resolveResult) {
        assertionResult = resolveResult;
      }
    }
    if (!assertionResult.canAssign(statementResult)) {
      final HaxeDocumentModel document = HaxeDocumentModel.fromElement(expr);
      Annotation annotation = holder.createErrorAnnotation(children[0],
                                                           HaxeBundle.message("haxe.semantic.statement.does.not.unify.with.asserted.type",
                                                                              statementResult.getType().toStringWithoutConstant(),
                                                                              assertionResult.getType().toStringWithoutConstant()));
      annotation.registerFix(new HaxeFixer(HaxeBundle.message("haxe.quickfix.remove.type.check")) {
        @Override
        public void run() {
          document.replaceElementText(expr, children[0].getText());
        }
      });
      annotation.registerFix(new HaxeFixer(HaxeBundle.message("haxe.quickfix.change.type.check.to.0", statementResult.toStringWithoutConstant())) {
        @Override
        public void run( ) {
          document.replaceElementText(children[1], statementResult.toStringWithoutConstant());
        }
      });
      // TODO: Add type conversion fixers. (eg. Wrap with Std.int(), wrap with Std.toString())
    }
  }
}
 
Example 13
Source File: WebReferencesAnnotatorBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(@Nonnull PsiFile file, MyInfo[] infos, @Nonnull AnnotationHolder holder) {
  if (infos.length == 0) {
    return;
  }

  final HighlightDisplayLevel displayLevel = getHighlightDisplayLevel(file);

  for (MyInfo info : infos) {
    if (!info.myResult) {
      final PsiElement element = info.myAnchor.retrieve();
      if (element != null) {
        final int start = element.getTextRange().getStartOffset();
        final TextRange range = new TextRange(start + info.myRangeInElement.getStartOffset(), start + info.myRangeInElement.getEndOffset());
        final String message = getErrorMessage(info.myUrl);

        final Annotation annotation;

        if (displayLevel == HighlightDisplayLevel.ERROR) {
          annotation = holder.createErrorAnnotation(range, message);
        }
        else if (displayLevel == HighlightDisplayLevel.WARNING) {
          annotation = holder.createWarningAnnotation(range, message);
        }
        else if (displayLevel == HighlightDisplayLevel.WEAK_WARNING) {
          annotation = holder.createInfoAnnotation(range, message);
        }
        else {
          annotation = holder.createWarningAnnotation(range, message);
        }

        for (IntentionAction action : getQuickFixes()) {
          annotation.registerFix(action);
        }
      }
    }
  }
}
 
Example 14
Source File: HLint.java    From intellij-haskforce with Apache License 2.0 4 votes vote down vote up
protected void createAnnotation(@NotNull HaskellAnnotationHolder holder, int start, int end, @NotNull String message) {
    Annotation ann = holder.createWarningAnnotation(TextRange.create(start, end), message);
    if (ann != null) ann.registerFix(new IgnoreHLint(hint));
}
 
Example 15
Source File: LatteAnnotator.java    From intellij-latte with MIT License 4 votes vote down vote up
private void checkMacroClassic(@NotNull LatteMacroClassic element, @NotNull AnnotationHolder holder) {
	LatteMacroTag openTag = element.getOpenTag();
	LatteMacroTag closeTag = element.getCloseTag();

	String openTagName = openTag.getMacroName();
	LatteTagSettings macro = LatteConfiguration.getInstance(element.getProject()).getTag(openTagName);
	if (macro == null || macro.getType() == LatteTagSettings.Type.ATTR_ONLY) {
		boolean isOk = false;
		LatteMacroContent content = openTag.getMacroContent();
		if (content != null) {
			LattePhpContent phpContent = content.getFirstPhpContent();
			if (phpContent != null && phpContent.getFirstChild() instanceof LattePhpVariable) {
				isOk = true;
			}
		}

		if (!isOk) {
			if (macro != null) {
				holder.createErrorAnnotation(openTag, "Can not use n:" + openTagName + " attribute as normal tag");
				if (closeTag != null) {
					holder.createErrorAnnotation(closeTag, "Tag n:" + openTagName + " can not be used as pair tag");
				}

			} else {
				Annotation annotation = holder.createErrorAnnotation(openTag, "Unknown tag {" + openTagName + "}");
				annotation.registerFix(new AddCustomPairMacro(openTagName));
				annotation.registerFix(new AddCustomUnpairedMacro(openTagName));
			}
		}
	}

	String closeTagName = closeTag != null ? closeTag.getMacroName() : null;
	if (closeTagName != null && !closeTagName.isEmpty() && !closeTagName.equals(openTagName)) {
		holder.createErrorAnnotation(closeTag, "Unexpected {/" + closeTagName + "}, expected {/" + openTagName + "}");
	}

	if (
			macro != null
			&& closeTag == null
			&& ((element instanceof LattePairMacro && macro.getType() == LatteTagSettings.Type.AUTO_EMPTY) || macro.getType() == LatteTagSettings.Type.PAIR)
	) {
		holder.createErrorAnnotation(openTag, "Unclosed tag " + openTagName);
	}
}
 
Example 16
Source File: HaxeSemanticAnnotator.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
private static void checkProperty(final HaxeFieldModel field, final HaxeAnnotationHolder holder) {
  final HaxeDocumentModel document = field.getDocument();

  if (field.getGetterPsi() != null && !field.getGetterType().isValidGetter()) {
    holder.createErrorAnnotation(field.getGetterPsi(), "Invalid getter accessor");
  }

  if (field.getSetterPsi() != null && !field.getSetterType().isValidSetter()) {
    holder.createErrorAnnotation(field.getSetterPsi(), "Invalid setter accessor");
  }

  if (field.isFinal()) {
    holder
      .createErrorAnnotation(field.getBasePsi(), HaxeBundle.message("haxe.semantic.property.cant.be.final"))
      .registerFix(new HaxeSwitchMutabilityModifier((HaxeFieldDeclaration)field.getBasePsi()));
  } else if (field.isProperty() && !field.isRealVar() && field.hasInitializer()) {
    final HaxeVarInit psi = field.getInitializerPsi();
    Annotation annotation = holder.createErrorAnnotation(
      field.getInitializerPsi(),
      "This field cannot be initialized because it is not a real variable"
    );
    annotation.registerFix(new HaxeFixer("Remove init") {
      @Override
      public void run() {
        document.replaceElementText(psi, "", StripSpaces.BEFORE);
      }
    });
    annotation.registerFix(new HaxeFixer("Add @:isVar") {
      @Override
      public void run() {
        field.getModifiers().addModifier(IS_VAR);
      }
    });
    if (field.getSetterPsi() != null) {
      annotation.registerFix(new HaxeFixer("Make setter null") {
        @Override
        public void run() {
          document.replaceElementText(field.getSetterPsi(), "null");
        }
      });
    }
  }
  checkPropertyAccessorMethods(field, holder);
}