Search in sources :

Example 31 with AnnotationTree

use of com.sun.source.tree.AnnotationTree in project palantir-java-format by palantir.

the class JavaInputAstVisitor method visitModule.

@Override
public Void visitModule(ModuleTree node, Void unused) {
    for (AnnotationTree annotation : node.getAnnotations()) {
        scan(annotation, null);
        builder.forcedBreak();
    }
    if (node.getModuleType() == ModuleTree.ModuleKind.OPEN) {
        token("open");
        builder.space();
    }
    token("module");
    builder.space();
    scan(node.getName(), null);
    builder.space();
    if (node.getDirectives().isEmpty()) {
        tokenBreakTrailingComment("{", plusTwo);
        builder.blankLineWanted(BlankLineWanted.NO);
        token("}", plusTwo);
    } else {
        builder.open(plusTwo);
        token("{");
        builder.forcedBreak();
        Optional<Tree.Kind> previousDirective = Optional.empty();
        for (DirectiveTree directiveTree : node.getDirectives()) {
            markForPartialFormat();
            builder.blankLineWanted(previousDirective.map(k -> !k.equals(directiveTree.getKind())).orElse(false) ? BlankLineWanted.YES : BlankLineWanted.NO);
            builder.forcedBreak();
            scan(directiveTree, null);
            previousDirective = Optional.of(directiveTree.getKind());
        }
        builder.close();
        builder.forcedBreak();
        token("}");
    }
    return null;
}
Also used : CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) Trees.getEndPosition(com.palantir.javaformat.java.Trees.getEndPosition) LiteralTree(com.sun.source.tree.LiteralTree) VARIABLE(com.sun.source.tree.Tree.Kind.VARIABLE) ExportsTree(com.sun.source.tree.ExportsTree) TreeScanner(com.sun.tools.javac.tree.TreeScanner) PeekingIterator(com.google.common.collect.PeekingIterator) ImmutableRangeMap(com.google.common.collect.ImmutableRangeMap) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) ARRAY_ACCESS(com.sun.source.tree.Tree.Kind.ARRAY_ACCESS) AssignmentTree(com.sun.source.tree.AssignmentTree) TypeCastTree(com.sun.source.tree.TypeCastTree) Trees.getMethodName(com.palantir.javaformat.java.Trees.getMethodName) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) SortedDims(com.palantir.javaformat.java.DimensionHelpers.SortedDims) Map(java.util.Map) CloseOp(com.palantir.javaformat.CloseOp) ForLoopTree(com.sun.source.tree.ForLoopTree) InstanceOfTree(com.sun.source.tree.InstanceOfTree) ModuleTree(com.sun.source.tree.ModuleTree) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) TreePath(com.sun.source.util.TreePath) Verify(com.google.common.base.Verify) OpensTree(com.sun.source.tree.OpensTree) Set(java.util.Set) MemberSelectTree(com.sun.source.tree.MemberSelectTree) Trees.operatorName(com.palantir.javaformat.java.Trees.operatorName) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) ThrowTree(com.sun.source.tree.ThrowTree) Stream(java.util.stream.Stream) Predicate(com.google.common.base.Predicate) DirectiveTree(com.sun.source.tree.DirectiveTree) BlockTree(com.sun.source.tree.BlockTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) Flags(com.sun.tools.javac.code.Flags) ReturnTree(com.sun.source.tree.ReturnTree) Iterables(com.google.common.collect.Iterables) FormattingError(com.palantir.javaformat.FormattingError) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree) Break(com.palantir.javaformat.doc.Break) Input(com.palantir.javaformat.Input) Op(com.palantir.javaformat.Op) LabeledStatementTree(com.sun.source.tree.LabeledStatementTree) PRESERVE(com.palantir.javaformat.OpsBuilder.BlankLineWanted.PRESERVE) UnaryTree(com.sun.source.tree.UnaryTree) VariableTree(com.sun.source.tree.VariableTree) TypeParameterTree(com.sun.source.tree.TypeParameterTree) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) NewClassTree(com.sun.source.tree.NewClassTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) UNION_TYPE(com.sun.source.tree.Tree.Kind.UNION_TYPE) BreakTree(com.sun.source.tree.BreakTree) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) UNIFIED(com.palantir.javaformat.doc.FillMode.UNIFIED) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) INDEPENDENT(com.palantir.javaformat.doc.FillMode.INDEPENDENT) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Indent(com.palantir.javaformat.Indent) ExpressionTree(com.sun.source.tree.ExpressionTree) Trees.precedence(com.palantir.javaformat.java.Trees.precedence) METHOD_INVOCATION(com.sun.source.tree.Tree.Kind.METHOD_INVOCATION) MoreObjects(com.google.common.base.MoreObjects) Throwables(com.google.common.base.Throwables) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) ASSIGNMENT(com.sun.source.tree.Tree.Kind.ASSIGNMENT) BreakBehaviours(com.palantir.javaformat.BreakBehaviours) BlankLineWanted(com.palantir.javaformat.OpsBuilder.BlankLineWanted) EXTENDS_WILDCARD(com.sun.source.tree.Tree.Kind.EXTENDS_WILDCARD) STRING_LITERAL(com.sun.source.tree.Tree.Kind.STRING_LITERAL) IntersectionTypeTree(com.sun.source.tree.IntersectionTypeTree) Token(com.palantir.javaformat.doc.Token) WildcardTree(com.sun.source.tree.WildcardTree) RequiresTree(com.sun.source.tree.RequiresTree) ArrayDeque(java.util.ArrayDeque) UnionTypeTree(com.sun.source.tree.UnionTypeTree) ArrayAccessTree(com.sun.source.tree.ArrayAccessTree) PartialInlineability(com.palantir.javaformat.PartialInlineability) If.make(com.palantir.javaformat.Indent.If.make) AnnotatedTypeTree(com.sun.source.tree.AnnotatedTypeTree) Trees.skipParen(com.palantir.javaformat.java.Trees.skipParen) HashMultiset(com.google.common.collect.HashMultiset) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) NewArrayTree(com.sun.source.tree.NewArrayTree) YES(com.palantir.javaformat.OpsBuilder.BlankLineWanted.YES) ImmutableSet(com.google.common.collect.ImmutableSet) Trees.getLength(com.palantir.javaformat.java.Trees.getLength) Collection(java.util.Collection) ContinueTree(com.sun.source.tree.ContinueTree) Iterables.getLast(com.google.common.collect.Iterables.getLast) UsesTree(com.sun.source.tree.UsesTree) BreakTag(com.palantir.javaformat.doc.BreakTag) Streams(com.google.common.collect.Streams) CaseTree(com.sun.source.tree.CaseTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) SwitchTree(com.sun.source.tree.SwitchTree) List(java.util.List) IF(com.sun.source.tree.Tree.Kind.IF) PrimitiveTypeTree(com.sun.source.tree.PrimitiveTypeTree) SynchronizedTree(com.sun.source.tree.SynchronizedTree) AssertTree(com.sun.source.tree.AssertTree) StatementTree(com.sun.source.tree.StatementTree) ModifiersTree(com.sun.source.tree.ModifiersTree) Optional(java.util.Optional) WhileLoopTree(com.sun.source.tree.WhileLoopTree) Pattern(java.util.regex.Pattern) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) Multiset(com.google.common.collect.Multiset) BinaryTree(com.sun.source.tree.BinaryTree) EmptyStatementTree(com.sun.source.tree.EmptyStatementTree) Deque(java.util.Deque) Iterators(com.google.common.collect.Iterators) NEW_CLASS(com.sun.source.tree.Tree.Kind.NEW_CLASS) ImmutableList(com.google.common.collect.ImmutableList) FillMode(com.palantir.javaformat.doc.FillMode) Trees.getStartPosition(com.palantir.javaformat.java.Trees.getStartPosition) NEW_ARRAY(com.sun.source.tree.Tree.Kind.NEW_ARRAY) TreePathScanner(com.sun.source.util.TreePathScanner) ClassTree(com.sun.source.tree.ClassTree) Name(javax.lang.model.element.Name) OpsBuilder(com.palantir.javaformat.OpsBuilder) IfTree(com.sun.source.tree.IfTree) ProvidesTree(com.sun.source.tree.ProvidesTree) LastLevelBreakability(com.palantir.javaformat.LastLevelBreakability) MemberReferenceTree(com.sun.source.tree.MemberReferenceTree) JCTree(com.sun.tools.javac.tree.JCTree) Trees.getSourceForNode(com.palantir.javaformat.java.Trees.getSourceForNode) Collectors.toList(java.util.stream.Collectors.toList) ANNOTATION(com.sun.source.tree.Tree.Kind.ANNOTATION) DoWhileLoopTree(com.sun.source.tree.DoWhileLoopTree) BLOCK(com.sun.source.tree.Tree.Kind.BLOCK) TypeWithDims(com.palantir.javaformat.java.DimensionHelpers.TypeWithDims) TryTree(com.sun.source.tree.TryTree) Collections(java.util.Collections) OpenOp(com.palantir.javaformat.OpenOp) DirectiveTree(com.sun.source.tree.DirectiveTree) AnnotationTree(com.sun.source.tree.AnnotationTree)

Example 32 with AnnotationTree

use of com.sun.source.tree.AnnotationTree in project gradle-baseline by palantir.

the class ImmutablesStyle method matchStyleAnnotatedType.

private Description matchStyleAnnotatedType(ClassTree tree, VisitorState state) {
    if (ASTHelpers.enclosingClass(ASTHelpers.getSymbol(tree)) == null) {
        // additional top-level classes.
        return buildDescription(tree).addFix(SuggestedFixes.addSuppressWarnings(state, canonicalName(), "Automatically suppressed to unblock enforcement in new code")).build();
    }
    SuggestedFix.Builder fix = SuggestedFix.builder();
    String qualifiedTarget = SuggestedFixes.qualifyType(state, fix, Target.class.getName());
    String qualifiedElementType = SuggestedFixes.qualifyType(state, fix, ElementType.class.getName());
    String qualifiedRetention = SuggestedFixes.qualifyType(state, fix, Retention.class.getName());
    String qualifiedRetentionPolicy = SuggestedFixes.qualifyType(state, fix, RetentionPolicy.class.getName());
    AnnotationTree styleAnnotationTree = getAnnotation(tree, "org.immutables.value.Value$Style", state);
    return buildDescription(tree).addFix(fix.prefixWith(tree, String.format("\n@%s(%s.TYPE)\n@%s(%s.SOURCE)\n%s\n@interface %sStyle {}\n@%sStyle\n", qualifiedTarget, qualifiedElementType, qualifiedRetention, qualifiedRetentionPolicy, state.getSourceForNode(styleAnnotationTree), tree.getSimpleName(), tree.getSimpleName())).replace(styleAnnotationTree, "").build()).build();
}
Also used : Target(java.lang.annotation.Target) ElementType(java.lang.annotation.ElementType) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) AnnotationTree(com.sun.source.tree.AnnotationTree) Retention(java.lang.annotation.Retention) RetentionPolicy(java.lang.annotation.RetentionPolicy)

Example 33 with AnnotationTree

use of com.sun.source.tree.AnnotationTree in project btrace by btraceio.

the class Verifier method hasTrustedAnnotation.

/**
 * Detects if the class is annotated as @BTrace(trusted=true).
 */
private boolean hasTrustedAnnotation(ClassTree ct, Element topElement) {
    for (AnnotationTree at : ct.getModifiers().getAnnotations()) {
        String annFqn = ((JCTree) at.getAnnotationType()).type.tsym.getQualifiedName().toString();
        if (!annFqn.equals(BTrace.class.getName())) {
            continue;
        }
        // now we have @BTrace, look for unsafe = xxx or trusted = xxx
        for (ExpressionTree ext : at.getArguments()) {
            if (!(ext instanceof JCAssign)) {
                continue;
            }
            JCAssign assign = (JCAssign) ext;
            String name = ((JCIdent) assign.lhs).name.toString();
            if (!"unsafe".equals(name) && !"trusted".equals(name)) {
                continue;
            }
            // now rhs is the value of @BTrace.unsafe.
            // The value can be complex (!!true, 1 == 2, etc.) - we support only booleans
            String val = assign.rhs.toString();
            if ("true".equals(val)) {
                // bingo!
                return true;
            } else if (!"false".equals(val)) {
                processingEnv.getMessager().printMessage(Kind.WARNING, Messages.get("no.complex.unsafe.value"), topElement);
            }
        }
    }
    return false;
}
Also used : JCAssign(com.sun.tools.javac.tree.JCTree.JCAssign) ExpressionTree(com.sun.source.tree.ExpressionTree) AnnotationTree(com.sun.source.tree.AnnotationTree)

Example 34 with AnnotationTree

use of com.sun.source.tree.AnnotationTree in project btrace by btraceio.

the class VerifierVisitor method visitMethod.

@Override
public Void visitMethod(MethodTree node, Void v) {
    boolean oldInsideMethod = insideMethod;
    insideMethod = true;
    try {
        Name name = node.getName();
        if (name.contentEquals("<init>")) {
            return super.visitMethod(node, v);
        } else {
            checkSampling(node);
            if (isExitHandler(node)) {
                if (node.getParameters().size() != 1 || !"int".equals(node.getParameters().get(0).getType().toString())) {
                    reportError("onexit.invalid", node);
                    return super.visitMethod(node, v);
                }
            }
            if (isErrorHandler(node)) {
                Element thrElement = getElement(node.getParameters().get(0).getType());
                if (node.getParameters().size() != 1 || !THROWABLE_TYPE.equals(thrElement.toString())) {
                    reportError("onerror.invalid", node);
                }
            }
            for (VariableTree vt : node.getParameters()) {
                vt.accept(new TreeScanner<Void, Void>() {

                    @Override
                    public Void visitAnnotation(AnnotationTree at, Void p) {
                        isInAnnotation = true;
                        try {
                            return super.visitAnnotation(at, p);
                        } finally {
                            isInAnnotation = false;
                        }
                    }
                }, null);
            }
            Set<Modifier> flags = node.getModifiers().getFlags();
            if (shortSyntax) {
                if (isStatic(flags)) {
                    reportError("no.static.method", node);
                }
                if (isSynchronized(flags)) {
                    reportError("no.synchronized.methods", node);
                }
            } else {
                boolean isStatic = isStatic(flags);
                if (isStatic) {
                    boolean isPublic = isPublic(node.getModifiers().getFlags());
                    if (isPublic) {
                        if (isSynchronized(flags)) {
                            reportError("no.synchronized.methods", node);
                        }
                    } else {
                        // force the "public" modifier only on the annotated methods
                        if (isAnnotated(node)) {
                            reportError("method.should.be.public", node);
                        }
                    }
                } else {
                    reportError("no.instance.method", node);
                }
            }
            node.accept(jfrFieldNameCollector, null);
            return super.visitMethod(node, v);
        }
    } finally {
        insideMethod = oldInsideMethod;
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) VariableTree(com.sun.source.tree.VariableTree) AnnotationTree(com.sun.source.tree.AnnotationTree) Modifier(javax.lang.model.element.Modifier) Name(javax.lang.model.element.Name)

Example 35 with AnnotationTree

use of com.sun.source.tree.AnnotationTree in project btrace by btraceio.

the class VerifierVisitor method isExitHandler.

private boolean isExitHandler(MethodTree node) {
    ModifiersTree mt = node.getModifiers();
    List<? extends AnnotationTree> annos = mt.getAnnotations();
    for (AnnotationTree at : annos) {
        String annFqn = ((JCTree) at.getAnnotationType()).type.tsym.getQualifiedName().toString();
        if (annFqn.equals(ON_EXIT_TYPE)) {
            return true;
        }
    }
    return false;
}
Also used : ModifiersTree(com.sun.source.tree.ModifiersTree) AnnotationTree(com.sun.source.tree.AnnotationTree)

Aggregations

AnnotationTree (com.sun.source.tree.AnnotationTree)85 Tree (com.sun.source.tree.Tree)37 ExpressionTree (com.sun.source.tree.ExpressionTree)35 MethodTree (com.sun.source.tree.MethodTree)33 VariableTree (com.sun.source.tree.VariableTree)32 ClassTree (com.sun.source.tree.ClassTree)29 ModifiersTree (com.sun.source.tree.ModifiersTree)25 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)24 MemberSelectTree (com.sun.source.tree.MemberSelectTree)24 IdentifierTree (com.sun.source.tree.IdentifierTree)23 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)23 NewClassTree (com.sun.source.tree.NewClassTree)23 NewArrayTree (com.sun.source.tree.NewArrayTree)21 AnnotatedTypeTree (com.sun.source.tree.AnnotatedTypeTree)20 AssignmentTree (com.sun.source.tree.AssignmentTree)18 CompoundAssignmentTree (com.sun.source.tree.CompoundAssignmentTree)18 InstanceOfTree (com.sun.source.tree.InstanceOfTree)16 JCTree (com.sun.tools.javac.tree.JCTree)16 ArrayList (java.util.ArrayList)16 ArrayTypeTree (com.sun.source.tree.ArrayTypeTree)15