Skip to content

AST Library

Ori Roth edited this page Apr 2, 2017 · 3 revisions

The AST (Abstract Syntax Tree) is formatted from the code by the class ASTParser. After creating an object of this class using the static method newParser(int level), source should be set by setSource(char[] source) method, and other features can be configured by other set functions. In the end the method createAST(IProgressMonitor monitor) should be called to finally create the AST (the monitor can be null), it returns an ASTNode whose type depends on the kind of parse requested.

example and documentation can be found here: http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Findex.html&org/eclipse/jdt/core/dom/ASTParser.html

ASTNode

Each AST node belongs to a unique AST instance. When an AST node is created it is unparented, when it is set as a child of a node (using a setCHILD method), its parent link is set automatically and the parent link of the former child is set to null.

ASTs do not contain "holes" (missing subtrees). If a node is required to have a certain property, a syntactically reasonable initial value is always supplied.

The nodes carry source ranges relating the node back to the original source characters.

to iterate an AST: you can navigate upwards from an ASTNode by using getParent(), you can also go straight to the root by using getRoot(). to navigate downwards you should use the ASTVisitor.

ASTVisitor

ASTVisitor basically has 4 functions boolean visit(T node), void endVisit(T node), void preVisit(ASTNode node) and void postVisit(ASTNode node). The first 2 are overloaded for each of the possible types of an AST node.

for documentation of those methods: http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom%2FASTVisitor.html

When visiting a node, first the preVisit method is called, afterwards the visit method and only after visiting the children (or immediately if visit returned false) endVisit will be called, followed by postVisit. (LineComment and BlockComment nodes are not normally visited in an AST because they are not considered part of main structure of the AST. Use CompilationUnit.getCommentList() to find these additional comments nodes.)

It is possible to modify the tree in the visitor, but it should be done carefully. It is better to use ASTRewrite to modify the original source code.

ASTRewrite

To instantiate a Rewrite clients should use create(AST ast). It collects descriptions of modifications to nodes and translates these descriptions into TextEdits that can then be applied to the original source.

ASTRewrite cannot rewrite (non-Javadoc) comments (as they are not part of the main structure of the AST).

Code example can be found here: http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom%2Frewrite%2FASTRewrite.html

Clone this wiki locally