Search in sources :

Example 41 with JCCompilationUnit

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

the class ExpressionTemplate method getPrecedence.

/**
   * Returns the precedence level appropriate for unambiguously printing
   * leaf as a subexpression of its parent.
   */
private static int getPrecedence(JCTree leaf, Context context) {
    JCCompilationUnit comp = context.get(JCCompilationUnit.class);
    JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);
    if (parent instanceof JCConditional) {
        // This intentionally differs from Pretty, because Pretty appears buggy:
        // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
        JCConditional conditional = (JCConditional) parent;
        return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
    } else if (parent instanceof JCAssign) {
        JCAssign assign = (JCAssign) parent;
        return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
    } else if (parent instanceof JCAssignOp) {
        JCAssignOp assignOp = (JCAssignOp) parent;
        return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
    } else if (parent instanceof JCUnary) {
        return TreeInfo.opPrec(parent.getTag());
    } else if (parent instanceof JCBinary) {
        JCBinary binary = (JCBinary) parent;
        return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
    } else if (parent instanceof JCTypeCast) {
        JCTypeCast typeCast = (JCTypeCast) parent;
        return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
    } else if (parent instanceof JCInstanceOf) {
        JCInstanceOf instanceOf = (JCInstanceOf) parent;
        return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
    } else if (parent instanceof JCArrayAccess) {
        JCArrayAccess arrayAccess = (JCArrayAccess) parent;
        return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
    } else if (parent instanceof JCFieldAccess) {
        JCFieldAccess fieldAccess = (JCFieldAccess) parent;
        return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
    } else {
        return TreeInfo.noPrec;
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JCTypeCast(com.sun.tools.javac.tree.JCTree.JCTypeCast) JCAssign(com.sun.tools.javac.tree.JCTree.JCAssign) JCUnary(com.sun.tools.javac.tree.JCTree.JCUnary) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) JCConditional(com.sun.tools.javac.tree.JCTree.JCConditional) JCTree(com.sun.tools.javac.tree.JCTree) JCBinary(com.sun.tools.javac.tree.JCTree.JCBinary) JCArrayAccess(com.sun.tools.javac.tree.JCTree.JCArrayAccess) JCAssignOp(com.sun.tools.javac.tree.JCTree.JCAssignOp) JCInstanceOf(com.sun.tools.javac.tree.JCTree.JCInstanceOf)

Example 42 with JCCompilationUnit

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

the class BugCheckerRefactoringTestHelper method doCompile.

private JCCompilationUnit doCompile(final JavaFileObject input, Iterable<JavaFileObject> files, Context context) throws IOException {
    JavacTool tool = JavacTool.create();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
    context.put(ErrorProneOptions.class, ErrorProneOptions.empty());
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, options, /*classes=*/
    null, files, context);
    Iterable<? extends CompilationUnitTree> trees = task.parse();
    task.analyze();
    JCCompilationUnit tree = Iterables.getOnlyElement(Iterables.filter(Iterables.filter(trees, JCCompilationUnit.class), compilationUnit -> compilationUnit.getSourceFile() == input));
    Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics = Iterables.filter(diagnosticsCollector.getDiagnostics(), d -> d.getKind() == Diagnostic.Kind.ERROR);
    if (!Iterables.isEmpty(errorDiagnostics)) {
        fail("compilation failed unexpectedly: " + errorDiagnostics);
    }
    return tree;
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) Iterables(com.google.common.collect.Iterables) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) HashMap(java.util.HashMap) DescriptionBasedDiff(com.google.errorprone.apply.DescriptionBasedDiff) ErrorProneScannerTransformer(com.google.errorprone.scanner.ErrorProneScannerTransformer) ErrorProneScanner(com.google.errorprone.scanner.ErrorProneScanner) ImmutableList(com.google.common.collect.ImmutableList) CharStreams(com.google.common.io.CharStreams) JavacTool(com.sun.tools.javac.api.JavacTool) Diagnostic(javax.tools.Diagnostic) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) Fix(com.google.errorprone.fixes.Fix) DiagnosticCollector(javax.tools.DiagnosticCollector) Truth.assertAbout(com.google.common.truth.Truth.assertAbout) JavaFileObjects(com.google.testing.compile.JavaFileObjects) TreePath(com.sun.source.util.TreePath) BugChecker(com.google.errorprone.bugpatterns.BugChecker) IOException(java.io.IOException) Truth.assertThat(com.google.common.truth.Truth.assertThat) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JavaSourceSubjectFactory.javaSource(com.google.testing.compile.JavaSourceSubjectFactory.javaSource) JavaFileObject(javax.tools.JavaFileObject) SourceFile(com.google.errorprone.apply.SourceFile) List(java.util.List) Description(com.google.errorprone.matchers.Description) Context(com.sun.tools.javac.util.Context) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JavaFileObject(javax.tools.JavaFileObject) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JavacTool(com.sun.tools.javac.api.JavacTool) Diagnostic(javax.tools.Diagnostic) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 43 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project lombok by rzwitserloot.

the class Delombok method delombok.

public boolean delombok() throws IOException {
    LombokOptions options = LombokOptionsFactory.getDelombokOptions(context);
    options.deleteLombokAnnotations();
    options.putJavacOption("ENCODING", charset.name());
    if (classpath != null)
        options.putJavacOption("CLASSPATH", classpath);
    if (sourcepath != null)
        options.putJavacOption("SOURCEPATH", sourcepath);
    if (bootclasspath != null)
        options.putJavacOption("BOOTCLASSPATH", bootclasspath);
    options.setFormatPreferences(new FormatPreferences(formatPrefs));
    options.put("compilePolicy", "check");
    CommentCatcher catcher = CommentCatcher.create(context);
    JavaCompiler compiler = catcher.getCompiler();
    List<JCCompilationUnit> roots = new ArrayList<JCCompilationUnit>();
    Map<JCCompilationUnit, File> baseMap = new IdentityHashMap<JCCompilationUnit, File>();
    compiler.initProcessAnnotations(Collections.singleton(new lombok.javac.apt.LombokProcessor()));
    for (File fileToParse : filesToParse) {
        @SuppressWarnings("deprecation") JCCompilationUnit unit = compiler.parse(fileToParse.getAbsolutePath());
        baseMap.put(unit, fileToBase.get(fileToParse));
        roots.add(unit);
    }
    if (compiler.errorCount() > 0) {
        // At least one parse error. No point continuing (a real javac run doesn't either).
        return false;
    }
    for (JCCompilationUnit unit : roots) {
        catcher.setComments(unit, new DocCommentIntegrator().integrate(catcher.getComments(unit), unit));
    }
    com.sun.tools.javac.util.List<JCCompilationUnit> trees = compiler.enterTrees(toJavacList(roots));
    JavaCompiler delegate = compiler.processAnnotations(trees);
    Object care = callAttributeMethodOnJavaCompiler(delegate, delegate.todo);
    callFlowMethodOnJavaCompiler(delegate, care);
    FormatPreferences fps = new FormatPreferences(formatPrefs);
    for (JCCompilationUnit unit : roots) {
        DelombokResult result = new DelombokResult(catcher.getComments(unit), unit, force || options.isChanged(unit), fps);
        if (verbose)
            feedback.printf("File: %s [%s%s]\n", unit.sourcefile.getName(), result.isChanged() ? "delomboked" : "unchanged", force && !options.isChanged(unit) ? " (forced)" : "");
        Writer rawWriter;
        if (presetWriter != null)
            rawWriter = createUnicodeEscapeWriter(presetWriter);
        else if (output == null)
            rawWriter = createStandardOutWriter();
        else
            rawWriter = createFileWriter(output, baseMap.get(unit), unit.sourcefile.toUri());
        BufferedWriter writer = new BufferedWriter(rawWriter);
        try {
            result.print(writer);
        } finally {
            if (output != null) {
                writer.close();
            } else {
                writer.flush();
            }
        }
    }
    delegate.close();
    return true;
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) IdentityHashMap(java.util.IdentityHashMap) CommentCatcher(lombok.javac.CommentCatcher) ArrayList(java.util.ArrayList) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) BufferedWriter(java.io.BufferedWriter) LombokOptions(lombok.javac.LombokOptions) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer)

Example 44 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project lombok by rzwitserloot.

the class JavacHandlerUtil method copyJavadoc.

/**
	 * Copies javadoc on one node to the other.
	 * 
	 * in 'GETTER' copyMode, first a 'GETTER' segment is searched for. If it exists, that will become the javadoc for the 'to' node, and this section is
	 * stripped out of the 'from' node. If no 'GETTER' segment is found, then the entire javadoc is taken minus any {@code @param} lines and other sections.
	 * any {@code @return} lines are stripped from 'from'.
	 * 
	 * in 'SETTER' mode, stripping works similarly to 'GETTER' mode, except {@code param} are copied and stripped from the original and {@code @return} are skipped.
	 */
public static void copyJavadoc(JavacNode from, JCTree to, CopyJavadoc copyMode) {
    if (copyMode == null)
        copyMode = CopyJavadoc.VERBATIM;
    try {
        JCCompilationUnit cu = ((JCCompilationUnit) from.top().get());
        Object dc = Javac.getDocComments(cu);
        if (dc instanceof Map) {
            copyJavadoc_jdk6_7(from, to, copyMode, dc);
        } else if (Javac.instanceOfDocCommentTable(dc)) {
            CopyJavadoc_8.copyJavadoc(from, to, copyMode, dc);
        }
    } catch (Exception ignore) {
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) Map(java.util.Map) HashMap(java.util.HashMap)

Example 45 with JCCompilationUnit

use of com.sun.tools.javac.tree.JCTree.JCCompilationUnit in project lombok by rzwitserloot.

the class JavacHandlerUtil method unboxAndRemoveAnnotationParameter.

static List<JCAnnotation> unboxAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName, String errorName, JavacNode annotationNode) {
    ListBuffer<JCExpression> params = new ListBuffer<JCExpression>();
    ListBuffer<JCAnnotation> result = new ListBuffer<JCAnnotation>();
    outer: for (JCExpression param : ast.args) {
        boolean allowRaw;
        String nameOfParam = "value";
        JCExpression valueOfParam = null;
        if (param instanceof JCAssign) {
            JCAssign assign = (JCAssign) param;
            if (assign.lhs instanceof JCIdent) {
                JCIdent ident = (JCIdent) assign.lhs;
                nameOfParam = ident.name.toString();
            }
            valueOfParam = assign.rhs;
        }
        /* strip trailing underscores */
        {
            int lastIdx;
            for (lastIdx = nameOfParam.length(); lastIdx > 0; lastIdx--) {
                if (nameOfParam.charAt(lastIdx - 1) != '_')
                    break;
            }
            allowRaw = lastIdx < nameOfParam.length();
            nameOfParam = nameOfParam.substring(0, lastIdx);
        }
        if (!parameterName.equals(nameOfParam)) {
            params.append(param);
            continue outer;
        }
        int endPos = Javac.getEndPosition(param.pos(), (JCCompilationUnit) annotationNode.top().get());
        annotationNode.getAst().removeFromDeferredDiagnostics(param.pos, endPos);
        if (valueOfParam instanceof JCAnnotation) {
            String dummyAnnotationName = ((JCAnnotation) valueOfParam).annotationType.toString();
            dummyAnnotationName = dummyAnnotationName.replace("_", "").replace("$", "").replace("x", "").replace("X", "");
            if (dummyAnnotationName.length() > 0) {
                if (allowRaw) {
                    result.append((JCAnnotation) valueOfParam);
                } else {
                    addError(errorName, annotationNode);
                    continue outer;
                }
            } else {
                for (JCExpression expr : ((JCAnnotation) valueOfParam).args) {
                    if (expr instanceof JCAssign && ((JCAssign) expr).lhs instanceof JCIdent) {
                        JCIdent id = (JCIdent) ((JCAssign) expr).lhs;
                        if ("value".equals(id.name.toString())) {
                            expr = ((JCAssign) expr).rhs;
                        } else {
                            addError(errorName, annotationNode);
                        }
                    }
                    if (expr instanceof JCAnnotation) {
                        result.append((JCAnnotation) expr);
                    } else if (expr instanceof JCNewArray) {
                        for (JCExpression expr2 : ((JCNewArray) expr).elems) {
                            if (expr2 instanceof JCAnnotation) {
                                result.append((JCAnnotation) expr2);
                            } else {
                                addError(errorName, annotationNode);
                                continue outer;
                            }
                        }
                    } else {
                        addError(errorName, annotationNode);
                        continue outer;
                    }
                }
            }
        } else if (valueOfParam instanceof JCNewArray) {
            JCNewArray arr = (JCNewArray) valueOfParam;
            if (arr.elems.isEmpty()) {
            // Just remove it, this is always fine.
            } else if (allowRaw) {
                for (JCExpression jce : arr.elems) {
                    if (jce instanceof JCAnnotation)
                        result.append((JCAnnotation) jce);
                    else
                        addError(errorName, annotationNode);
                }
            } else {
                addError(errorName, annotationNode);
            }
        } else {
            addError(errorName, annotationNode);
        }
    }
    ast.args = params.toList();
    return result.toList();
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JCIdent(com.sun.tools.javac.tree.JCTree.JCIdent) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCAssign(com.sun.tools.javac.tree.JCTree.JCAssign) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCNewArray(com.sun.tools.javac.tree.JCTree.JCNewArray) JCAnnotation(com.sun.tools.javac.tree.JCTree.JCAnnotation)

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