Java Code Examples for com.intellij.lang.annotation.AnnotationHolder#createErrorAnnotation()

The following examples show how to use com.intellij.lang.annotation.AnnotationHolder#createErrorAnnotation() . 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: UnaryOperatorTypeAnnotation.java    From glsl4idea with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void annotate(GLSLUnaryOperatorExpression expr, AnnotationHolder holder) {
    final GLSLExpression operand = expr.getOperand();
    final GLSLOperator operator = expr.getOperator();
    if(operand == null || operator == null)return;

    if(!(operator instanceof GLSLOperator.GLSLUnaryOperator)){
        holder.createErrorAnnotation(expr, '\''+operator.getTextRepresentation()+"' is not an unary operator");
        return;
    }

    GLSLOperator.GLSLUnaryOperator unaryOperator = (GLSLOperator.GLSLUnaryOperator) operator;
    final GLSLType operandType = operand.getType();
    if(operandType.isValidType()){
        if(!unaryOperator.isValidInput(operandType)){
            holder.createErrorAnnotation(expr,
                    "'" + operator.getTextRepresentation() + "' does not operate on '" + operandType.getTypename() + "'");
        }
    }
}
 
Example 2
Source File: EelHelperMethodAnnotator.java    From intellij-neos with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
    if (element instanceof FusionMethodCall) {
        FusionMethodCall methodCall = (FusionMethodCall) element;
        if (methodCall.getPrevSibling() != null && methodCall.getPrevSibling().getPrevSibling() instanceof FusionCompositeIdentifier) {
            FusionCompositeIdentifier compositeId = (FusionCompositeIdentifier) methodCall.getPrevSibling().getPrevSibling();
            List<String> helpers = FileBasedIndex.getInstance().getValues(DefaultContextFileIndex.KEY, compositeId.getText(), GlobalSearchScope.allScope(element.getProject()));
            if (!helpers.isEmpty()) {
                for (String helper : helpers) {
                     if (PhpElementsUtil.getClassMethod(element.getProject(), helper, methodCall.getMethodName().getText()) != null) {
                         return;
                     }
                }

                holder.createErrorAnnotation(methodCall, "Unresolved EEL helper method");
            }
        }
    }
}
 
Example 3
Source File: DustAnnotator.java    From Intellij-Dust with MIT License 6 votes vote down vote up
private static boolean checkMatchingCloseTag(DustOpenTag openTag, AnnotationHolder holder) {
  if (openTag == null) return false;

  String openTagName = getTagName(openTag);
  PsiElement sibling = openTag.getNextSibling();
  DustCloseTag closeTag = null;
  while (sibling != null) {
    if (sibling instanceof DustCloseTag) {
      closeTag = (DustCloseTag) sibling;
      if (getTagName(closeTag).equals(openTagName)) {
        return true;
      }
    }
    sibling = sibling.getNextSibling();
  }

  holder.createErrorAnnotation(openTag.getTextRange(), "Could not find matching closing tag " + getTagName(openTag));

  if (closeTag != null) {
    holder.createErrorAnnotation(closeTag.getTextRange(), "Could not find matching opening tag " + getTagName(closeTag));
  }

  return false;
}
 
Example 4
Source File: LSPAnnotator.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
protected Annotation createAnnotation(Editor editor, AnnotationHolder holder, Diagnostic diagnostic) {
    final int start = DocumentUtils.LSPPosToOffset(editor, diagnostic.getRange().getStart());
    final int end = DocumentUtils.LSPPosToOffset(editor, diagnostic.getRange().getEnd());
    if (start >= end) {
        return null;
    }
    final TextRange textRange = new TextRange(start, end);
    switch (diagnostic.getSeverity()) {
        // TODO: Use 'newAnnotation'; 'create*Annotation' methods are deprecated.
        case Error:
            return holder.createErrorAnnotation(textRange, diagnostic.getMessage());
        case Warning:
            return holder.createWarningAnnotation(textRange, diagnostic.getMessage());
        case Information:
            return holder.createInfoAnnotation(textRange, diagnostic.getMessage());
        default:
            return holder.createWeakWarningAnnotation(textRange, diagnostic.getMessage());
    }
}
 
Example 5
Source File: GivenParametersAnnotator.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
private static void checkMissingRequiredParameters(
    @NotNull AnnotationHolder annotationHolder,
    PsiElement identifier,
    Collection<ParameterSpecification> givenParameters,
    List<Parameter> declaredParameters) {

  List<String> requiredParameterNames =
      declaredParameters.stream()
          .filter(var -> !var.isOptional)
          .map(var -> var.name)
          .collect(Collectors.toList());
  List<String> givenParameterNames =
      givenParameters.stream().map(ParameterSpecification::name).collect(Collectors.toList());

  if (!givenParameterNames.containsAll(requiredParameterNames)) {
    requiredParameterNames.removeAll(givenParameterNames);
    annotationHolder.createErrorAnnotation(
        identifier, "Missing required parameters: " + String.join(",", requiredParameterNames));
  }
}
 
Example 6
Source File: ConstModificationAnnotation.java    From glsl4idea with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void annotate(GLSLAssignmentExpression assignment, AnnotationHolder holder) {
    GLSLExpression expr = assignment.getLeftOperand();
    if (expr == null) return;

    PsiReference reference = expr.getReference();
    if (reference == null && expr instanceof GLSLReferenceElement)
        reference = ((GLSLReferenceElement) expr).getReferenceProxy();

    if (reference == null) return;

    PsiElement declarator = reference.resolve();
    if (!(declarator instanceof GLSLDeclarator)) return;

    if (((GLSLDeclarator) declarator).getQualifiedType().hasQualifier(GLSLQualifier.Qualifier.CONST)) {
        holder.createErrorAnnotation(expr, "Cannot assign to const variable");
    }
}
 
Example 7
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 8
Source File: CamelSimpleAnnotator.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Validate simple expression. eg simple("${body}")
 * if the expression is not valid a error annotation is created and highlight the invalid value.
 */
void validateText(@NotNull PsiElement element, @NotNull AnnotationHolder holder, @NotNull String text) {

    // we only want to evaluate if there is a simple function as plain text without functions dont make sense to validate
    boolean hasSimple = text.contains("${") || text.contains("$simple{");
    if (hasSimple && getCamelIdeaUtils().isCamelExpression(element, "simple")) {
        CamelCatalog catalogService = ServiceManager.getService(element.getProject(), CamelCatalogService.class).get();
        CamelService camelService = ServiceManager.getService(element.getProject(), CamelService.class);

        boolean predicate = false;
        try {
            // need to use the classloader that can load classes from the camel-core
            ClassLoader loader = camelService.getCamelCoreClassloader();
            if (loader != null) {
                SimpleValidationResult result;
                predicate = getCamelIdeaUtils().isCamelExpressionUsedAsPredicate(element, "simple");
                if (predicate) {
                    LOG.debug("Validate simple predicate: " + text);
                    result = catalogService.validateSimplePredicate(loader, text);
                } else {
                    LOG.debug("Validate simple expression: " + text);
                    result = catalogService.validateSimpleExpression(loader, text);
                }
                if (!result.isSuccess()) {
                    String error = result.getShortError();
                    TextRange range = element.getTextRange();
                    if (result.getIndex() > 0) {
                        range = getAdjustedTextRange(element, range, text, result);

                    }
                    holder.createErrorAnnotation(range, error);
                }
            }
        } catch (Throwable e) {
            LOG.warn("Error validating Camel simple " + (predicate ? "predicate" : "expression") + ": " + text, e);
        }
    }
}
 
Example 9
Source File: IncompleteBlockAnnotator.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) {
  if (psiElement instanceof TagBlockElement) {
    TagBlockElement block = (TagBlockElement) psiElement;
    if (block.isIncomplete() && !(block instanceof ChoiceClauseElement)) {
      annotationHolder.createErrorAnnotation(block.getOpeningTag(),
          "{" + block.getTagName() + "} is not closed.");
    }
  }
}
 
Example 10
Source File: MisplacedCommentHighlighter.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
public void highlight(PsiElement element, AnnotationHolder holder) {
    XQueryMisplacedComment misplacedComment = PsiTreeUtil.getTopmostParentOfType(element, XQueryMisplacedComment.class);
    if (isTheStartingElementOfMisplacedComment(element, misplacedComment)) {
        Annotation annotation = holder.createErrorAnnotation(misplacedComment, "Comments cannot be used here.");
        annotation.setHighlightType(ProblemHighlightType.GENERIC_ERROR);
    }
}
 
Example 11
Source File: GivenParametersAnnotator.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
private static void checkDuplicateParameters(
    @NotNull AnnotationHolder annotationHolder,
    Collection<ParameterSpecification> givenParameters) {
  Set<String> seenNames = new HashSet<>();
  for (ParameterSpecification givenParameter : givenParameters) {
    if (!seenNames.add(givenParameter.name())) {
      annotationHolder.createErrorAnnotation(
          givenParameter.identifier(), "Duplicate parameter specified");
    }
  }
}
 
Example 12
Source File: StatementParentAnnotation.java    From glsl4idea with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void annotate(GLSLStatement expr, AnnotationHolder holder) {
    AcceptableParents acceptableParents = parentsForClass.get(expr.getClass());
    if (acceptableParents == null) return;
    PsiElement parent = expr.findParentByClasses(acceptableParents.parents);
    if (parent == null) { // we needed a parent and we couldn't find one - this is a compile-time error
        holder.createErrorAnnotation(expr, acceptableParents.message);
    }
}
 
Example 13
Source File: ClosingBraceSanityAnnotator.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) {
  if (psiElement instanceof TagElement) {
    TagElement tagElement = (TagElement) psiElement;

    TokenSet allowedRBraces = SoyTokenTypes.RIGHT_BRACES;
    if (mustCloseRBraceTags.contains(tagElement.getClass())) {
      allowedRBraces = TokenSet.andNot(allowedRBraces, SoyTokenTypes.SLASH_R_BRACES);
    } else if (mustCloseSlashRBraceTags.contains(tagElement.getClass())) {
      allowedRBraces = TokenSet.andSet(allowedRBraces, SoyTokenTypes.SLASH_R_BRACES);
    }

    if (tagElement.isDoubleBraced()) {
      allowedRBraces = TokenSet.andSet(allowedRBraces, SoyTokenTypes.DOUBLE_BRACES);
    } else {
      allowedRBraces = TokenSet.andNot(allowedRBraces, SoyTokenTypes.DOUBLE_BRACES);
    }

    if (!allowedRBraces.contains(tagElement.getClosingBraceType())) {
      annotationHolder.createErrorAnnotation(tagElement, "Must close by " +
          Stream.of(allowedRBraces.getTypes())
              .map(SoyTokenTypes.BRACE_TYPE_TO_STRING::get)
              .sorted()
              .collect(Collectors.joining(" or ")));
    }
  }
}
 
Example 14
Source File: ConditionCheckAnnotation.java    From glsl4idea with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void annotate(GLSLStatement expr, AnnotationHolder holder) {
    if (expr instanceof ConditionStatement) {
        ConditionStatement conditionStatement = (ConditionStatement) expr;
        GLSLCondition condition = conditionStatement.getCondition();

        if (condition != null) {
            GLSLType conditionExpressionType = condition.getType();
            if(!conditionExpressionType.isValidType())return;
            if(conditionExpressionType != GLSLTypes.BOOL){
                holder.createErrorAnnotation(condition, "Condition must be a boolean expression.");
            }
        }
    }
}
 
Example 15
Source File: JSGraphQLEndpointDocHighlightAnnotator.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {

	final IElementType elementType = element.getNode().getElementType();

       // highlight TO-DO items
       if(elementType == JSGraphQLEndpointDocTokenTypes.DOCTEXT) {
		final String elementText = element.getText().toLowerCase();
		if(isTodoToken(elementText)) {
			setTextAttributes(element, holder, CodeInsightColors.TODO_DEFAULT_ATTRIBUTES);
               holder.getCurrentAnnotationSession().putUserData(TODO_ELEMENT, element);
			return;
		} else {
               PsiElement prevSibling = element.getPrevSibling();
               while (prevSibling != null) {
                   if(prevSibling == holder.getCurrentAnnotationSession().getUserData(TODO_ELEMENT)) {
                       setTextAttributes(element, holder, CodeInsightColors.TODO_DEFAULT_ATTRIBUTES);
                       return;
                   }
                   prevSibling = prevSibling.getPrevSibling();
               }
           }
	}

	final PsiComment comment = PsiTreeUtil.getContextOfType(element, PsiComment.class);
	if (comment != null && JSGraphQLEndpointDocPsiUtil.isDocumentationComment(comment)) {
		final TextAttributesKey textAttributesKey = ATTRIBUTES.get(elementType);
		if (textAttributesKey != null) {
			setTextAttributes(element, holder, textAttributesKey);
		}
		// highlight invalid argument names after @param
		if(elementType == JSGraphQLEndpointDocTokenTypes.DOCVALUE) {
			final JSGraphQLEndpointFieldDefinition field = PsiTreeUtil.getNextSiblingOfType(comment, JSGraphQLEndpointFieldDefinition.class);
			if(field != null) {
				final JSGraphQLEndpointDocTag tag = PsiTreeUtil.getParentOfType(element, JSGraphQLEndpointDocTag.class);
				if(tag != null && tag.getDocName().getText().equals("@param")) {
					final String paramName = element.getText();
					final JSGraphQLEndpointInputValueDefinitions arguments = PsiTreeUtil.findChildOfType(field, JSGraphQLEndpointInputValueDefinitions.class);
					if(arguments == null) {
						// no arguments so invalid use of @param
						holder.createErrorAnnotation(element, "Invalid use of @param. The property has no arguments");
					} else {
						final JSGraphQLEndpointInputValueDefinition[] inputValues = PsiTreeUtil.getChildrenOfType(arguments, JSGraphQLEndpointInputValueDefinition.class);
						boolean found = false;
						if(inputValues != null) {
							for (JSGraphQLEndpointInputValueDefinition inputValue: inputValues) {
								if(inputValue.getInputValueDefinitionIdentifier().getText().equals(paramName)) {
									found = true;
									break;
								}
							}
						}
						if(!found) {
							holder.createErrorAnnotation(element, "@param name '" + element.getText() + "' doesn't match any of the field arguments");
						}

					}
				}
			}
		}
	}
}
 
Example 16
Source File: AnnotationHolderModifier.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
public void modifyHolder(AnnotationHolder holder, XQueryFunctionName functionName, XQueryFile file) {
    XQueryFunctionDecl functionDeclaration = (XQueryFunctionDecl) functionName.getParent();
    TextRange textRange = textRangeCalculator.calculateTextRange(functionDeclaration);
    String description = descriptionProducer.createDescription(functionName, file);
    holder.createErrorAnnotation(textRange, description);
}
 
Example 17
Source File: CamelBeanMethodAnnotator.java    From camel-idea-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
    if (!isEnabled(element)) {
        return;
    }

    PsiClass psiClass = getCamelIdeaUtils().getBean(element);

    if (psiClass == null) {
        return;
    }

    String errorMessage;
    final String beanName = getJavaClassUtils().getBeanName(psiClass);
    final String methodNameWithParameters = StringUtils.stripDoubleQuotes(element.getText());
    final String methodName = StringUtils.stripDoubleQuotes(getJavaMethodUtils().getMethodNameWithOutParameters(element));

    if (methodName.equals(beanName)) {
        //We don't want to check psiClass elements it self
        return;
    }

    final List<PsiMethod> matchMethods = getMatchingMethods(psiClass, methodName);

    if (matchMethods.isEmpty()) {
        errorMessage = matchMethods.isEmpty() ? String.format(METHOD_CAN_NOT_RESOLVED, methodNameWithParameters, psiClass.getQualifiedName()) : null;
    } else {
        final long privateMethods = matchMethods.stream()
            .filter(method -> getJavaMethodUtils().isMatchOneOfModifierType(method, PsiModifier.PRIVATE))
            .count();

        final boolean isAnnotatedWithHandler = matchMethods.stream().anyMatch(psiMethod -> getCamelIdeaUtils().isAnnotatedWithHandler(psiMethod));

        final boolean allPrivates = privateMethods == matchMethods.size() ? true : false;

        if (methodNameWithParameters.indexOf("(", methodName.length()) > 0 && methodNameWithParameters.endsWith(")") && !allPrivates) {
            //TODO implement logic for matching on parameters.
            return;
        }

        if ((matchMethods.size() - privateMethods) > 1 && (!isAnnotatedWithHandler)) {
            errorMessage = String.format(METHOD_HAS_AMBIGUOUS_ACCESS, methodNameWithParameters, psiClass.getQualifiedName());
        } else {
            errorMessage = allPrivates ? String.format(METHOD_HAS_PRIVATE_ACCESS, methodNameWithParameters, psiClass.getQualifiedName()) : null;
        }

    }

    if (errorMessage != null) {
        holder.createErrorAnnotation(element, errorMessage);
    }

}
 
Example 18
Source File: SwitchAnnotation.java    From glsl4idea with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void annotate(GLSLSwitchStatement expr, AnnotationHolder holder) {
    final GLSLExpression switchCondition = expr.getSwitchCondition();
    if (switchCondition == null) return;

    final GLSLType switchConditionType = switchCondition.getType();
    if (!switchConditionType.isValidType()) return;

    if (!GLSLScalarType.isIntegerScalar(switchConditionType)) {
        holder.createErrorAnnotation(switchCondition, "Expression must be of integer scalar type");
    } else if (switchCondition.isConstantValue()) {
        holder.createWeakWarningAnnotation(switchCondition, "Expression is constant");
    }

    final List<GLSLLabelStatement> labelStatements = expr.getLabelStatements();


    Set<Object> encounteredCases = new HashSet<>();
    boolean defaultFound = false;

    for (GLSLLabelStatement label : labelStatements) {
        if (label instanceof GLSLDefaultStatement) {
            if (defaultFound) {
                holder.createErrorAnnotation(label, "Multiple default labels are not allowed");
            }
            defaultFound = true;
        } else if (label instanceof GLSLCaseStatement) {//This _should_ be the only possible way
            final GLSLCaseStatement caseLabel = (GLSLCaseStatement) label;
            final GLSLExpression caseExpression = caseLabel.getCaseExpression();
            if (caseExpression != null) {
                final GLSLType caseExpressionType = caseExpression.getType();
                if (caseExpressionType.isValidType()) {
                    if (!GLSLScalarType.isIntegerScalar(caseExpressionType)) {
                        holder.createErrorAnnotation(caseExpression, "Case expression must be of integer scalar type");
                    } else {
                        //It is a valid type, do dupe check
                        if (caseExpression.isConstantValue()) {
                            Object constantValue = caseExpression.getConstantValue();
                            //constantValue should be Long, but don't dwell on that
                            if (encounteredCases.contains(constantValue)) {
                                holder.createWarningAnnotation(caseExpression, "Duplicate case label (" + constantValue + ")");
                            }
                            encounteredCases.add(constantValue);
                        }
                    }
                }
            }
        }
    }
}
 
Example 19
Source File: InitializerListEmptyAnnotation.java    From glsl4idea with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void annotate(GLSLInitializerList expr, AnnotationHolder holder) {
    if (expr.getInitializers().length == 0) {
        holder.createErrorAnnotation(expr, "Empty initializer lists are not allowed");
    }
}
 
Example 20
Source File: ReservedKeywordAnnotation.java    From glsl4idea with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void annotate(PsiElement element, AnnotationHolder holder) {
    if (element.getNode().getElementType() == GLSLTokenTypes.RESERVED_KEYWORD) {
        holder.createErrorAnnotation(element, "Reserved keyword");
    }
}