Search in sources :

Example 6 with Context

use of com.sun.tools.javac.util.Context in project lombok by rzwitserloot.

the class HandleSynchronized method handle.

@Override
public void handle(AnnotationValues<Synchronized> annotation, JCAnnotation ast, JavacNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.SYNCHRONIZED_FLAG_USAGE, "@Synchronized");
    if (inNetbeansEditor(annotationNode))
        return;
    deleteAnnotationIfNeccessary(annotationNode, Synchronized.class);
    JavacNode methodNode = annotationNode.up();
    if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl)) {
        annotationNode.addError("@Synchronized is legal only on methods.");
        return;
    }
    JCMethodDecl method = (JCMethodDecl) methodNode.get();
    if ((method.mods.flags & Flags.ABSTRACT) != 0) {
        annotationNode.addError("@Synchronized is legal only on concrete methods.");
        return;
    }
    boolean isStatic = (method.mods.flags & Flags.STATIC) != 0;
    String lockName = annotation.getInstance().value();
    boolean autoMake = false;
    if (lockName.length() == 0) {
        autoMake = true;
        lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME;
    }
    JavacTreeMaker maker = methodNode.getTreeMaker().at(ast.pos);
    Context context = methodNode.getContext();
    if (fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS) {
        if (!autoMake) {
            annotationNode.addError("The field " + lockName + " does not exist.");
            return;
        }
        JCExpression objectType = genJavaLangTypeRef(methodNode, ast.pos, "Object");
        //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable!
        JCNewArray newObjectArray = maker.NewArray(genJavaLangTypeRef(methodNode, ast.pos, "Object"), List.<JCExpression>of(maker.Literal(CTC_INT, 0)), null);
        JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef(maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)), methodNode.toName(lockName), objectType, newObjectArray), ast, context);
        injectFieldAndMarkGenerated(methodNode.up(), fieldDecl);
    }
    if (method.body == null)
        return;
    JCExpression lockNode;
    if (isStatic) {
        lockNode = chainDots(methodNode, ast.pos, methodNode.up().getName(), lockName);
    } else {
        lockNode = maker.Select(maker.Ident(methodNode.toName("this")), methodNode.toName(lockName));
    }
    recursiveSetGeneratedBy(lockNode, ast, context);
    method.body = setGeneratedBy(maker.Block(0, List.<JCStatement>of(setGeneratedBy(maker.Synchronized(lockNode, method.body), ast, context))), ast, context);
    methodNode.rebuild();
}
Also used : Context(com.sun.tools.javac.util.Context) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JavacNode(lombok.javac.JavacNode) JCNewArray(com.sun.tools.javac.tree.JCTree.JCNewArray) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl)

Example 7 with Context

use of com.sun.tools.javac.util.Context in project bazel by bazelbuild.

the class JavaSource2CFGDOT method getMethodTreeAndCompilationUnit.

/**
     * @return The AST of a specific method in a specific class as well as the
     *         {@link CompilationUnitTree} in a specific file (or null they do
     *         not exist).
     */
public static Entry</*@Nullable*/
MethodTree, /*@Nullable*/
CompilationUnitTree> getMethodTreeAndCompilationUnit(String file, final String method, String clas) {
    final Holder<MethodTree> m = new Holder<>();
    final Holder<CompilationUnitTree> c = new Holder<>();
    BasicTypeProcessor typeProcessor = new BasicTypeProcessor() {

        @Override
        protected TreePathScanner<?, ?> createTreePathScanner(CompilationUnitTree root) {
            c.value = root;
            return new TreePathScanner<Void, Void>() {

                @Override
                public Void visitMethod(MethodTree node, Void p) {
                    ExecutableElement el = TreeUtils.elementFromDeclaration(node);
                    if (el.getSimpleName().contentEquals(method)) {
                        m.value = node;
                        // compilation).
                        throw new RuntimeException();
                    }
                    return null;
                }
            };
        }
    };
    Context context = new Context();
    JavaCompiler javac = new JavaCompiler(context);
    javac.attrParseOnly = true;
    JavacFileManager fileManager = (JavacFileManager) context.get(JavaFileManager.class);
    JavaFileObject l = fileManager.getJavaFileObjectsFromStrings(List.of(file)).iterator().next();
    PrintStream err = System.err;
    try {
        // redirect syserr to nothing (and prevent the compiler from issuing
        // warnings about our exception.
        System.setErr(new PrintStream(new OutputStream() {

            @Override
            public void write(int b) throws IOException {
            }
        }));
        javac.compile(List.of(l), List.of(clas), List.of(typeProcessor));
    } catch (Throwable e) {
    // ok
    } finally {
        System.setErr(err);
    }
    return new Entry<MethodTree, CompilationUnitTree>() {

        @Override
        public CompilationUnitTree setValue(CompilationUnitTree value) {
            return null;
        }

        @Override
        public CompilationUnitTree getValue() {
            return c.value;
        }

        @Override
        public MethodTree getKey() {
            return m.value;
        }
    };
}
Also used : Context(com.sun.tools.javac.util.Context) PrintStream(java.io.PrintStream) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) MethodTree(com.sun.source.tree.MethodTree) JavaFileManager(javax.tools.JavaFileManager) Holder(javax.xml.ws.Holder) ExecutableElement(javax.lang.model.element.ExecutableElement) OutputStream(java.io.OutputStream) TreePathScanner(com.sun.source.util.TreePathScanner) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) JavaFileObject(javax.tools.JavaFileObject) Entry(java.util.Map.Entry) BasicTypeProcessor(org.checkerframework.javacutil.BasicTypeProcessor)

Example 8 with Context

use of com.sun.tools.javac.util.Context in project bazel by bazelbuild.

the class AbstractTypeProcessor method init.

/**
     * {@inheritDoc}
     *
     * Register a TaskListener that will get called after FLOW.
     */
@Override
public void init(ProcessingEnvironment env) {
    super.init(env);
    JavacTask.instance(env).addTaskListener(listener);
    Context ctx = ((JavacProcessingEnvironment) processingEnv).getContext();
    JavaCompiler compiler = JavaCompiler.instance(ctx);
    compiler.shouldStopPolicyIfNoError = CompileState.max(compiler.shouldStopPolicyIfNoError, CompileState.FLOW);
}
Also used : Context(com.sun.tools.javac.util.Context) JavacProcessingEnvironment(com.sun.tools.javac.processing.JavacProcessingEnvironment) JavaCompiler(com.sun.tools.javac.main.JavaCompiler)

Example 9 with Context

use of com.sun.tools.javac.util.Context in project bazel by bazelbuild.

the class JavacTurbineTest method reducedClasspath.

@Test
public void reducedClasspath() throws Exception {
    Path libD = temp.newFile("libd.jar").toPath();
    compileLib(libD, Collections.<Path>emptyList(), Arrays.asList(new StringJavaFileObject("D.java", "public class D {}")));
    Path libC = temp.newFile("libc.jar").toPath();
    compileLib(libC, Collections.singleton(libD), Arrays.asList(new StringJavaFileObject("C.java", "class C { static D d; }")));
    Path libB = temp.newFile("libb.jar").toPath();
    compileLib(libB, Arrays.asList(libC, libD), Arrays.asList(new StringJavaFileObject("B.java", "class B { static C c; }")));
    Path libA = temp.newFile("liba.jar").toPath();
    compileLib(libA, Arrays.asList(libB, libC, libD), Arrays.asList(new StringJavaFileObject("A.java", "class A { static B b; }")));
    Path depsA = writedeps("liba.jdeps", Deps.Dependencies.newBuilder().setSuccess(true).setRuleLabel("//lib:a").addDependency(Deps.Dependency.newBuilder().setPath(libB.toString()).setKind(Deps.Dependency.Kind.EXPLICIT)).build());
    optionsBuilder.addClassPathEntries(ImmutableList.of(libA.toString(), libB.toString(), libC.toString(), libD.toString()));
    optionsBuilder.addAllDepsArtifacts(ImmutableList.of(depsA.toString()));
    optionsBuilder.addDirectJarToTarget(libA.toString(), "//lib:a");
    optionsBuilder.addIndirectJarToTarget(libB.toString(), "//lib:b");
    optionsBuilder.addIndirectJarToTarget(libC.toString(), "//lib:c");
    optionsBuilder.addIndirectJarToTarget(libD.toString(), "//lib:d");
    optionsBuilder.setTargetLabel("//my:target");
    addSourceLines("Hello.java", "class Hello {", "  public static A a = new A();", "  public static void main(String[] args) {", "    A a = null;", "    B b = null;", "    C c = null;", "    D d = null;", "  }", "}");
    optionsBuilder.addSources(ImmutableList.copyOf(Iterables.transform(sources, TO_STRING)));
    try (JavacTurbine turbine = new JavacTurbine(new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err, UTF_8))), optionsBuilder.build())) {
        assertThat(turbine.compile()).isEqualTo(Result.OK_WITH_REDUCED_CLASSPATH);
        Context context = turbine.context;
        JavacFileManager fm = (JavacFileManager) context.get(JavaFileManager.class);
        assertThat(fm.getLocationAsPaths(StandardLocation.CLASS_PATH)).containsExactly(libA, libB);
        Deps.Dependencies depsProto = getDeps();
        assertThat(depsProto.getSuccess()).isTrue();
        assertThat(depsProto.getRuleLabel()).isEqualTo("//my:target");
        assertThat(getEntries(depsProto)).containsExactlyEntriesIn(ImmutableMap.of(libA.toString(), Deps.Dependency.Kind.EXPLICIT, libB.toString(), Deps.Dependency.Kind.INCOMPLETE));
    }
}
Also used : Path(java.nio.file.Path) Context(com.sun.tools.javac.util.Context) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Deps(com.google.devtools.build.lib.view.proto.Deps) JavaFileManager(javax.tools.JavaFileManager) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter) Test(org.junit.Test)

Example 10 with Context

use of com.sun.tools.javac.util.Context in project bazel by bazelbuild.

the class TreePrunerTest method setUp.

@Before
public void setUp() {
    this.context = new Context();
    // registers itself in the context as a side effect
    new JavacFileManager(context, true, UTF_8);
}
Also used : Context(com.sun.tools.javac.util.Context) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Before(org.junit.Before)

Aggregations

Context (com.sun.tools.javac.util.Context)65 JavacFileManager (com.sun.tools.javac.file.JavacFileManager)19 Test (org.junit.Test)9 Options (com.sun.tools.javac.util.Options)8 IOException (java.io.IOException)8 PrintWriter (java.io.PrintWriter)8 JavaFileObject (javax.tools.JavaFileObject)7 ListBuffer (com.sun.tools.javac.util.ListBuffer)6 JavacTask (com.sun.source.util.JavacTask)5 JavacProcessingEnvironment (com.sun.tools.javac.processing.JavacProcessingEnvironment)5 JCCompilationUnit (com.sun.tools.javac.tree.JCTree.JCCompilationUnit)5 JavaFileManager (javax.tools.JavaFileManager)5 OutputStreamWriter (java.io.OutputStreamWriter)4 Path (java.nio.file.Path)4 DiagnosticListener (javax.tools.DiagnosticListener)4 ImmutableList (com.google.common.collect.ImmutableList)3 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)3 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)3 JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)3 StringWriter (java.io.StringWriter)3