Here are the examples of the java api com.sun.source.util.JavacTask taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
241 Examples
19
Source : JavacTrees.java
with Apache License 2.0
from tzfun
with Apache License 2.0
from tzfun
private void init(Context context) {
attr = Attr.instance(context);
enter = Enter.instance(context);
elements = JavacElements.instance(context);
log = Log.instance(context);
resolve = Resolve.instance(context);
treeMaker = TreeMaker.instance(context);
memberEnter = MemberEnter.instance(context);
names = Names.instance(context);
types = Types.instance(context);
JavacTask t = context.get(JavacTask.clreplaced);
if (t instanceof JavacTaskImpl)
javacTaskImpl = (JavacTaskImpl) t;
}
19
Source : Env.java
with Apache License 2.0
from tzfun
with Apache License 2.0
from tzfun
void init(JavacTask task) {
init(DocTrees.instance(task), task.getElements(), task.getTypes());
}
19
Source : DocLint.java
with Apache License 2.0
from tzfun
with Apache License 2.0
from tzfun
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Embedding API">
public void init(JavacTask task, String[] args, boolean addTaskListener) {
env = new Env();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals(XMSGS_OPTION)) {
env.messages.setOptions(null);
} else if (arg.startsWith(XMSGS_CUSTOM_PREFIX)) {
env.messages.setOptions(arg.substring(arg.indexOf(":") + 1));
} else if (arg.matches(XIMPLICIT_HEADERS + "[1-6]")) {
char ch = arg.charAt(arg.length() - 1);
env.setImplicitHeaders(Character.digit(ch, 10));
} else if (arg.startsWith(XCUSTOM_TAGS_PREFIX)) {
env.setCustomTags(arg.substring(arg.indexOf(":") + 1));
} else
throw new IllegalArgumentException(arg);
}
env.init(task);
checker = new Checker(env);
if (addTaskListener) {
final DeclScanner ds = new DeclScanner() {
@Override
void visitDecl(Tree tree, Name name) {
TreePath p = getCurrentPath();
DocCommentTree dc = env.trees.getDocCommentTree(p);
checker.scan(dc, p);
}
};
TaskListener tl = new TaskListener() {
@Override
public void started(TaskEvent e) {
switch(e.getKind()) {
case replacedYZE:
CompilationUnitTree tree;
while ((tree = todo.poll()) != null) ds.scan(tree, null);
break;
}
}
@Override
public void finished(TaskEvent e) {
switch(e.getKind()) {
case PARSE:
todo.add(e.getCompilationUnit());
break;
}
}
Queue<CompilationUnitTree> todo = new LinkedList<CompilationUnitTree>();
};
task.addTaskListener(tl);
}
}
19
Source : T7043922.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
void compileAndCheck() throws Exception {
JavaSource source = new JavaSource();
ErrorChecker ec = new ErrorChecker();
JavacTask ct = (JavacTask) tool.getTask(null, fm, ec, null, null, Arrays.asList(source));
ct.replacedyze();
if (ec.errorFound) {
throw new Error("invalid diagnostics for source:\n" + source.getCharContent(true) + "\nCompiler diagnostics:\n" + ec.printDiags());
}
}
19
Source : Main.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public clreplaced Main {
public static PackageElement getPackage(TypeElement type) {
Element owner = type;
while (owner.getKind() != ElementKind.PACKAGE) owner = owner.getEnclosingElement();
return (PackageElement) owner;
}
static int progress = 0;
static JavaCompiler tool;
static JavacTask javac;
static Elements elements;
public static void main(String[] args) throws Exception {
if (haveAltRt()) {
System.out.println("Warning: alt-rt.jar detected, test skipped");
return;
}
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
fm.setLocation(CLreplaced_PATH, Collections.<File>emptyList());
JavacTask javac = (JavacTask) tool.getTask(null, fm, null, null, null, null);
Elements elements = javac.getElements();
final Set<String> packages = new LinkedHashSet<String>();
int nestedClreplacedes = 0;
int clreplacedes = 0;
for (JavaFileObject file : fm.list(PLATFORM_CLreplaced_PATH, "", EnumSet.of(CLreplaced), true)) {
String type = fm.inferBinaryName(PLATFORM_CLreplaced_PATH, file);
if (type.endsWith("package-info"))
continue;
try {
TypeElement elem = elements.getTypeElement(type);
if (elem == null && type.indexOf('$') > 0) {
nestedClreplacedes++;
type = null;
continue;
}
clreplacedes++;
packages.add(getPackage(elem).getQualifiedName().toString());
// force completion
elements.getTypeElement(type).getKind();
type = null;
} finally {
if (type != null)
System.err.println("Looking at " + type);
}
}
javac = null;
elements = null;
javac = (JavacTask) tool.getTask(null, fm, null, null, null, null);
elements = javac.getElements();
for (String name : packages) {
PackageElement pe = elements.getPackageElement(name);
for (Element e : pe.getEnclosedElements()) {
e.getSimpleName().getClreplaced();
}
}
/*
* A few sanity checks based on current values:
*
* packages: 775, clreplacedes: 12429 + 5917
*
* As the platform evolves the numbers are likely to grow
* monotonically but in case somebody gets a clever idea for
* limiting the number of packages exposed, this number might
* drop. So we test low values.
*/
System.out.format("packages: %s, clreplacedes: %s + %s%n", packages.size(), clreplacedes, nestedClreplacedes);
if (clreplacedes < 9000)
throw new replacedertionError("Too few clreplacedes in PLATFORM_CLreplaced_PATH ;-)");
if (packages.size() < 530)
throw new replacedertionError("Too few packages in PLATFORM_CLreplaced_PATH ;-)");
if (nestedClreplacedes < 3000)
throw new replacedertionError("Too few nested clreplacedes in PLATFORM_CLreplaced_PATH ;-)");
}
/*
* If -XX:+AggressiveOpts has been used to test, the option currently
* instructs the VM to prepend alt-rt.jar onto the bootclreplacedpath. This
* overrides the default TreeMap implemation in rt.jar causing symbol
* resolution problems (caused by inconsistent inner clreplaced), although
* alt-rt.jar is being eliminated, we have this sanity check to detect this
* case and skip the test.
*/
static boolean haveAltRt() {
String bootClreplacedPath = System.getProperty("sun.boot.clreplaced.path");
for (String cp : bootClreplacedPath.split(File.pathSeparator)) {
if (cp.endsWith("alt-rt.jar")) {
System.err.println("Warning: detected alt-rt.jar in " + "sun.boot.clreplaced.path");
return true;
}
}
return false;
}
}
19
Source : TestClose2.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
void run() throws IOException {
File testSrc = new File(System.getProperty("test.src"));
File testClreplacedes = new File(System.getProperty("test.clreplacedes"));
JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
final ClreplacedLoader cl = getClreplaced().getClreplacedLoader();
Context c = new Context();
StandardJavaFileManager fm = new JavacFileManager(c, true, null) {
@Override
protected ClreplacedLoader getClreplacedLoader(URL[] urls) {
return new URLClreplacedLoader(urls, cl) {
@Override
public void close() throws IOException {
System.err.println(getClreplaced().getName() + " closing");
TestClose2.this.closedCount++;
TestClose2.this.closedIsLast = true;
super.close();
}
};
}
};
fm.setLocation(StandardLocation.CLreplaced_OUTPUT, Collections.singleton(new File(".")));
fm.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH, Collections.singleton(testClreplacedes));
Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(new File(testSrc, TestClose2.clreplaced.getName() + ".java"));
List<String> options = Arrays.asList("-processor", TestClose2.clreplaced.getName());
JavacTask task = tool.getTask(null, fm, null, options, null, files);
task.setTaskListener(this);
if (!task.call())
throw new Error("compilation failed");
if (closedCount == 0)
throw new Error("no closing message");
else if (closedCount > 1)
throw new Error(closedCount + " closed messages");
if (!closedIsLast)
throw new Error("closing message not last");
}
19
Source : ShowTypePlugin.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public void init(JavacTask task, String... args) {
Pattern pattern = null;
if (args.length == 1)
pattern = Pattern.compile(args[0]);
task.addTaskListener(new PostreplacedyzeTaskListener(task, pattern));
}
19
Source : DisjunctiveTypeWellFormednessTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
@Override
public void run() {
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source));
try {
ct.replacedyze();
} catch (Throwable t) {
processException(t);
return;
}
check();
}
19
Source : TypeInferenceComboTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public void run() {
DiagnosticChecker dc = new DiagnosticChecker();
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
try {
ct.replacedyze();
} catch (Throwable t) {
processException(t);
}
if (dc.errorFound == checkTypeInference()) {
throw new replacedertionError(samSourceFile + "\n\n" + clientSourceFile + "\n" + parameterType + " " + returnType);
}
}
19
Source : StructuralMostSpecificTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public void run() {
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), diagChecker, Arrays.asList("-XDverboseResolution=all,-predef,-internal,-object-init"), null, Arrays.asList(source));
try {
ct.replacedyze();
} catch (Throwable ex) {
throw new replacedertionError("Error thron when replacedyzing the following source:\n" + source.getCharContent(true));
}
check();
}
19
Source : MethodReferenceParserTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
@Override
public void run() {
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source));
try {
ct.parse();
} catch (Throwable ex) {
processException(ex);
return;
}
check();
}
19
Source : SamConversionComboTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
void test() throws Exception {
System.out.println("\n====================================");
System.out.println(fInterface + ", " + context + ", " + methodReference);
System.out.println(samSourceFile + "\n" + clientSourceFile);
DiagnosticChecker dc = new DiagnosticChecker();
JavacTask ct = (JavacTask) comp.getTask(null, fm, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
ct.replacedyze();
if (dc.errorFound == checkSamConversion()) {
throw new replacedertionError(samSourceFile + "\n\n" + clientSourceFile);
}
count++;
}
19
Source : LambdaParserTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public void run() {
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source));
try {
ct.parse();
} catch (Throwable ex) {
processException(ex);
return;
}
check();
}
19
Source : GenericOverrideTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
@Override
public void run() {
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), diagChecker, level.opts != null ? Arrays.asList(level.opts) : null, null, Arrays.asList(source));
try {
ct.replacedyze();
} catch (Throwable ex) {
throw new replacedertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true));
}
check();
}
19
Source : DiamondAndInnerClassTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
@Override
public void run() {
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source));
try {
ct.replacedyze();
} catch (Throwable ex) {
throw new replacedertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true));
}
check();
}
19
Source : CheckAttributedTree.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
/**
* Read a file.
* @param file the file to be read
* @return the tree for the content of the file
* @throws IOException if any IO errors occur
* @throws TreePosTest.ParseException if any errors occur while parsing the file
*/
List<Pair<JCCompilationUnit, JCTree>> read(File file) throws IOException, AttributionException {
r.errors = 0;
Iterable<? extends JavaFileObject> files = fm.get().getJavaFileObjects(file);
String[] opts = { "-XDshouldStopPolicy=ATTR", "-XDverboseCompilePolicy" };
JavacTask task = (JavacTask) comp.getTask(pw, fm.get(), r, Arrays.asList(opts), null, files);
final List<Element> replacedyzedElems = new ArrayList<>();
task.setTaskListener(new TaskListener() {
public void started(TaskEvent e) {
if (e.getKind() == TaskEvent.Kind.replacedYZE)
replacedyzedElems.add(e.getTypeElement());
}
public void finished(TaskEvent e) {
}
});
try {
Iterable<? extends CompilationUnitTree> trees = task.parse();
task.replacedyze();
List<Pair<JCCompilationUnit, JCTree>> res = new ArrayList<>();
// System.out.println("Try to add pairs. Elems are " + replacedyzedElems);
for (CompilationUnitTree t : trees) {
JCCompilationUnit cu = (JCCompilationUnit) t;
for (JCTree def : cu.defs) {
if (def.hasTag(CLreplacedDEF) && replacedyzedElems.contains(((JCTree.JCClreplacedDecl) def).sym)) {
// System.out.println("Adding pair...");
res.add(new Pair<>(cu, def));
}
}
}
return res;
} catch (Throwable t) {
throw new AttributionException("Exception while attributing file: " + file);
}
}
19
Source : TestDefaultSuperCall.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public void run() {
JavacTask ct = (JavacTask) comp.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source));
try {
ct.replacedyze();
} catch (Throwable ex) {
processException(ex);
return;
}
check();
}
19
Source : TestSimpleAddRemove.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
static void removeInListener(final JavacTask task, final TaskEvent.Kind kind, final TaskListener listener) {
task.addTaskListener(new TaskListener() {
public void started(TaskEvent e) {
if (e.getKind() == kind) {
task.removeTaskListener(listener);
task.removeTaskListener(this);
}
}
public void finished(TaskEvent e) {
}
});
}
19
Source : TestSimpleAddRemove.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
static void addInListener(final JavacTask task, final TaskEvent.Kind kind, final TaskListener listener) {
task.addTaskListener(new TaskListener() {
public void started(TaskEvent e) {
if (e.getKind() == kind) {
task.addTaskListener(listener);
task.removeTaskListener(this);
}
}
public void finished(TaskEvent e) {
}
});
}
19
Source : T6557752.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public clreplaced T6557752 {
static clreplaced MyFileObject extends SimpleJavaFileObject {
public MyFileObject() {
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return "import java.util.*;\n" + "public clreplaced Test {\n" + " void foobar() {\n" + " Iterator<Number> itr = null;\n" + " String str = itr.next();\n" + " FooBar fooBar = FooBar.foobar();\n" + " }\n" + "}";
}
}
static Trees trees;
static JavacTask task = null;
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
Iterable<? extends CompilationUnitTree> asts = task.parse();
task.replacedyze();
trees = Trees.instance(task);
MyVisitor myVisitor = new MyVisitor();
for (CompilationUnitTree ast : asts) {
myVisitor.compilationUnit = ast;
myVisitor.scan(ast, null);
}
if (!myVisitor.foundError) {
throw new replacedertionError("Expected error not found!");
}
}
static clreplaced MyVisitor extends TreePathScanner<Void, Void> {
public boolean foundError = false;
CompilationUnitTree compilationUnit = null;
int i = 0;
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void ignored) {
TreePath path = TreePath.getPath(compilationUnit, node);
TypeMirror typeMirror = trees.getTypeMirror(path);
if (typeMirror.getKind() == TypeKind.ERROR) {
if (i == 0) {
String str1 = trees.getOriginalType((ErrorType) typeMirror).toString();
if (!str1.equals("java.lang.Number")) {
throw new replacedertionError("Trees.getOriginalType() error!");
}
Types types = task.getTypes();
str1 = types.asElement(trees.getOriginalType((ErrorType) typeMirror)).toString();
if (!str1.equals("java.lang.Number")) {
throw new replacedertionError("Types.asElement() error!");
}
i++;
} else if (i == 1) {
String str1 = trees.getOriginalType((ErrorType) typeMirror).toString();
if (!str1.equals("FooBar")) {
throw new replacedertionError("Trees.getOriginalType() error!");
}
Types types = task.getTypes();
str1 = types.asElement(trees.getOriginalType((ErrorType) typeMirror)).toString();
if (!str1.equals("FooBar")) {
throw new replacedertionError("Types.asElement() error!");
}
foundError = true;
}
}
return null;
}
}
}
19
Source : DocEnv.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
void initDoclint(Collection<String> opts, Collection<String> customTagNames) {
ArrayList<String> doclintOpts = new ArrayList<String>();
for (String opt : opts) {
doclintOpts.add(opt == null ? DocLint.XMSGS_OPTION : DocLint.XMSGS_CUSTOM_PREFIX + opt);
}
if (doclintOpts.isEmpty()) {
doclintOpts.add(DocLint.XMSGS_OPTION);
} else if (doclintOpts.size() == 1 && doclintOpts.get(0).equals(DocLint.XMSGS_CUSTOM_PREFIX + "none")) {
return;
}
String sep = "";
StringBuilder customTags = new StringBuilder();
for (String customTag : customTagNames) {
customTags.append(sep);
customTags.append(customTag);
sep = DocLint.TAGS_SEPARATOR;
}
doclintOpts.add(DocLint.XCUSTOM_TAGS_PREFIX + customTags.toString());
JavacTask t = BasicJavacTask.instance(context);
doclint = new DocLint();
// standard doclet normally generates H1, H2
doclintOpts.add(DocLint.XIMPLICIT_HEADERS + "2");
doclint.init(t, doclintOpts.toArray(new String[doclintOpts.size()]), false);
}
19
Source : AbstractCodingRulesAnalyzer.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public void init(JavacTask task, String... args) {
BasicJavacTask impl = (BasicJavacTask) task;
Context context = impl.getContext();
log = Log.instance(context);
trees = Trees.instance(task);
messages = new Messages();
task.addTaskListener(new PostreplacedyzeTaskListener());
}
19
Source : StaticLoad.java
with Apache License 2.0
from multi-os-engine
with Apache License 2.0
from multi-os-engine
@Override
public void init(JavacTask javacTask, String... args) {
context = ((BasicJavacTask) javacTask).getContext();
names = Names.instance(context);
maker = TreeMaker.instance(context);
javacTask.addTaskListener(new TaskListener() {
@Override
public void finished(TaskEvent taskEvent) {
// Using a TreeScanner might be somewhat simpler, but would not be as precise.
taskEvent.getCompilationUnit().getTypeDecls().stream().filter(decl -> decl instanceof JCTree.JCClreplacedDecl).forEach(decl -> ((JCTree.JCClreplacedDecl) decl).getMembers().stream().filter(member -> member instanceof JCTree.JCMethodDecl || member instanceof JCTree.JCBlock).forEach(method -> method.accept(scanner, StaticLoad.this)));
}
@Override
public void started(TaskEvent arg0) {
// Nothing to do.
}
});
}
19
Source : JavaParser.java
with Apache License 2.0
from micronaut-projects
with Apache License 2.0
from micronaut-projects
/**
* Parses {@code sources} into {@code CompilationUnitTree} units. This method
* <b>does not</b> compile the sources.
*
* @param sources The sources
* @return The elements
*/
public Iterable<? extends Element> parse(JavaFileObject... sources) {
Set<String> options = getCompilerOptions();
JavacTask task = ((JavacTool) compiler).getTask(// explicitly use the default because old javac logs some output on stderr
null, fileManager, diagnosticCollector, options, Collections.emptySet(), Arrays.asList(sources), context);
try {
task.parse();
return task.replacedyze();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
System.out.println(diagnostic);
if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
throw new RuntimeException(diagnostic.toString());
}
}
}
}
19
Source : JavacPluginBootstrap.java
with Apache License 2.0
from manifold-systems
with Apache License 2.0
from manifold-systems
@Override
public void init(JavacTask task, String... args) {
_delegate.init(task, args);
}
19
Source : BaseClassesNotReRead.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
void run() throws IOException {
File sources = new File(System.getProperty("test.src"));
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(new File(sources, "BaseClreplacedesNotReReadSource.java"));
DiagnosticListener<JavaFileObject> noErrors = new DiagnosticListener<JavaFileObject>() {
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
throw new IllegalStateException(diagnostic.toString());
}
};
JavaFileManager manager = new OnlyOneReadFileManager(fm);
Iterable<String> options = Arrays.asList("-processor", "BaseClreplacedesNotReRead");
JavacTask task = (JavacTask) compiler.getTask(null, manager, noErrors, options, null, files);
task.replacedyze();
}
}
19
Source : TestPackageInfoComments.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
static void run_test(String[] opts, File[] files) throws IOException {
DiagnosticListener<JavaFileObject> dl = new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic diagnostic) {
throw new Error(diagnostic.toString());
}
};
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
Iterable<? extends JavaFileObject> units = fm.getJavaFileObjects(files);
JavacTask t = (JavacTask) c.getTask(null, fm, dl, Arrays.asList(opts), null, units);
t.parse();
t.replacedyze();
}
}
19
Source : Main.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
public clreplaced Main {
public static PackageElement getPackage(TypeElement type) {
Element owner = type;
while (owner.getKind() != ElementKind.PACKAGE) owner = owner.getEnclosingElement();
return (PackageElement) owner;
}
static int progress = 0;
static JavaCompiler tool;
static JavacTask javac;
static Elements elements;
static List<String> addmods_ALL_SYSTEM = Arrays.asList("--add-modules", "ALL-SYSTEM");
public static void main(String[] args) throws Exception {
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
fm.setLocation(CLreplaced_PATH, Collections.<File>emptyList());
JavacTask javac = (JavacTask) tool.getTask(null, fm, null, addmods_ALL_SYSTEM, null, null);
Elements elements = javac.getElements();
final Map<String, Set<String>> packages = new LinkedHashMap<>();
int nestedClreplacedes = 0;
int clreplacedes = 0;
for (JavaFileObject file : fm.list(PLATFORM_CLreplaced_PATH, "", EnumSet.of(CLreplaced), true)) {
String type = fm.inferBinaryName(PLATFORM_CLreplaced_PATH, file);
if (type.endsWith("package-info"))
continue;
if (type.endsWith("module-info"))
continue;
Path path = fm.asPath(file);
int moduleIndex = path.getNameCount() - type.split("\\Q.\\E").length - 1;
String moduleName = path.getName(moduleIndex).toString();
if (// incubator modules not in module graph by default
moduleName.startsWith("jdk.incubator."))
continue;
try {
ModuleElement me = elements.getModuleElement(moduleName);
me.getClreplaced();
TypeElement elem = ((JavacElements) elements).getTypeElement(me, type);
if (elem == null && type.indexOf('$') > 0) {
nestedClreplacedes++;
type = null;
continue;
}
clreplacedes++;
String pack = getPackage(elem).getQualifiedName().toString();
packages.computeIfAbsent(me.getQualifiedName().toString(), m -> new LinkedHashSet<>()).add(pack);
// force completion
elem.getKind();
type = null;
} finally {
if (type != null)
System.err.println("Looking at " + type);
}
}
javac = null;
elements = null;
javac = (JavacTask) tool.getTask(null, fm, null, addmods_ALL_SYSTEM, null, null);
elements = javac.getElements();
for (Entry<String, Set<String>> module2Packages : packages.entrySet()) {
ModuleElement me = elements.getModuleElement(module2Packages.getKey());
me.getClreplaced();
for (String name : module2Packages.getValue()) {
PackageElement pe = ((JavacElements) elements).getPackageElement(me, name);
for (Element e : pe.getEnclosedElements()) {
e.getSimpleName().getClreplaced();
}
}
}
/*
* A few sanity checks based on current values:
*
* packages: 775, clreplacedes: 12429 + 5917
*
* As the platform evolves the numbers are likely to grow
* monotonically but in case somebody gets a clever idea for
* limiting the number of packages exposed, this number might
* drop. So we test low values.
*/
System.out.format("packages: %s, clreplacedes: %s + %s%n", packages.size(), clreplacedes, nestedClreplacedes);
if (clreplacedes < 9000)
throw new replacedertionError("Too few clreplacedes in PLATFORM_CLreplaced_PATH ;-)");
if (packages.values().stream().flatMap(packs -> packs.stream()).count() < 530)
throw new replacedertionError("Too few packages in PLATFORM_CLreplaced_PATH ;-)");
if (nestedClreplacedes < 3000)
throw new replacedertionError("Too few nested clreplacedes in PLATFORM_CLreplaced_PATH ;-)");
}
}
}
19
Source : TestClose2.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
void run() throws IOException {
File testSrc = new File(System.getProperty("test.src"));
File testClreplacedes = new File(System.getProperty("test.clreplacedes"));
JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
final ClreplacedLoader cl = getClreplaced().getClreplacedLoader();
Context c = new Context();
StandardJavaFileManager fm = new JavacFileManager(c, true, null) {
@Override
protected ClreplacedLoader getClreplacedLoader(URL[] urls) {
return new URLClreplacedLoader(urls, cl) {
@Override
public void close() throws IOException {
System.err.println(getClreplaced().getName() + " closing");
TestClose2.this.closedCount++;
TestClose2.this.closedIsLast = true;
super.close();
}
};
}
};
fm.setLocation(StandardLocation.CLreplaced_OUTPUT, Collections.singleton(new File(".")));
fm.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH, Collections.singleton(testClreplacedes));
Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(new File(testSrc, TestClose2.clreplaced.getName() + ".java"));
List<String> options = Arrays.asList("--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", "--add-exports", "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", "--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", "-processor", TestClose2.clreplaced.getName());
JavacTask task = tool.getTask(null, fm, null, options, null, files);
task.setTaskListener(this);
if (!task.call())
throw new Error("compilation failed");
if (closedCount == 0)
throw new Error("no closing message");
else if (closedCount > 1)
throw new Error(closedCount + " closed messages");
if (!closedIsLast)
throw new Error("closing message not last");
}
19
Source : ComboTask.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
/**
* This clreplaced represents a compilation task replacedociated with a combo test instance. This is a small
* wrapper around {@link JavacTask} which allows for fluent setup style and which makes use of
* the shared compilation context to speedup performances.
*/
public clreplaced ComboTask {
/**
* Sources to be compiled in this task.
*/
private List<JavaFileObject> sources = List.nil();
/**
* Options replacedociated with this task.
*/
private List<String> options = List.nil();
/**
* Diagnostic collector.
*/
private DiagnosticCollector diagsCollector = new DiagnosticCollector();
/**
* Output writer.
*/
private Writer out;
/**
* Listeners replacedociated with this task.
*/
private List<TaskListener> listeners = List.nil();
/**
* Underlying javac task object.
*/
private JavacTask task;
/**
* Combo execution environment.
*/
private ComboTestHelper<?>.Env env;
ComboTask(ComboTestHelper<?>.Env env) {
this.env = env;
}
/**
* Add a new source to this task.
*/
public ComboTask withSource(JavaFileObject comboSource) {
sources = sources.prepend(comboSource);
return this;
}
/**
* Add a new template source with given name to this task; the template is replaced with
* corresponding combo parameters (as defined in the combo test environment).
*/
public ComboTask withSourceFromTemplate(String name, String template) {
return withSource(new ComboTemplateSource(name, template));
}
/**
* Add a new template source with default name ("Test") to this task; the template is replaced with
* corresponding combo parameters (as defined in the combo test environment).
*/
public ComboTask withSourceFromTemplate(String template) {
return withSource(new ComboTemplateSource("Test", template));
}
/**
* Add a new template source with given name to this task; the template is replaced with
* corresponding combo parameters (as defined in the combo test environment). A custom resolver
* is used to add combo parameter mappings to the current combo test environment.
*/
public ComboTask withSourceFromTemplate(String name, String template, Resolver resolver) {
return withSource(new ComboTemplateSource(name, template, resolver));
}
/**
* Add a new template source with default name ("Test") to this task; the template is replaced with
* corresponding combo parameters (as defined in the combo test environment). A custom resolver
* is used to add combo parameter mappings to the current combo test environment.
*/
public ComboTask withSourceFromTemplate(String template, Resolver resolver) {
return withSource(new ComboTemplateSource("Test", template, resolver));
}
/**
* Add a new option to this task.
*/
public ComboTask withOption(String opt) {
options = options.append(opt);
return this;
}
/**
* Add a set of options to this task.
*/
public ComboTask withOptions(String[] opts) {
for (String opt : opts) {
options = options.append(opt);
}
return this;
}
/**
* Add a set of options to this task.
*/
public ComboTask withOptions(Iterable<? extends String> opts) {
for (String opt : opts) {
options = options.append(opt);
}
return this;
}
/**
* Set the output writer replacedociated with this task.
*/
public ComboTask withWriter(Writer out) {
this.out = out;
return this;
}
/**
* Add a task listener to this task.
*/
public ComboTask withListener(TaskListener listener) {
listeners = listeners.prepend(listener);
return this;
}
/**
* Parse the sources replacedociated with this task.
*/
public Result<Iterable<? extends CompilationUnitTree>> parse() throws IOException {
return new Result<>(getTask().parse());
}
/**
* Parse and replacedyzes the sources replacedociated with this task.
*/
public Result<Iterable<? extends Element>> replacedyze() throws IOException {
return new Result<>(getTask().replacedyze());
}
/**
* Parse, replacedyze and perform code generation for the sources replacedociated with this task.
*/
public Result<Iterable<? extends JavaFileObject>> generate() throws IOException {
return new Result<>(getTask().generate());
}
/**
* Parse, replacedyze, perform code generation for the sources replacedociated with this task and finally
* executes them
*/
public <Z> Optional<Z> execute(Function<ExecutionTask, Z> executionFunc) throws IOException {
Result<Iterable<? extends JavaFileObject>> generationResult = generate();
Iterable<? extends JavaFileObject> jfoIterable = generationResult.get();
if (generationResult.hasErrors()) {
// we have nothing else to do
return Optional.empty();
}
java.util.List<URL> urlList = new ArrayList<>();
for (JavaFileObject jfo : jfoIterable) {
String urlStr = jfo.toUri().toURL().toString();
urlStr = urlStr.substring(0, urlStr.length() - jfo.getName().length());
urlList.add(new URL(urlStr));
}
return Optional.of(executionFunc.apply(new ExecutionTask(new URLClreplacedLoader(urlList.toArray(new URL[urlList.size()])))));
}
/**
* Fork a new compilation task; if possible the compilation context from previous executions is
* retained (see comments in ReusableContext as to when it's safe to do so); otherwise a brand
* new context is created.
*/
public JavacTask getTask() {
if (task == null) {
ReusableContext context = env.context();
String opts = options == null ? "" : StreamSupport.stream(options.spliterator(), false).collect(Collectors.joining());
context.clear();
if (!context.polluted && (context.opts == null || context.opts.equals(opts))) {
// we can reuse former context
env.info().ctxReusedCount++;
} else {
env.info().ctxDroppedCount++;
// it's not safe to reuse context - create a new one
context = env.setContext(new ReusableContext());
}
context.opts = opts;
JavacTask javacTask = ((JavacTool) env.javaCompiler()).getTask(out, env.fileManager(), diagsCollector, options, null, sources, context);
javacTask.setTaskListener(context);
for (TaskListener l : listeners) {
javacTask.addTaskListener(l);
}
task = javacTask;
}
return task;
}
/**
* This clreplaced represents an execution task. It allows the execution of one or more clreplacedes previously
* added to a given clreplaced loader. This clreplaced uses reflection to execute any given static public method
* in any given clreplaced. It's not restricted to the execution of the {@code main} method
*/
public clreplaced ExecutionTask {
private ClreplacedLoader clreplacedLoader;
private String methodName = "main";
private Clreplaced<?>[] parameterTypes = new Clreplaced<?>[] { String[].clreplaced };
private Object[] args = new String[0];
private Consumer<Throwable> handler;
private Clreplaced<?> c;
private ExecutionTask(ClreplacedLoader clreplacedLoader) {
this.clreplacedLoader = clreplacedLoader;
}
/**
* Set the name of the clreplaced to be loaded.
*/
public ExecutionTask withClreplaced(String clreplacedName) {
replacedert.check(clreplacedName != null, "clreplaced name value is null, impossible to proceed");
try {
c = clreplacedLoader.loadClreplaced(clreplacedName);
} catch (Throwable t) {
throw new IllegalStateException(t);
}
return this;
}
/**
* Set the name of the method to be executed along with the parameter types to
* reflectively obtain the method.
*/
public ExecutionTask withMethod(String methodName, Clreplaced<?>... parameterTypes) {
this.methodName = methodName;
this.parameterTypes = parameterTypes;
return this;
}
/**
* Set the arguments to be preplaceded to the method.
*/
public ExecutionTask withArguments(Object... args) {
this.args = args;
return this;
}
/**
* Set a handler to handle any exception thrown.
*/
public ExecutionTask withHandler(Consumer<Throwable> handler) {
this.handler = handler;
return this;
}
/**
* Executes the given method in the given clreplaced. Returns true if the execution was
* successful, false otherwise.
*/
public Object run() {
try {
java.lang.reflect.Method meth = c.getMethod(methodName, parameterTypes);
meth.invoke(null, (Object) args);
return true;
} catch (Throwable t) {
if (handler != null) {
handler.accept(t);
}
return false;
}
}
}
/**
* This clreplaced is used to help clients accessing the results of a given compilation task.
* Contains several helper methods to inspect diagnostics generated during the task execution.
*/
public clreplaced Result<D> {
/**
* The underlying compilation results.
*/
private final D data;
public Result(D data) {
this.data = data;
}
public D get() {
return data;
}
/**
* Did this task generate any error diagnostics?
*/
public boolean hasErrors() {
return diagsCollector.diagsByKind.containsKey(Diagnostic.Kind.ERROR);
}
/**
* Did this task generate any warning diagnostics?
*/
public boolean hasWarnings() {
return diagsCollector.diagsByKind.containsKey(Diagnostic.Kind.WARNING);
}
/**
* Did this task generate any note diagnostics?
*/
public boolean hasNotes() {
return diagsCollector.diagsByKind.containsKey(Diagnostic.Kind.NOTE);
}
/**
* Did this task generate any diagnostic with given key?
*/
public boolean containsKey(String key) {
return diagsCollector.diagsByKeys.containsKey(key);
}
/**
* Retrieve the list of diagnostics of a given kind.
*/
public List<Diagnostic<? extends JavaFileObject>> diagnosticsForKind(Diagnostic.Kind kind) {
List<Diagnostic<? extends JavaFileObject>> diags = diagsCollector.diagsByKind.get(kind);
return diags != null ? diags : List.nil();
}
/**
* Retrieve the list of diagnostics with given key.
*/
public List<Diagnostic<? extends JavaFileObject>> diagnosticsForKey(String key) {
List<Diagnostic<? extends JavaFileObject>> diags = diagsCollector.diagsByKeys.get(key);
return diags != null ? diags : List.nil();
}
/**
* Dump useful info replacedociated with this task.
*/
public String compilationInfo() {
return "instance#" + env.info().comboCount + ":[ options = " + options + ", diagnostics = " + diagsCollector.diagsByKeys.keySet() + ", dimensions = " + env.bindings + ", sources = \n" + sources.stream().map(s -> {
try {
return s.getCharContent(true);
} catch (IOException ex) {
return "";
}
}).collect(Collectors.joining(",")) + "]";
}
}
/**
* This clreplaced represents a Java source file whose contents are defined in terms of a template
* string. The holes in such template are expanded using corresponding combo parameter
* instances which can be retrieved using a resolver object.
*/
clreplaced ComboTemplateSource extends SimpleJavaFileObject {
String source;
Map<String, ComboParameter> localParametersCache = new HashMap<>();
protected ComboTemplateSource(String name, String template) {
this(name, template, null);
}
protected ComboTemplateSource(String name, String template, Resolver resolver) {
super(URI.create("myfo:/" + env.info().comboCount + "/" + name + ".java"), Kind.SOURCE);
source = ComboParameter.expandTemplate(template, pname -> resolveParameter(pname, resolver));
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return source;
}
/**
* Combo parameter resolver function. First parameters are looked up in the global environment,
* then the local environment is looked up as a fallback.
*/
ComboParameter resolveParameter(String pname, Resolver resolver) {
// first search the env
ComboParameter parameter = env.parametersCache.get(pname);
if (parameter == null) {
// then lookup local cache
parameter = localParametersCache.get(pname);
if (parameter == null && resolver != null) {
// if still null and we have a custom resolution function, try that
parameter = resolver.lookup(pname);
if (parameter != null) {
// if a match was found, store it in the local cache to aviod redundant recomputation
localParametersCache.put(pname, parameter);
}
}
}
return parameter;
}
}
/**
* Helper clreplaced to collect all diagnostic generated during the execution of a given compilation task.
*/
clreplaced DiagnosticCollector implements DiagnosticListener<JavaFileObject> {
Map<Diagnostic.Kind, List<Diagnostic<? extends JavaFileObject>>> diagsByKind = new HashMap<>();
Map<String, List<Diagnostic<? extends JavaFileObject>>> diagsByKeys = new HashMap<>();
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
List<Diagnostic<? extends JavaFileObject>> diags = diagsByKeys.getOrDefault(diagnostic.getCode(), List.nil());
diagsByKeys.put(diagnostic.getCode(), diags.prepend(diagnostic));
Diagnostic.Kind kind = diagnostic.getKind();
diags = diagsByKind.getOrDefault(kind, List.nil());
diagsByKind.put(kind, diags.prepend(diagnostic));
}
}
}
19
Source : ComboTask.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
/**
* Fork a new compilation task; if possible the compilation context from previous executions is
* retained (see comments in ReusableContext as to when it's safe to do so); otherwise a brand
* new context is created.
*/
public JavacTask getTask() {
if (task == null) {
ReusableContext context = env.context();
String opts = options == null ? "" : StreamSupport.stream(options.spliterator(), false).collect(Collectors.joining());
context.clear();
if (!context.polluted && (context.opts == null || context.opts.equals(opts))) {
// we can reuse former context
env.info().ctxReusedCount++;
} else {
env.info().ctxDroppedCount++;
// it's not safe to reuse context - create a new one
context = env.setContext(new ReusableContext());
}
context.opts = opts;
JavacTask javacTask = ((JavacTool) env.javaCompiler()).getTask(out, env.fileManager(), diagsCollector, options, null, sources, context);
javacTask.setTaskListener(context);
for (TaskListener l : listeners) {
javacTask.addTaskListener(l);
}
task = javacTask;
}
return task;
}
19
Source : SamConversionComboTest.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
void test() throws Exception {
System.out.println("\n====================================");
System.out.println(fInterface + ", " + context + ", " + lambdaKind + ", " + lambdaBody + ", " + returnValue);
System.out.println(samSourceFile + "\n");
String clientFileStr = clientSourceFile.toString();
System.out.println(clientFileStr.substring(0, clientFileStr.indexOf("\n\n")));
DiagnosticChecker dc = new DiagnosticChecker();
JavacTask ct = (JavacTask) comp.getTask(null, fm, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
try {
ct.replacedyze();
} catch (Exception e) {
throw new replacedertionError("failing SAM source file \n" + samSourceFile + "\n\n" + "failing client source file \n" + clientSourceFile);
}
if (dc.errorFound == checkSamConversion()) {
throw new replacedertionError(samSourceFile + "\n\n" + clientSourceFile);
}
count++;
}
19
Source : VerifyErroneousAnnotationsAttributed.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
void validate(String code) throws IOException, URISyntaxException {
JavacTask task = tool.getTask(null, fm, devNull, Arrays.asList("--should-stop:at=FLOW"), null, Arrays.asList(new MyFileObject(code)));
final Trees trees = Trees.instance(task);
final CompilationUnitTree cut = task.parse().iterator().next();
task.replacedyze();
// ensure all the annotation attributes are annotated meaningfully
// all the attributes in the test file should contain either an identifier
// or a select, so only checking those for a reasonable Element/Symbol.
new TreePathScanner<Void, Void>() {
@Override
public Void visitIdentifier(IdentifierTree node, Void p) {
verifyAttributedMeaningfully();
return super.visitIdentifier(node, p);
}
@Override
public Void visitMemberSelect(MemberSelectTree node, Void p) {
verifyAttributedMeaningfully();
return super.visitMemberSelect(node, p);
}
private void verifyAttributedMeaningfully() {
Element el = trees.getElement(getCurrentPath());
if (el == null || el.getKind() == ElementKind.OTHER || el.asType().getKind() == TypeKind.OTHER) {
throw new IllegalStateException("Not attributed properly: " + getCurrentPath().getParentPath().getLeaf());
}
}
}.scan(cut, null);
}
19
Source : JavadocHelperTest.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
private Element getFirstMethod(JavacTask task, String typeName) {
return ElementFilter.methodsIn(task.getElements().getTypeElement(typeName).getEnclosedElements()).get(0);
}
19
Source : JavadocFormatter.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
/**
* Format javadoc to plain text.
*
* @param header element caption that should be used
* @param javadoc to format
* @return javadoc formatted to plain text
*/
public String formatJavadoc(String header, String javadoc) {
try {
StringBuilder result = new StringBuilder();
result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n");
if (javadoc == null) {
return result.toString();
}
JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null);
DocTrees trees = DocTrees.instance(task);
DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) {
@Override
@DefinedBy(Api.COMPILER)
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return "<body>" + javadoc + "</body>";
}
});
new FormatJavadocScanner(result, task).scan(docComment, null);
addNewLineIfNeeded(result);
return result.toString();
} catch (URISyntaxException ex) {
throw new InternalError("Unexpected exception", ex);
}
}
19
Source : DocLint.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Embedding API">
public void init(JavacTask task, String[] args, boolean addTaskListener) {
env = new Env();
for (String arg : args) {
if (arg.equals(XMSGS_OPTION)) {
env.messages.setOptions(null);
} else if (arg.startsWith(XMSGS_CUSTOM_PREFIX)) {
env.messages.setOptions(arg.substring(arg.indexOf(":") + 1));
} else if (arg.matches(XIMPLICIT_HEADERS + "[1-6]")) {
char ch = arg.charAt(arg.length() - 1);
env.setImplicitHeaders(Character.digit(ch, 10));
} else if (arg.startsWith(XCUSTOM_TAGS_PREFIX)) {
env.setCustomTags(arg.substring(arg.indexOf(":") + 1));
} else if (arg.startsWith(XHTML_VERSION_PREFIX)) {
String argsVersion = arg.substring(arg.indexOf(":") + 1);
HtmlVersion htmlVersion = HtmlVersion.getHtmlVersion(argsVersion);
if (htmlVersion != null) {
env.setHtmlVersion(htmlVersion);
} else {
throw new IllegalArgumentException(argsVersion);
}
} else if (arg.startsWith(XCHECK_PACKAGE)) {
env.setCheckPackages(arg.substring(arg.indexOf(":") + 1));
} else
throw new IllegalArgumentException(arg);
}
env.init(task);
checker = new Checker(env);
if (addTaskListener) {
final DeclScanner ds = new DeclScanner(env) {
@Override
void visitDecl(Tree tree, Name name) {
TreePath p = getCurrentPath();
DocCommentTree dc = env.trees.getDocCommentTree(p);
checker.scan(dc, p);
}
};
TaskListener tl = new TaskListener() {
@Override
@DefinedBy(Api.COMPILER_TREE)
public void started(TaskEvent e) {
switch(e.getKind()) {
case replacedYZE:
CompilationUnitTree tree;
while ((tree = todo.poll()) != null) ds.scan(tree, null);
break;
}
}
@Override
@DefinedBy(Api.COMPILER_TREE)
public void finished(TaskEvent e) {
switch(e.getKind()) {
case PARSE:
todo.add(e.getCompilationUnit());
break;
}
}
Queue<CompilationUnitTree> todo = new LinkedList<>();
};
task.addTaskListener(tl);
}
}
19
Source : CodingRulesAnalyzerPlugin.java
with GNU General Public License v2.0
from hzio
with GNU General Public License v2.0
from hzio
@DefinedBy(Api.COMPILER_TREE)
public void init(JavacTask task, String... args) {
BasicJavacTask impl = (BasicJavacTask) task;
Context context = impl.getContext();
log = Log.instance(context);
trees = Trees.instance(task);
task.addTaskListener(new PostreplacedyzeTaskListener(new MutableFieldsreplacedyzer(task), new replacedertCheckreplacedyzer(task), new DefinedByreplacedyzer(task), new LegacyLogMethodreplacedyzer(task)));
}
19
Source : DocLint.java
with GNU General Public License v2.0
from eppleton
with GNU General Public License v2.0
from eppleton
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Embedding API">
public void init(JavacTask task, String[] args, boolean addTaskListener) {
env = new Env();
for (String arg : args) {
if (arg.equals(XMSGS_OPTION)) {
env.messages.setOptions(null);
} else if (arg.startsWith(XMSGS_CUSTOM_PREFIX)) {
env.messages.setOptions(arg.substring(arg.indexOf(":") + 1));
} else if (arg.startsWith(XCUSTOM_TAGS_PREFIX)) {
env.setCustomTags(arg.substring(arg.indexOf(":") + 1));
} else if (arg.startsWith(XHTML_VERSION_PREFIX)) {
String argsVersion = arg.substring(arg.indexOf(":") + 1);
HtmlVersion htmlVersion = HtmlVersion.getHtmlVersion(argsVersion);
if (htmlVersion != null) {
env.setHtmlVersion(htmlVersion);
} else {
throw new IllegalArgumentException(argsVersion);
}
} else if (arg.startsWith(XCHECK_PACKAGE)) {
env.setCheckPackages(arg.substring(arg.indexOf(":") + 1));
} else
throw new IllegalArgumentException(arg);
}
env.init(task);
checker = new Checker(env);
if (addTaskListener) {
final DeclScanner ds = new DeclScanner(env) {
@Override
void visitDecl(Tree tree, Name name) {
TreePath p = getCurrentPath();
DocCommentTree dc = env.trees.getDocCommentTree(p);
checker.scan(dc, p);
}
};
TaskListener tl = new TaskListener() {
@Override
@DefinedBy(Api.COMPILER_TREE)
public void started(TaskEvent e) {
switch(e.getKind()) {
case replacedYZE:
CompilationUnitTree tree;
while ((tree = todo.poll()) != null) ds.scan(tree, null);
break;
}
}
@Override
@DefinedBy(Api.COMPILER_TREE)
public void finished(TaskEvent e) {
switch(e.getKind()) {
case PARSE:
todo.add(e.getCompilationUnit());
break;
}
}
Queue<CompilationUnitTree> todo = new LinkedList<>();
};
task.addTaskListener(tl);
}
}
19
Source : TrauteJavacPlugin.java
with MIT License
from denis-zhdanov
with MIT License
from denis-zhdanov
@Override
public void init(JavacTask task, String... args) {
if (!(task instanceof BasicJavacTask)) {
throw new RuntimeException(AbstractLogger.getProblemMessage(String.format("get an instance of type %s in init() method but got %s (%s)", BasicJavacTask.clreplaced.getName(), task.getClreplaced().getName(), task)));
}
Context context = ((BasicJavacTask) task).getContext();
AtomicBoolean contextClosed = new AtomicBoolean();
TrautePluginSettings settings = getPluginSettings(context);
pluginSettingsRef.set(settings);
task.addTaskListener(new TaskListener() {
@Override
public void started(TaskEvent event) {
if (event.getKind() != TaskEvent.Kind.ENTER || isContextClosed()) {
// The idea is to add our checks just after the parser builds an AST. Further on the code
// will also be replacedyzed for errors and included into resulting binary.
// We don't apply the instrumentations after TaskEvent.Kind.PARSE event because there is
// a possible case that there are package-level annotations like
// javax.annotation.ParametersAreNonnullByDefault in package-info.java. So, we need to build
// AST for all input files first and instrument only after that.
return;
}
Log log = Log.instance(context);
if (log == null) {
throw new RuntimeException(AbstractLogger.getProblemMessage("get a javac logger from the current javac context but got <null>"));
}
TrautePluginLogger logger = getPluginLogger(settings.getLogFile().orElse(null), log);
CompilationUnitTree compilationUnit = event.getCompilationUnit();
if (compilationUnit == null) {
logger.reportDetails("get a prepared compilation unit object but got <null>");
return;
}
TreeMaker treeMaker = TreeMaker.instance(context);
if (treeMaker == null) {
logger.reportDetails("get an AST factory from the current javac context but got <null>");
return;
}
Names names = Names.instance(context);
if (names == null) {
logger.reportDetails("get a name table from the current javac context but got <null>");
return;
}
TrautePluginSettings pluginSettings = pluginSettingsRef.get();
StatsCollector statsCollector = new StatsCollector();
try {
compilationUnit.accept(new InstrumentationApplianceFinder(new CompilationUnitProcessingContext(pluginSettings, treeMaker, names, logger, statsCollector, new ExceptionTextGeneratorManager(logger), packageInfoManager), parameterInstrumentator, methodInstrumentator), null);
if (pluginSettings.isVerboseMode()) {
printInstrumentationResults(compilationUnit.getSourceFile(), statsCollector, logger);
}
} catch (Throwable e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
log.rawError(-1, String.format("Unexpected exception occurred on attempt to perform NotNull instrumentation for %s:%n%s", event.getSourceFile(), writer));
}
}
@Override
public void finished(TaskEvent event) {
if (event.getKind() != TaskEvent.Kind.PARSE || isContextClosed()) {
return;
}
Log log = Log.instance(context);
if (log == null) {
throw new RuntimeException(AbstractLogger.getProblemMessage("get a javac logger from the current javac context but got <null>"));
}
TrautePluginLogger logger = getPluginLogger(settings.getLogFile().orElse(null), log);
CompilationUnitTree compilationUnit = event.getCompilationUnit();
if (compilationUnit == null) {
logger.reportDetails("get a prepared compilation unit object but got <null>");
return;
}
packageInfoManager.onCompilationUnit(compilationUnit);
}
/**
* We encountered a situation when target context is closed (internal state is {@code null}) but plugin's
* listener is called. That was the case for processing sources generated by an annotation processor.
* Unfortunately, there is no public API to check that, hence, we use this trick
* (see {@link Context#checkState(java.util.Map)}).
*
* @return {@code true} if current context is closed; {@code false} otherwise
*/
private boolean isContextClosed() {
if (contextClosed.get()) {
return true;
}
try {
Log.instance(context);
return false;
} catch (Exception e) {
contextClosed.set(true);
return true;
}
}
});
}
19
Source : CodingRulesAnalyzerPlugin.java
with GNU General Public License v2.0
from AdoptOpenJDK
with GNU General Public License v2.0
from AdoptOpenJDK
@DefinedBy(Api.COMPILER_TREE)
public void init(JavacTask task, String... args) {
BasicJavacTask impl = (BasicJavacTask) task;
Context context = impl.getContext();
log = Log.instance(context);
trees = Trees.instance(task);
task.addTaskListener(new PostreplacedyzeTaskListener(new MutableFieldsreplacedyzer(task), new replacedertCheckreplacedyzer(task), new DefinedByreplacedyzer(task)));
}
19
Source : FeaturePlugin.java
with Apache License 2.0
from acr31
with Apache License 2.0
from acr31
@Override
public void init(JavacTask task, String... args) {
Context context = ((BasicJavacTask) task).getContext();
task.addTaskListener(new TaskListener() {
@Override
public void finished(TaskEvent e) {
if (e.getKind() != TaskEvent.Kind.replacedYZE) {
return;
}
process(e, context);
}
});
}
18
Source : JavaSourceCheck.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
public void check() {
JavacTask javacTask = (JavacTask) compilationTask;
try {
Iterable<? extends CompilationUnitTree> result = javacTask.parse();
for (CompilationUnitTree tree : result) {
tree.accept(treeScanner, null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
18
Source : BasicJavacTask.java
with Apache License 2.0
from tzfun
with Apache License 2.0
from tzfun
public static JavacTask instance(Context context) {
JavacTask instance = context.get(JavacTask.clreplaced);
if (instance == null)
instance = new BasicJavacTask(context, true);
return instance;
}
18
Source : DocLint.java
with Apache License 2.0
from tzfun
with Apache License 2.0
from tzfun
@Override
public void init(JavacTask task, String... args) {
init(task, args, true);
}
18
Source : T7190862.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
private void compile(JavaCompiler comp) {
JavacTask ct = (JavacTask) comp.getTask(null, null, null, null, null, Arrays.asList(source));
try {
if (!ct.call()) {
throw new replacedertionError("Error thrown when compiling the following source:\n" + source.getCharContent(true));
}
} catch (Throwable ex) {
throw new replacedertionError("Error thrown when compiling the following source:\n" + source.getCharContent(true));
}
}
18
Source : VerifySuppressWarnings.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public static void main(String... args) throws IOException, URISyntaxException {
if (args.length != 1)
throw new IllegalStateException("Must provide clreplaced name!");
String testContent = null;
List<File> sourcePath = new ArrayList<>();
for (String sourcePaths : System.getProperty("test.src.path").split(":")) {
sourcePath.add(new File(sourcePaths));
}
JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
for (File sp : sourcePath) {
File inp = new File(sp, args[0]);
if (inp.canRead()) {
testContent = fm.getRegularFile(inp).getCharContent(true).toString();
}
}
if (testContent == null)
throw new IllegalStateException();
final List<Diagnostic<?>> diagnostics = new ArrayList<>();
DiagnosticListener<JavaFileObject> collectDiagnostics = new DiagnosticListener<JavaFileObject>() {
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
diagnostics.add(diagnostic);
}
};
JavaFileObject testFile = new TestFO(new URI("mem://" + args[0]), testContent);
JavacTask task = JavacTool.create().getTask(null, new TestFM(fm), collectDiagnostics, STANDARD_PARAMS, null, Arrays.asList(testFile));
final Trees trees = Trees.instance(task);
final CompilationUnitTree cut = task.parse().iterator().next();
task.replacedyze();
final List<int[]> declarationSpans = new ArrayList<>();
new TreeScanner<Void, Void>() {
@Override
public Void visitClreplaced(ClreplacedTree node, Void p) {
handleDeclaration(node);
return super.visitClreplaced(node, p);
}
@Override
public Void visitMethod(MethodTree node, Void p) {
handleDeclaration(node);
return super.visitMethod(node, p);
}
@Override
public Void visitVariable(VariableTree node, Void p) {
handleDeclaration(node);
return super.visitVariable(node, p);
}
@Override
public Void visitNewClreplaced(NewClreplacedTree node, Void p) {
if (node.getClreplacedBody() != null) {
scan(node.getClreplacedBody().getMembers(), null);
}
return null;
}
private void handleDeclaration(Tree node) {
int endPos = (int) trees.getSourcePositions().getEndPosition(cut, node);
if (endPos == (-1)) {
if (node.getKind() == Tree.Kind.METHOD && (((JCMethodDecl) node).getModifiers().flags & Flags.GENERATEDCONSTR) != 0) {
return;
}
throw new IllegalStateException();
}
declarationSpans.add(new int[] { (int) trees.getSourcePositions().getStartPosition(cut, node), endPos });
}
}.scan(cut, null);
for (final int[] declarationSpan : declarationSpans) {
final String suppressWarnings = "@SuppressWarnings({\"deprecation\", \"unchecked\", \"serial\"})";
final String updatedContent = testContent.substring(0, declarationSpan[0]) + suppressWarnings + testContent.substring(declarationSpan[0]);
final List<Diagnostic<?>> foundErrors = new ArrayList<>(diagnostics);
DiagnosticListener<JavaFileObject> verifyDiagnostics = new DiagnosticListener<JavaFileObject>() {
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
long adjustedPos = diagnostic.getPosition();
if (adjustedPos >= declarationSpan[0])
adjustedPos -= suppressWarnings.length();
if (declarationSpan[0] <= adjustedPos && adjustedPos <= declarationSpan[1]) {
throw new IllegalStateException("unsuppressed: " + diagnostic.getMessage(null));
}
boolean found = false;
for (Iterator<Diagnostic<?>> it = foundErrors.iterator(); it.hasNext(); ) {
Diagnostic<?> d = it.next();
if (d.getPosition() == adjustedPos && d.getCode().equals(diagnostic.getCode())) {
it.remove();
found = true;
break;
}
}
if (!found) {
throw new IllegalStateException("diagnostic not originally reported: " + diagnostic.getMessage(null));
}
}
};
JavaFileObject updatedFile = new TestFO(new URI("mem://" + args[0]), updatedContent);
JavacTask testTask = JavacTool.create().getTask(null, new TestFM(fm), verifyDiagnostics, STANDARD_PARAMS, null, Arrays.asList(updatedFile));
testTask.replacedyze();
for (Diagnostic<?> d : foundErrors) {
if (d.getPosition() < declarationSpan[0] || declarationSpan[1] < d.getPosition()) {
throw new IllegalStateException("missing: " + d.getMessage(null));
}
}
}
}
18
Source : TreePosTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
/**
* Read a file.
* @param file the file to be read
* @return the tree for the content of the file
* @throws IOException if any IO errors occur
* @throws TreePosTest.ParseException if any errors occur while parsing the file
*/
JCCompilationUnit read(File file) throws IOException, ParseException {
JavacTool tool = JavacTool.create();
r.errors = 0;
Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files);
Iterable<? extends CompilationUnitTree> trees = task.parse();
pw.flush();
if (r.errors > 0)
throw new ParseException(sw.toString());
Iterator<? extends CompilationUnitTree> iter = trees.iterator();
if (!iter.hasNext())
throw new Error("no trees found");
JCCompilationUnit t = (JCCompilationUnit) iter.next();
if (iter.hasNext())
throw new Error("too many trees found");
return t;
}
18
Source : ParameterNamesAreNotCopiedToAnonymousInitTest.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
/* This method expect a non-null ordered list of integers, listing the
* position of the parameters to be checked on the init method. Position 0
* corresponds to the first parameter.
*
* As we are looking for a constructor of an anonymous clreplaced, the
* clreplacedOwnerName parameter must be the name of the method where the
* anonymous clreplaced is declared.
*/
void checkInitSymbol(final String clreplacedOwnerName, final java.util.List<Integer> paramsToCheck, final java.util.List<String> paramNames) throws IOException {
replacedert.checkNonNull(paramsToCheck, nonNullParamPositionsMsg);
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = c.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(System.getProperty("test.src"), this.getClreplaced().getName() + ".java")));
JavacTask task = (JavacTask) c.getTask(null, fm, null, Arrays.asList("-d", System.getProperty("user.dir")), null, fos);
BasicJavacTask impl = (BasicJavacTask) task;
Context context = impl.getContext();
final Names names = Names.instance(context);
task.addTaskListener(new TaskListener() {
@Override
public void started(TaskEvent e) {
}
@Override
public void finished(TaskEvent e) {
clreplaced TheTreeScanner extends TreeScanner {
boolean foundAndCorrect = false;
@Override
public void visitMethodDef(JCTree.JCMethodDecl tree) {
ClreplacedSymbol clazz = (ClreplacedSymbol) tree.sym.owner;
if (clazz.owner.name.toString().equals(clreplacedOwnerName) && tree.sym.name == names.init) {
int currentParamPos = 0;
int paramArrayIndex = 0;
List<VarSymbol> params = tree.sym.params;
while (params.nonEmpty() && paramArrayIndex < paramsToCheck.size()) {
VarSymbol param = params.head;
if (currentParamPos == paramsToCheck.get(paramArrayIndex)) {
if (!param.name.toString().equals(paramNames.get(paramArrayIndex))) {
error(paramNameNotCopiedreplacedertionMsg);
}
paramArrayIndex++;
}
currentParamPos++;
params = params.tail;
}
foundAndCorrect = paramArrayIndex >= paramsToCheck.size();
}
super.visitMethodDef(tree);
}
}
if (e.getKind() == TaskEvent.Kind.replacedYZE) {
CompilationUnitTree compUnitTree = e.getCompilationUnit();
boolean foundAndCorrect = false;
for (Tree tree : compUnitTree.getTypeDecls()) {
TheTreeScanner scanner = new TheTreeScanner();
scanner.scan((JCTree) tree);
foundAndCorrect = foundAndCorrect | scanner.foundAndCorrect;
}
if (!foundAndCorrect) {
error(seekMethodNotFound);
}
}
}
});
if (!task.call()) {
error(compilationFailed);
}
}
18
Source : T6665791.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public static void main(String[] args) throws Exception {
write(test_java, test);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(test_java);
final StringWriter sw = new StringWriter();
JavacTask task = (JavacTask) compiler.getTask(sw, manager, null, null, null, units);
new TreeScanner<Boolean, Void>() {
@Override
public Boolean visitClreplaced(ClreplacedTree arg0, Void arg1) {
sw.write(arg0.toString());
return super.visitClreplaced(arg0, arg1);
}
}.scan(task.parse(), null);
System.out.println("output:");
System.out.println(sw.toString());
String found = sw.toString().replaceAll("\\s+", " ").trim();
String expect = test.replaceAll("\\s+", " ").trim();
if (!expect.equals(found)) {
System.out.println("expect: " + expect);
System.out.println("found: " + found);
throw new Exception("unexpected output");
}
}
18
Source : Processor.java
with GNU General Public License v2.0
from Tencent
with GNU General Public License v2.0
from Tencent
public static void main(String... args) throws IOException, URISyntaxException {
if (args.length != 1)
throw new IllegalStateException("Must provide clreplaced name!");
String testContent = null;
List<File> sourcePath = new ArrayList<>();
for (String sourcePaths : System.getProperty("test.src.path").split(":")) {
sourcePath.add(new File(sourcePaths));
}
JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
for (File sp : sourcePath) {
File inp = new File(sp, args[0]);
if (inp.canRead()) {
testContent = fm.getRegularFile(inp).getCharContent(true).toString();
}
}
if (testContent == null)
throw new IllegalStateException();
DiagnosticListener<JavaFileObject> devNull = new DiagnosticListener<JavaFileObject>() {
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
}
};
JavaFileObject testFile = new TestFO(new URI("mem://" + args[0]), testContent);
JavacTask task = JavacTool.create().getTask(null, new TestFM(fm), devNull, Arrays.asList("-Xjcov"), null, Arrays.asList(testFile));
final Trees trees = Trees.instance(task);
final CompilationUnitTree cut = task.parse().iterator().next();
task.replacedyze();
final List<int[]> annotations = new ArrayList<>();
new TreeScanner<Void, Void>() {
@Override
public Void visitAnnotation(AnnotationTree node, Void p) {
int endPos = (int) trees.getSourcePositions().getEndPosition(cut, node);
replacedert.check(endPos >= 0);
annotations.add(new int[] { (int) trees.getSourcePositions().getStartPosition(cut, node), endPos });
return super.visitAnnotation(node, p);
}
}.scan(cut.getTypeDecls().get(0), null);
Collections.sort(annotations, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o2[0] - o1[0];
}
});
for (final int[] annotation : annotations) {
StringBuilder updatedContent = new StringBuilder();
int last = testContent.length();
for (int[] toRemove : annotations) {
if (toRemove == annotation)
continue;
updatedContent.insert(0, testContent.substring(toRemove[1], last));
last = toRemove[0];
}
updatedContent.insert(0, testContent.substring(0, last));
JavaFileObject updatedFile = new TestFO(new URI("mem://" + args[0]), updatedContent.toString());
JavacTask testTask = JavacTool.create().getTask(null, new TestFM(fm), devNull, Arrays.asList("-processor", "Processor"), null, Arrays.asList(updatedFile));
try {
testTask.replacedyze();
} catch (Throwable e) {
System.out.println("error while processing:");
System.out.println(updatedContent);
throw e;
}
}
}
See More Examples