Search in sources :

Example 36 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project bazel by bazelbuild.

the class TreePrunerTest method annotationDeclaration.

@Test
public void annotationDeclaration() {
    String[] lines = { "@interface Anno {", "  int f() default CONST;", "  int CONST = 42;", "  int NONCONST = new Integer(42);", "}" };
    JCCompilationUnit tree = parseLines(lines);
    TreePruner.prune(context, tree);
    String[] expected = { "@interface Anno {", "    ", "    int f() default CONST;", "    int CONST = 42;", "    int NONCONST;", "}" };
    assertThat(prettyPrint(tree)).isEqualTo(Joiner.on('\n').join(expected));
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) Test(org.junit.Test)

Example 37 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project bazel by bazelbuild.

the class TreePrunerTest method nonConstantFieldInitializers.

@Test
public void nonConstantFieldInitializers() {
    String[] lines = { //
    "class Test {", "  Object a = null;", "  int[] b = {1};", "  int c = g();", "  String d = \"\" + h();", "}" };
    JCCompilationUnit tree = parseLines(lines);
    TreePruner.prune(context, tree);
    String[] expected = { //
    "class Test {", "    Object a;", "    int[] b;", "    int c;", "    String d;", "}" };
    assertThat(prettyPrint(tree)).isEqualTo(Joiner.on('\n').join(expected));
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) Test(org.junit.Test)

Example 38 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project error-prone by google.

the class RestrictedApiChecker method checkRestriction.

private Description checkRestriction(@Nullable RestrictedApi restriction, Tree where, VisitorState state) {
    if (restriction == null) {
        return Description.NO_MATCH;
    }
    if (!restriction.allowedOnPath().isEmpty()) {
        JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit();
        if (Pattern.matches(restriction.allowedOnPath(), compilationUnit.getSourceFile().toUri().getRawPath())) {
            return Description.NO_MATCH;
        }
    }
    boolean warn = Matchers.enclosingNode(shouldAllowWithWarning(restriction, state)).matches(where, state);
    boolean allow = Matchers.enclosingNode(shouldAllow(restriction, state)).matches(where, state);
    if (warn && allow) {
        // TODO(bangert): Clarify this message if possible.
        return buildDescription(where).setMessage("The Restricted API ([" + restriction.checkerName() + "]" + restriction.explanation() + ") call here is both whitelisted-as-warning and " + "silently whitelisted. " + "Please remove one of the conflicting suppression annotations.").build();
    }
    if (allow) {
        return Description.NO_MATCH;
    }
    SeverityLevel level = warn ? SeverityLevel.WARNING : SeverityLevel.ERROR;
    return Description.builder(where, restriction.checkerName(), restriction.link(), level, restriction.explanation()).build();
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) SeverityLevel(com.google.errorprone.BugPattern.SeverityLevel)

Example 39 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project error-prone by google.

the class UnificationTest method expectMatches.

public void expectMatches(final Template<?> template, Match... expected) {
    final Set<Match> expectedMatches = Sets.newHashSet(expected);
    TreeScanner matchScanner = new TreeScanner() {

        @Override
        public void scan(JCTree tree) {
            if (tree == null) {
                return;
            }
            for (TemplateMatch templateMatch : template.match(tree, context)) {
                Match match = Match.create(templateMatch);
                if (!expectedMatches.remove(match)) {
                    fail(String.format("Unexpected match against template %s:%n%s", template, match));
                }
            }
            super.scan(tree);
        }
    };
    for (JCCompilationUnit unit : compilationUnits) {
        matchScanner.scan(unit);
    }
    for (Match missingMatch : expectedMatches) {
        fail(String.format("Expected match against template %s not found: %s", template, missingMatch));
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) TreeScanner(com.sun.tools.javac.tree.TreeScanner) JCTree(com.sun.tools.javac.tree.JCTree)

Example 40 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project error-prone by google.

the class Template method pretty.

protected static Pretty pretty(Context context, final Writer writer) {
    final JCCompilationUnit unit = context.get(JCCompilationUnit.class);
    try {
        final String unitContents = unit.getSourceFile().getCharContent(false).toString();
        return new Pretty(writer, true) {

            {
                // Work-around for b/22196513
                width = 0;
            }

            @Override
            public void visitAnnotation(JCAnnotation anno) {
                if (anno.getArguments().isEmpty()) {
                    try {
                        print("@");
                        printExpr(anno.annotationType);
                    } catch (IOException e) {
                        // the supertype swallows exceptions too
                        throw new RuntimeException(e);
                    }
                } else {
                    super.visitAnnotation(anno);
                }
            }

            @Override
            public void printExpr(JCTree tree, int prec) throws IOException {
                EndPosTable endPositions = unit.endPositions;
                /*
           * Modifiers, and specifically flags like final, appear to just need weird special
           * handling.
           *
           * Note: we can't use {@code TreeInfo.getEndPos()} or {@code JCTree.getEndPosition()}
           * here, because they will return the end position of an enclosing AST node for trees
           * whose real end positions aren't stored.
           */
                int endPos = endPositions.getEndPos(tree);
                boolean hasRealEndPosition = endPos != Position.NOPOS;
                if (tree.getKind() != Kind.MODIFIERS && hasRealEndPosition) {
                    writer.append(unitContents.substring(tree.getStartPosition(), endPos));
                } else {
                    super.printExpr(tree, prec);
                }
            }

            @Override
            public void visitApply(JCMethodInvocation tree) {
                JCExpression select = tree.getMethodSelect();
                if (select != null && select.toString().equals("Refaster.emitCommentBefore")) {
                    String commentLiteral = (String) ((JCLiteral) tree.getArguments().get(0)).getValue();
                    JCExpression expr = tree.getArguments().get(1);
                    try {
                        print("/* " + commentLiteral + " */ ");
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    expr.accept(this);
                } else {
                    super.visitApply(tree);
                }
            }

            @Override
            public void printStat(JCTree tree) throws IOException {
                if (tree instanceof JCExpressionStatement && ((JCExpressionStatement) tree).getExpression() instanceof JCMethodInvocation) {
                    JCMethodInvocation invocation = (JCMethodInvocation) ((JCExpressionStatement) tree).getExpression();
                    JCExpression select = invocation.getMethodSelect();
                    if (select != null && select.toString().equals("Refaster.emitComment")) {
                        String commentLiteral = (String) ((JCLiteral) invocation.getArguments().get(0)).getValue();
                        print("// " + commentLiteral);
                        return;
                    }
                }
                super.printStat(tree);
            }

            @Override
            public void visitTry(JCTry tree) {
                if (tree.getResources().isEmpty()) {
                    super.visitTry(tree);
                    return;
                }
                try {
                    print("try (");
                    boolean first = true;
                    for (JCTree resource : tree.getResources()) {
                        if (!first) {
                            print(";");
                            println();
                        }
                        printExpr(resource);
                        first = false;
                    }
                    print(")");
                    printStat(tree.body);
                    for (JCCatch catchStmt : tree.getCatches()) {
                        printStat(catchStmt);
                    }
                    if (tree.getFinallyBlock() != null) {
                        print(" finally ");
                        printStat(tree.getFinallyBlock());
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JCTree(com.sun.tools.javac.tree.JCTree) IOException(java.io.IOException) JCExpressionStatement(com.sun.tools.javac.tree.JCTree.JCExpressionStatement) Pretty(com.sun.tools.javac.tree.Pretty) JCTry(com.sun.tools.javac.tree.JCTree.JCTry) JCMethodInvocation(com.sun.tools.javac.tree.JCTree.JCMethodInvocation) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCCatch(com.sun.tools.javac.tree.JCTree.JCCatch) JCAnnotation(com.sun.tools.javac.tree.JCTree.JCAnnotation) EndPosTable(com.sun.tools.javac.tree.EndPosTable)

Aggregations

JCCompilationUnit (com.sun.tools.javac.tree.JCTree.JCCompilationUnit)50 JCTree (com.sun.tools.javac.tree.JCTree)11 JavaFileObject (javax.tools.JavaFileObject)7 Test (org.junit.Test)7 JCClassDecl (com.sun.tools.javac.tree.JCTree.JCClassDecl)6 IOException (java.io.IOException)6 CeylonCompilationUnit (com.redhat.ceylon.compiler.java.codegen.CeylonCompilationUnit)5 TaskEvent (com.sun.source.util.TaskEvent)5 File (java.io.File)5 TaskListener (com.sun.source.util.TaskListener)4 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)4 ArrayList (java.util.ArrayList)4 ImmutableList (com.google.common.collect.ImmutableList)3 CeyloncTaskImpl (com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl)3 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)3 TreePath (com.sun.source.util.TreePath)3 JavacTool (com.sun.tools.javac.api.JavacTool)3 JCAnnotation (com.sun.tools.javac.tree.JCTree.JCAnnotation)3 JCAssign (com.sun.tools.javac.tree.JCTree.JCAssign)3 Context (com.sun.tools.javac.util.Context)3