Helping to find the usefulness of a proposal
Joe Darcy
Joe.Darcy at Sun.COM
Thu Apr 2 11:33:45 PDT 2009
On 04/02/09 11:16 AM, Jonathan Gibbons wrote:
> For all this sort of analysis, you'd do better to use the combination of
> javac's
> annotation processing framework and the javac Tree API, than to use direct
> access into private javac API.
>
> Annotation processing isn't just for processing annotations ;-) You can
> write
> a processor that will be called on all types, and you can bridge from the
> processing world (javax.lang.model.*) to the java Tree API
> (com.sun.source.*)
> using com.sun.source.util.Trees. This allows you to write utilities to
> analyze ASTs without requiring the use of any javac internal API.
>
+1
The annotation processing in javac with JSR 269 (and apt before it) is a
general purpose meta-programming framework.
Combined with the javac tree API, many program analyses can be performed.
-Joe
> -- Jon
>
>
>
> Mark Mahieu wrote:
>
>> Wow.
>>
>> http://www.geekherocomic.com/comics-highres/2009-02-25-coding-overkill.png
>>
>>
>> Here are the important bits from my quick hack. Took under half an hour to
>> get it finding cases where Auto-assignment Parameters would and wouldn't
>> work across large source trees.
>>
>> Of course, javac makes much more than parsing available if you need it...
>>
>>
>>
>> import com.sun.tools.javac.file.JavacFileManager;
>> import com.sun.tools.javac.parser.JavacParser;
>> import com.sun.tools.javac.parser.ParserFactory;
>> import com.sun.tools.javac.tree.TreeScanner;
>> import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
>> import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
>> import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
>> import com.sun.tools.javac.util.Context;
>> import com.sun.tools.javac.util.List;
>>
>> ...
>>
>> // create a TreeScanner to do your analysis
>> TreeScanner scanner = new TreeScanner() {
>>
>> @Override
>> public void visitMethodDef(JCMethodDecl tree) {
>> // look at a method's parameters
>> for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
>> JCVariableDecl param = l.head;
>> // examine param or whatever
>> }
>> // continue recursively scanning the method body etc
>> super.visitMethodDef(tree);
>> }
>> };
>>
>> ...
>>
>> Context context = new Context();
>> JavacFileManager.preRegister(context);
>> ParserFactory factory = ParserFactory.instance(context);
>>
>> String sourceCode = readSourceFromFile(...);
>>
>> JavacParser parser = (JavacParser) factory.newParser(sourceCode, false,
>> false, false);
>> JCCompilationUnit cu = parser.parseCompilationUnit();
>>
>> // do your analysis
>> scanner.scan(cu);
>>
>>
>>
>
>
>
More information about the coin-dev
mailing list