Search in sources :

Example 1 with AnnotationHolder

use of com.intellij.lang.annotation.AnnotationHolder in project intellij-community by JetBrains.

the class GlobalAnnotator method visitPyGlobalStatement.

@Override
public void visitPyGlobalStatement(final PyGlobalStatement node) {
    PyFunction function = PsiTreeUtil.getParentOfType(node, PyFunction.class);
    if (function != null) {
        PyParameterList paramList = function.getParameterList();
        // collect param names
        final Set<String> paramNames = new HashSet<>();
        ParamHelper.walkDownParamArray(paramList.getParameters(), new ParamHelper.ParamVisitor() {

            @Override
            public void visitNamedParameter(PyNamedParameter param, boolean first, boolean last) {
                paramNames.add(param.getName());
            }
        });
        // check globals
        final AnnotationHolder holder = getHolder();
        for (PyTargetExpression expr : node.getGlobals()) {
            final String expr_name = expr.getReferencedName();
            if (paramNames.contains(expr_name)) {
                holder.createErrorAnnotation(expr.getTextRange(), PyBundle.message("ANN.$0.both.global.and.param", expr_name));
            }
        }
    }
}
Also used : AnnotationHolder(com.intellij.lang.annotation.AnnotationHolder) ParamHelper(com.jetbrains.python.psi.impl.ParamHelper) HashSet(java.util.HashSet)

Example 2 with AnnotationHolder

use of com.intellij.lang.annotation.AnnotationHolder in project intellij-community by JetBrains.

the class GroovyAnnotator method checkThisOrSuperReferenceExpression.

private static void checkThisOrSuperReferenceExpression(final GrReferenceExpression ref, AnnotationHolder holder) {
    PsiElement nameElement = ref.getReferenceNameElement();
    if (nameElement == null)
        return;
    IElementType elementType = nameElement.getNode().getElementType();
    if (!(elementType == GroovyTokenTypes.kSUPER || elementType == GroovyTokenTypes.kTHIS))
        return;
    final GrExpression qualifier = ref.getQualifier();
    if (qualifier instanceof GrReferenceExpression) {
        final PsiElement resolved = ((GrReferenceExpression) qualifier).resolve();
        if (resolved instanceof PsiClass) {
            GrTypeDefinition containingClass = PsiTreeUtil.getParentOfType(ref, GrTypeDefinition.class, true, GroovyFile.class);
            if (elementType == GroovyTokenTypes.kSUPER && containingClass != null && GrTraitUtil.isTrait((PsiClass) resolved)) {
                PsiClassType[] superTypes = containingClass.getSuperTypes();
                if (ContainerUtil.find(superTypes, type -> ref.getManager().areElementsEquivalent(type.resolve(), resolved)) != null) {
                    holder.createInfoAnnotation(nameElement, null).setTextAttributes(GroovySyntaxHighlighter.KEYWORD);
                    // reference to trait method
                    return;
                }
            }
            if (containingClass == null || containingClass.getContainingClass() == null && !containingClass.isAnonymous()) {
                holder.createErrorAnnotation(ref, GroovyBundle.message("qualified.0.is.allowed.only.in.nested.or.inner.classes", nameElement.getText()));
                return;
            }
            if (PsiTreeUtil.isAncestor(resolved, ref, true)) {
                if (PsiUtil.hasEnclosingInstanceInScope((PsiClass) resolved, ref, true)) {
                    holder.createInfoAnnotation(nameElement, null).setTextAttributes(GroovySyntaxHighlighter.KEYWORD);
                }
            } else {
                String qname = ((PsiClass) resolved).getQualifiedName();
                assert qname != null;
                holder.createErrorAnnotation(ref, GroovyBundle.message("is.not.enclosing.class", qname));
            }
        }
    } else if (qualifier == null) {
        if (elementType == GroovyTokenTypes.kSUPER) {
            final GrMember container = PsiTreeUtil.getParentOfType(ref, GrMethod.class, GrClassInitializer.class);
            if (container != null && container.hasModifierProperty(PsiModifier.STATIC)) {
                holder.createErrorAnnotation(ref, GroovyBundle.message("super.cannot.be.used.in.static.context"));
            }
        }
    }
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) GrModifierList(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList) LiteralConstructorReference(org.jetbrains.plugins.groovy.findUsages.LiteralConstructorReference) org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals) IElementType(com.intellij.psi.tree.IElementType) PsiImplUtil(org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) Document(com.intellij.openapi.editor.Document) HashSet(com.intellij.util.containers.HashSet) THashSet(gnu.trove.THashSet) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) ResolveUtil(org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil) org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef) AnnotationHolder(com.intellij.lang.annotation.AnnotationHolder) CustomAnnotationChecker(org.jetbrains.plugins.groovy.annotator.checkers.CustomAnnotationChecker) org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation) GrArgumentLabel(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel) GrContinueStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrContinueStatement) org.jetbrains.plugins.groovy.lang.psi(org.jetbrains.plugins.groovy.lang.psi) GrIndexProperty(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty) TokenSets(org.jetbrains.plugins.groovy.lang.lexer.TokenSets) SuperMethodsSearch(com.intellij.psi.search.searches.SuperMethodsSearch) org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members) GrModifierFix(org.jetbrains.plugins.groovy.codeInspection.bugs.GrModifierFix) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) MultiMap(com.intellij.util.containers.MultiMap) GroovyTokenTypes(org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GroovyConfigUtils(org.jetbrains.plugins.groovy.config.GroovyConfigUtils) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) ModuleUtilCore(com.intellij.openapi.module.ModuleUtilCore) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GrModifier(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) VisibilityUtil(com.intellij.util.VisibilityUtil) TextRange(com.intellij.openapi.util.TextRange) GroovyBundle(org.jetbrains.plugins.groovy.GroovyBundle) GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) Nullable(org.jetbrains.annotations.Nullable) org.jetbrains.plugins.groovy.lang.psi.api.statements(org.jetbrains.plugins.groovy.lang.psi.api.statements) OverrideImplementExploreUtil(com.intellij.codeInsight.generation.OverrideImplementExploreUtil) org.jetbrains.plugins.groovy.lang.psi.util(org.jetbrains.plugins.groovy.lang.psi.util) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) Annotation(com.intellij.lang.annotation.Annotation) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) PsiUtil(org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil) org.jetbrains.plugins.groovy.lang.psi.api.types(org.jetbrains.plugins.groovy.lang.psi.api.types) java.util(java.util) org.jetbrains.plugins.groovy.annotator.intentions(org.jetbrains.plugins.groovy.annotator.intentions) GrFlowInterruptingStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrFlowInterruptingStatement) GrPackageDefinition(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition) GroovyLanguage(org.jetbrains.plugins.groovy.GroovyLanguage) GroovyPresentationUtil(org.jetbrains.plugins.groovy.lang.documentation.GroovyPresentationUtil) GrStatementOwner(org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner) ContainerUtil(com.intellij.util.containers.ContainerUtil) HighlightClassUtil(com.intellij.codeInsight.daemon.impl.analysis.HighlightClassUtil) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock) GrReturnStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement) GrListOrMap(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap) TypeInferenceHelper(org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper) InheritConstructorContributor(org.jetbrains.plugins.groovy.lang.resolve.ast.InheritConstructorContributor) UtilKt(org.jetbrains.plugins.groovy.annotator.UtilKt) GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass) GroovySyntaxHighlighter(org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter) StringUtil(com.intellij.openapi.util.text.StringUtil) com.intellij.psi.util(com.intellij.psi.util) QuickFixFactory(com.intellij.codeInsight.intention.QuickFixFactory) AnnotationChecker(org.jetbrains.plugins.groovy.annotator.checkers.AnnotationChecker) GrDocComment(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment) GrBreakStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrBreakStatement) TypesUtil(org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) ASTNode(com.intellij.lang.ASTNode) ExpressionConverter(com.intellij.psi.impl.ExpressionConverter) GrAnnotationCollector(org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.GrAnnotationCollector) ClassUtil(com.intellij.codeInsight.ClassUtil) org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions) ObjectUtils(com.intellij.util.ObjectUtils) GrForInClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause) Condition(com.intellij.openapi.util.Condition) GrDocReferenceElement(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocReferenceElement) IElementType(com.intellij.psi.tree.IElementType)

Example 3 with AnnotationHolder

use of com.intellij.lang.annotation.AnnotationHolder in project android by JetBrains.

the class AndroidColorAnnotatorTest method findAnnotation.

@NotNull
private Annotation findAnnotation(VirtualFile virtualFile, String target, Class<? extends PsiElement> elementClass) {
    PsiFile file = PsiManager.getInstance(getProject()).findFile(virtualFile);
    assertThat(file).isNotNull();
    int caretOffset = target.indexOf('|');
    if (caretOffset != -1) {
        target = target.substring(0, caretOffset) + target.substring(caretOffset + 1);
    } else {
        caretOffset = 0;
    }
    String source = file.getText();
    int dot = source.indexOf(target);
    assertThat(dot).isNotEqualTo(-1);
    dot += caretOffset;
    PsiElement element = PsiTreeUtil.findElementOfClassAtOffset(file, dot, elementClass, false);
    assertThat(element).isNotNull();
    final List<Annotation> annotations = Lists.newArrayList();
    AnnotationHolder holder = Mockito.mock(AnnotationHolder.class);
    Mockito.when(holder.createInfoAnnotation(Matchers.any(PsiElement.class), Matchers.anyString())).thenAnswer(invocation -> {
        PsiElement e = (PsiElement) invocation.getArguments()[0];
        String message = (String) invocation.getArguments()[1];
        Annotation annotation = new Annotation(e.getTextRange().getStartOffset(), e.getTextRange().getEndOffset(), HighlightSeverity.INFORMATION, message, null);
        annotations.add(annotation);
        return annotation;
    });
    AndroidColorAnnotator annotator = new AndroidColorAnnotator();
    annotator.annotate(element, holder);
    Mockito.reset(holder);
    assertThat(annotations).isNotEmpty();
    return annotations.get(0);
}
Also used : AnnotationHolder(com.intellij.lang.annotation.AnnotationHolder) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) Annotation(com.intellij.lang.annotation.Annotation) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with AnnotationHolder

use of com.intellij.lang.annotation.AnnotationHolder in project intellij-community by JetBrains.

the class DaemonRespondToChangesTest method testHighlightingDoesWaitForEmbarrassinglySlowExternalAnnotatorsToFinish.

public void testHighlightingDoesWaitForEmbarrassinglySlowExternalAnnotatorsToFinish() throws Exception {
    configureByText(JavaFileType.INSTANCE, "class X { int f() { int gg<caret> = 11; return 0;} }");
    final AtomicBoolean run = new AtomicBoolean();
    final int SLEEP = 20000;
    ExternalAnnotator<Integer, Integer> annotator = new ExternalAnnotator<Integer, Integer>() {

        @Nullable
        @Override
        public Integer collectInformation(@NotNull PsiFile file) {
            return 0;
        }

        @Nullable
        @Override
        public Integer doAnnotate(final Integer collectedInfo) {
            TimeoutUtil.sleep(SLEEP);
            return 0;
        }

        @Override
        public void apply(@NotNull final PsiFile file, final Integer annotationResult, @NotNull final AnnotationHolder holder) {
            run.set(true);
        }
    };
    ExternalLanguageAnnotators.INSTANCE.addExplicitExtension(JavaLanguage.INSTANCE, annotator);
    try {
        long start = System.currentTimeMillis();
        List<HighlightInfo> errors = filter(CodeInsightTestFixtureImpl.instantiateAndRun(getFile(), getEditor(), new int[0], false), HighlightSeverity.ERROR);
        long elapsed = System.currentTimeMillis() - start;
        assertEquals(0, errors.size());
        if (!run.get()) {
            fail(ThreadDumper.dumpThreadsToString());
        }
        assertTrue("Elapsed: " + elapsed, elapsed >= SLEEP);
    } finally {
        ExternalLanguageAnnotators.INSTANCE.removeExplicitExtension(JavaLanguage.INSTANCE, annotator);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ExternalAnnotator(com.intellij.lang.annotation.ExternalAnnotator) AnnotationHolder(com.intellij.lang.annotation.AnnotationHolder) NotNull(org.jetbrains.annotations.NotNull) LightweightHint(com.intellij.ui.LightweightHint)

Example 5 with AnnotationHolder

use of com.intellij.lang.annotation.AnnotationHolder in project intellij-community by JetBrains.

the class GroovyPostHighlightingPass method doApplyInformationToEditor.

@Override
public void doApplyInformationToEditor() {
    if (myUnusedDeclarations == null || myUnusedImports == null) {
        return;
    }
    AnnotationHolder annotationHolder = new AnnotationHolderImpl(new AnnotationSession(myFile));
    List<HighlightInfo> infos = new ArrayList<>(myUnusedDeclarations);
    for (GrImportStatement unusedImport : myUnusedImports) {
        Annotation annotation = annotationHolder.createWarningAnnotation(calculateRangeToUse(unusedImport), GroovyInspectionBundle.message("unused.import"));
        annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
        annotation.registerFix(GroovyQuickFixFactory.getInstance().createOptimizeImportsFix(false));
        infos.add(HighlightInfo.fromAnnotation(annotation));
    }
    UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, myFile.getTextLength(), infos, getColorsScheme(), getId());
    if (myUnusedImports != null && !myUnusedImports.isEmpty()) {
        IntentionAction fix = GroovyQuickFixFactory.getInstance().createOptimizeImportsFix(true);
        if (fix.isAvailable(myProject, myEditor, myFile) && myFile.isWritable()) {
            fix.invoke(myProject, myEditor, myFile);
        }
    }
}
Also used : AnnotationSession(com.intellij.lang.annotation.AnnotationSession) AnnotationHolder(com.intellij.lang.annotation.AnnotationHolder) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) Annotation(com.intellij.lang.annotation.Annotation)

Aggregations

AnnotationHolder (com.intellij.lang.annotation.AnnotationHolder)5 Annotation (com.intellij.lang.annotation.Annotation)3 NotNull (org.jetbrains.annotations.NotNull)3 IntentionAction (com.intellij.codeInsight.intention.IntentionAction)2 ClassUtil (com.intellij.codeInsight.ClassUtil)1 HighlightClassUtil (com.intellij.codeInsight.daemon.impl.analysis.HighlightClassUtil)1 OverrideImplementExploreUtil (com.intellij.codeInsight.generation.OverrideImplementExploreUtil)1 QuickFixFactory (com.intellij.codeInsight.intention.QuickFixFactory)1 ASTNode (com.intellij.lang.ASTNode)1 AnnotationSession (com.intellij.lang.annotation.AnnotationSession)1 ExternalAnnotator (com.intellij.lang.annotation.ExternalAnnotator)1 InjectedLanguageManager (com.intellij.lang.injection.InjectedLanguageManager)1 Logger (com.intellij.openapi.diagnostic.Logger)1 Document (com.intellij.openapi.editor.Document)1 Module (com.intellij.openapi.module.Module)1 ModuleUtilCore (com.intellij.openapi.module.ModuleUtilCore)1 IndexNotReadyException (com.intellij.openapi.project.IndexNotReadyException)1 Condition (com.intellij.openapi.util.Condition)1 TextRange (com.intellij.openapi.util.TextRange)1 StringUtil (com.intellij.openapi.util.text.StringUtil)1