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();
}
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;
}
};
}
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);
}
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));
}
}
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);
}
Aggregations