public boolean process(Set<? extends TypeElement> annos, RoundEnvironment rEnv) { Trees trees = Trees.instance(processingEnv); Test test = new Test(); for (Element e : rEnv.getRootElements()) { Tree t = trees.getTree(e); test.scan(t, null); } return true; }
@Override public void init(ProcessingEnvironment processingEnvironment) { this.processingEnv = processingEnvironment; JavacProcessingEnvironment javacProcessingEnvironment = (JavacProcessingEnvironment) processingEnvironment; this.trees = Trees.instance(processingEnvironment); TreeMaker treeMaker = TreeMaker.instance(javacProcessingEnvironment.getContext()); visitor = new ChangeTranslator(javacProcessingEnvironment, treeMaker); }
@Override public boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) { if (!roundEnvironment.processingOver()) { Set<? extends Element> elements = roundEnvironment.getRootElements(); elements.forEach( element -> { JCTree tree = (JCTree) trees.getTree(element); tree.accept(visitor); }); } return false; }
/** {@inheritDoc} */ @Override public void init(ProcessingEnvironment procEnv) { super.init(procEnv); this.processingEnv = (JavacProcessingEnvironment) procEnv; placePostCompileAndDontMakeForceRoundDummiesHook(); transformer = new JavacTransformer(procEnv.getMessager()); trees = Trees.instance(procEnv); SortedSet<Long> p = transformer.getPriorities(); if (p.isEmpty()) { this.priorityLevels = new long[] {0L}; this.priorityLevelsRequiringResolutionReset = new HashSet<Long>(); } else { this.priorityLevels = new long[p.size()]; int i = 0; for (Long prio : p) this.priorityLevels[i++] = prio; this.priorityLevelsRequiringResolutionReset = transformer.getPrioritiesRequiringResolutionReset(); } }
protected void printSymbol(String label, Symbol sym, Details details) { if (sym == null) { printNull(label); } else { switch (details) { case SUMMARY: printString(label, toString(sym)); break; case FULL: indent(); out.print(label); out.println( ": " + info( sym.getClass(), String.format("0x%x--%s", sym.kind.ordinal(), Kinds.kindName(sym)), sym.getKind()) + " " + sym.name + " " + hashString(sym)); indent(+1); if (showSrc) { JCTree tree = (JCTree) trees.getTree(sym); if (tree != null) printSource("src", tree); } printString( "flags", String.format("0x%x--%s", sym.flags_field, Flags.toString(sym.flags_field))); printObject("completer", sym.completer, Details.SUMMARY); // what if too long? printSymbol("owner", sym.owner, Details.SUMMARY); printType("type", sym.type, Details.SUMMARY); printType("erasure", sym.erasure_field, Details.SUMMARY); sym.accept(symVisitor, null); printAnnotations("annotations", sym.getMetadata(), Details.SUMMARY); indent(-1); } } }
public static void main(String... args) throws IOException, URISyntaxException { if (args.length != 1) throw new IllegalStateException("Must provide class 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.toPath()).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.analyze(); final List<int[]> declarationSpans = new ArrayList<>(); new TreeScanner<Void, Void>() { @Override public Void visitClass(ClassTree node, Void p) { handleDeclaration(node); return super.visitClass(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 visitNewClass(NewClassTree node, Void p) { if (node.getClassBody() != null) { scan(node.getClassBody().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\", \"divzero\"})"; 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.analyze(); for (Diagnostic<?> d : foundErrors) { if (d.getPosition() < declarationSpan[0] || declarationSpan[1] < d.getPosition()) { throw new IllegalStateException("missing: " + d.getMessage(null)); } } } }
void run(PrintWriter out, String... args) throws IOException { JavaCompiler c = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = c.getStandardFileManager(null, null, null); // DPrinter options final Set<TaskEvent.Kind> before = EnumSet.noneOf(TaskEvent.Kind.class); final Set<TaskEvent.Kind> after = EnumSet.noneOf(TaskEvent.Kind.class); boolean showPositions = false; boolean showSource = false; boolean showTreeSymbols = false; boolean showTreeTypes = false; boolean showEmptyItems = true; boolean showNulls = true; // javac options Collection<String> options = new ArrayList<String>(); Collection<File> files = new ArrayList<File>(); String classpath = null; String classoutdir = null; final Handler h = getHandlers().get(args[0]); if (h == null) throw new IllegalArgumentException(args[0]); for (int i = 1; i < args.length; i++) { String arg = args[i]; if (arg.equals("-before") && i + 1 < args.length) { before.add(getKind(args[++i])); } else if (arg.equals("-after") && i + 1 < args.length) { after.add(getKind(args[++i])); } else if (arg.equals("-showPositions")) { showPositions = true; } else if (arg.equals("-showSource")) { showSource = true; } else if (arg.equals("-showTreeSymbols")) { showTreeSymbols = true; } else if (arg.equals("-showTreeTypes")) { showTreeTypes = true; } else if (arg.equals("-hideEmptyLists")) { showEmptyItems = false; } else if (arg.equals("-hideNulls")) { showNulls = false; } else if (arg.equals("-classpath") && i + 1 < args.length) { classpath = args[++i]; } else if (arg.equals("-d") && i + 1 < args.length) { classoutdir = args[++i]; } else if (arg.startsWith("-")) { int n = c.isSupportedOption(arg); if (n < 0) throw new IllegalArgumentException(arg); options.add(arg); while (n > 0) options.add(args[++i]); } else if (arg.endsWith(".java")) { files.add(new File(arg)); } } if (classoutdir != null) { fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(classoutdir))); } if (classpath != null) { Collection<File> path = new ArrayList<File>(); for (String p : classpath.split(File.pathSeparator)) { if (p.isEmpty()) continue; File f = new File(p); if (f.exists()) path.add(f); } fm.setLocation(StandardLocation.CLASS_PATH, path); } Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files); JavacTask task = (JavacTask) c.getTask(out, fm, null, options, null, fos); final Trees trees = Trees.instance(task); final DPrinter dprinter = new DPrinter(out, trees); dprinter .source(showSource) .emptyItems(showEmptyItems) .nulls(showNulls) .positions(showPositions) .treeSymbols(showTreeSymbols) .treeTypes(showTreeTypes); if (before.isEmpty() && after.isEmpty()) { if (h.name.equals("trees") && !showTreeSymbols && !showTreeTypes) after.add(TaskEvent.Kind.PARSE); else after.add(TaskEvent.Kind.ANALYZE); } task.addTaskListener( new TaskListener() { public void started(TaskEvent e) { if (before.contains(e.getKind())) handle(e); } public void finished(TaskEvent e) { if (after.contains(e.getKind())) handle(e); } private void handle(TaskEvent e) { JCCompilationUnit unit = (JCCompilationUnit) e.getCompilationUnit(); switch (e.getKind()) { case PARSE: case ENTER: h.handle(e.getSourceFile().getName(), unit, unit, dprinter); break; default: TypeElement elem = e.getTypeElement(); h.handle(elem.toString(), unit, (JCTree) trees.getTree(elem), dprinter); break; } } }); task.call(); }
private JCCompilationUnit toUnit(Element element) { TreePath path = trees == null ? null : trees.getPath(element); if (path == null) return null; return (JCCompilationUnit) path.getCompilationUnit(); }
public void finished(TaskEvent e) { System.err.println("Finished: " + e); Trees t = Trees.instance(task); }
public void started(TaskEvent e) { System.err.println("Started: " + e); Trees t = Trees.instance(task); }