Class AST

java.lang.Object
org.aspectj.org.eclipse.jdt.core.dom.AST
Direct Known Subclasses:
AjAST

public class AST extends Object
Umbrella owner and abstract syntax tree node factory. An AST instance serves as the common owner of any number of AST nodes, and as the factory for creating new AST nodes owned by that instance.

Abstract syntax trees may be hand constructed by clients, using the newTYPE factory methods to create new nodes, and the various setCHILD methods (see ASTNode and its subclasses) to connect them together.

Each AST node belongs to a unique AST instance, called the owning AST. The children of an AST node always have the same owner as their parent node. If a node from one AST is to be added to a different AST, the subtree must be cloned first to ensures that the added nodes have the correct owning AST.

There can be any number of AST nodes owned by a single AST instance that are unparented. Each of these nodes is the root of a separate little tree of nodes. The method ASTNode.getRoot() navigates from any node to the root of the tree that it is contained in. Ordinarily, an AST instance has one main tree (rooted at a CompilationUnit), with newly-created nodes appearing as additional roots until they are parented somewhere under the main tree. One can navigate from any node to its AST instance, but not conversely.

The class ASTParser parses a string containing a Java source code and returns an abstract syntax tree for it. The resulting nodes carry source ranges relating the node back to the original source characters.

Compilation units created by ASTParser from a source document can be serialized after arbitrary modifications with minimal loss of original formatting. Here is an example:

 Document doc = new Document("import java.util.List;\nclass X {}\n");
 ASTParser parser = ASTParser.newParser(AST.JLS3);
 parser.setSource(doc.get().toCharArray());
 CompilationUnit cu = (CompilationUnit) parser.createAST(null);
 cu.recordModifications();
 AST ast = cu.getAST();
 ImportDeclaration id = ast.newImportDeclaration();
 id.setName(ast.newName(new String[] {"java", "util", "Set"});
 cu.imports().add(id); // add import declaration at end
 TextEdit edits = cu.rewrite(document, null);
 UndoEdit undo = edits.apply(document);
 

See also ASTRewrite for an alternative way to describe and serialize changes to a read-only AST.

Clients may create instances of this class using newAST(int, boolean), but this class is not intended to be subclassed.

Since:
2.0
See Also: