Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate AST from Java source-code? [closed]

As far as I know, the only way to parse Java source-code into an AST (Abstract Syntax Tree) is to use the Java Compiler Tree API: com.sun.source.tree

I have two questions:

  1. What JDKs support com.sun.source.tree?
  2. Is there a portable replacement that works for all JDKs?
like image 995
Gili Avatar asked Dec 28 '09 04:12

Gili


People also ask

What is AST in Java?

The Abstract Syntax Tree (AST) As mentioned, the Abstract Syntax Tree is the way that Eclipse looks at your source code: every Java source file is entirely represented as tree of AST nodes. These nodes are all subclasses of ASTNode . Every subclass is specialized for an element of the Java Programming Language.

What is JavaParser?

The JavaParser library provides you with an Abstract Syntax Tree of your Java code. The AST structure then allows you to work with your Java code in an easy programmatic way.


1 Answers

Regarding your second question, there are dozens of Java parsers available in addition to Sun's. Here is a small sample:

  • Eclipse's org.eclipse.jdt.core.dom package.
  • Spoon outputs a very nice annotated parse tree with type information and variable binding (and uses Eclipse's parser internally)
  • ANTLR is a parser-generator, but there are grammars for Java available
  • javaparser (which I have not used)

My best advice is to try each of them to see which works best for your needs.

like image 144
Brett Daniel Avatar answered Sep 21 '22 17:09

Brett Daniel