public final class AST extends Object
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)
,
but this class is not intended to be subclassed.
Modifier and Type | Field and Description |
---|---|
static int |
JLS2
Deprecated.
Clients should use the
JLS8 AST API instead. |
static int |
JLS3
Deprecated.
Clients should use the
JLS8 AST API instead. |
static int |
JLS4
Deprecated.
Clients should use the
JLS8 AST API instead. |
static int |
JLS8
Constant for indicating the AST API that handles JLS8.
|
Constructor and Description |
---|
AST()
Deprecated.
Clients should port their code to use the new JLS4 AST API and call
AST.newAST(AST.JLS4) instead of using this constructor. |
AST(Map options)
Deprecated.
Clients should port their code to use the new JLS4 AST API and call
AST.newAST(AST.JLS4) instead of using this constructor. |
Modifier and Type | Method and Description |
---|---|
int |
apiLevel()
Return the API level supported by this AST.
|
static CompilationUnit |
convertCompilationUnit(int level,
org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration compilationUnitDeclaration,
char[] source,
Map options,
boolean isResolved,
org.eclipse.jdt.internal.core.CompilationUnit workingCopy,
int reconcileFlags,
IProgressMonitor monitor)
Deprecated.
Use org.eclipse.jdt.core.dom.AST.convertCompilationUnit(int, CompilationUnitDeclaration, Map, boolean, CompilationUnit, int, IProgressMonitor) instead
|
static CompilationUnit |
convertCompilationUnit(int level,
org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration compilationUnitDeclaration,
Map options,
boolean isResolved,
org.eclipse.jdt.internal.core.CompilationUnit workingCopy,
int reconcileFlags,
IProgressMonitor monitor)
Internal method.
|
ASTNode |
createInstance(Class nodeClass)
Creates an unparented node of the given node class
(non-abstract subclass of
ASTNode ). |
ASTNode |
createInstance(int nodeType)
Creates an unparented node of the given node type.
|
boolean |
hasBindingsRecovery()
Returns true if the ast tree was created with bindings recovery, false otherwise
|
boolean |
hasResolvedBindings()
Returns true if the ast tree was created with bindings, false otherwise
|
boolean |
hasStatementsRecovery()
Returns true if the ast tree was created with statements recovery, false otherwise
|
long |
modificationCount()
Returns the modification count for this AST.
|
AnnotationTypeDeclaration |
newAnnotationTypeDeclaration()
Creates and returns a new unparented annotation type declaration
node for an unspecified, but legal, name; no modifiers; no javadoc;
and an empty list of member declarations.
|
AnnotationTypeMemberDeclaration |
newAnnotationTypeMemberDeclaration()
Creates and returns a new unparented annotation type
member declaration node for an unspecified, but legal,
member name and type; no modifiers; no javadoc;
and no default value.
|
AnonymousClassDeclaration |
newAnonymousClassDeclaration()
Creates and returns a new unparented anonymous class declaration
node owned by this AST.
|
ArrayAccess |
newArrayAccess()
Creates and returns a new unparented array access expression node
owned by this AST.
|
ArrayCreation |
newArrayCreation()
Creates and returns a new unparented array creation expression node
owned by this AST.
|
ArrayInitializer |
newArrayInitializer()
Creates and returns a new unparented array initializer node
owned by this AST.
|
ArrayType |
newArrayType(Type elementType)
Creates and returns a new unparented array type node with the given
element type, which cannot be an array type for API levels JLS8 and later.
|
ArrayType |
newArrayType(Type elementType,
int dimensions)
Creates and returns a new unparented array type node with the given
element type and number of dimensions.
|
AssertStatement |
newAssertStatement()
Creates a new unparented assert statement node owned by this AST.
|
Assignment |
newAssignment()
Creates and returns a new unparented assignment expression node
owned by this AST.
|
static AST |
newAST(int level)
Creates a new Java abstract syntax tree
(AST) following the specified set of API rules.
|
Block |
newBlock()
Creates an unparented block node owned by this AST, for an empty list
of statements.
|
BlockComment |
newBlockComment()
Creates and returns a new block comment placeholder node.
|
BooleanLiteral |
newBooleanLiteral(boolean value)
Creates and returns a new unparented boolean literal node.
|
BreakStatement |
newBreakStatement()
Creates an unparented break statement node owned by this AST.
|
CastExpression |
newCastExpression()
Creates and returns a new unparented cast expression node
owned by this AST.
|
CatchClause |
newCatchClause()
Creates a new unparented catch clause node owned by this AST.
|
CharacterLiteral |
newCharacterLiteral()
Creates and returns a new unparented character literal node.
|
ClassInstanceCreation |
newClassInstanceCreation()
Creates and returns a new unparented class instance creation
("new") expression node owned by this AST.
|
CompilationUnit |
newCompilationUnit()
Creates an unparented compilation unit node owned by this AST.
|
ConditionalExpression |
newConditionalExpression()
Creates and returns a new unparented conditional expression node
owned by this AST.
|
ConstructorInvocation |
newConstructorInvocation()
Creates an unparented alternate constructor ("this(...);") invocation
statement node owned by this AST.
|
ContinueStatement |
newContinueStatement()
Creates an unparented continue statement node owned by this AST.
|
CreationReference |
newCreationReference()
Creates an unparented creation reference node owned by this AST.
|
Dimension |
newDimension()
Creates and returns a new unparented annotatable dimension node
(Supported only in JLS8 level).
|
DoStatement |
newDoStatement()
Creates a new unparented do statement node owned by this AST.
|
EmptyStatement |
newEmptyStatement()
Creates a new unparented empty statement node owned by this AST.
|
EnhancedForStatement |
newEnhancedForStatement()
Creates a new unparented enhanced for statement node owned by this AST.
|
EnumConstantDeclaration |
newEnumConstantDeclaration()
Creates an unparented enum constant declaration node owned by this AST.
|
EnumDeclaration |
newEnumDeclaration()
Creates an unparented enum declaration node owned by this AST.
|
ExpressionMethodReference |
newExpressionMethodReference()
Creates an unparented expression method reference node owned by this AST.
|
ExpressionStatement |
newExpressionStatement(Expression expression)
Creates a new unparented expression statement node owned by this AST,
for the given expression.
|
FieldAccess |
newFieldAccess()
Creates and returns a new unparented field access expression node
owned by this AST.
|
FieldDeclaration |
newFieldDeclaration(VariableDeclarationFragment fragment)
Creates a new unparented field declaration node owned by this AST,
for the given variable declaration fragment.
|
ForStatement |
newForStatement()
Creates a new unparented for statement node owned by this AST.
|
IfStatement |
newIfStatement()
Creates a new unparented if statement node owned by this AST.
|
ImportDeclaration |
newImportDeclaration()
Creates an unparented import declaration node owned by this AST.
|
InfixExpression |
newInfixExpression()
Creates and returns a new unparented infix expression node
owned by this AST.
|
Initializer |
newInitializer()
Creates an unparented initializer node owned by this AST, with an
empty block.
|
InstanceofExpression |
newInstanceofExpression()
Creates and returns a new unparented instanceof expression node
owned by this AST.
|
IntersectionType |
newIntersectionType()
Creates a new unparented intersection type node owned by this AST.
|
Javadoc |
newJavadoc()
Creates and returns a new doc comment node.
|
LabeledStatement |
newLabeledStatement()
Creates a new unparented labeled statement node owned by this AST.
|
LambdaExpression |
newLambdaExpression()
Creates an unparented lambda expression node owned by this AST.
|
LineComment |
newLineComment()
Creates and returns a new line comment placeholder node.
|
MarkerAnnotation |
newMarkerAnnotation()
Creates and returns a new unparented marker annotation node with
an unspecified type name.
|
MemberRef |
newMemberRef()
Creates and returns a new member reference node.
|
MemberValuePair |
newMemberValuePair()
Creates and returns a new unparented member value pair node with
an unspecified member name and value.
|
MethodDeclaration |
newMethodDeclaration()
Creates an unparented method declaration node owned by this AST.
|
MethodInvocation |
newMethodInvocation()
Creates an unparented method invocation expression node owned by this
AST.
|
MethodRef |
newMethodRef()
Creates and returns a new method reference node.
|
MethodRefParameter |
newMethodRefParameter()
Creates and returns a new method reference node.
|
Modifier |
newModifier(Modifier.ModifierKeyword keyword)
Creates and returns a new unparented modifier node for the given
modifier.
|
List |
newModifiers(int flags)
Creates and returns a list of new unparented modifier nodes
for the given modifier flags.
|
Name |
newName(String qualifiedName)
Creates and returns a new unparented name node for the given name.
|
Name |
newName(String[] identifiers)
Creates and returns a new unparented name node for the given name
segments.
|
NameQualifiedType |
newNameQualifiedType(Name qualifier,
SimpleName name)
Creates and returns a new unparented name qualified type node with
the given qualifier and name.
|
NormalAnnotation |
newNormalAnnotation()
Creates and returns a new unparented normal annotation node with
an unspecified type name and an empty list of member value
pairs.
|
NullLiteral |
newNullLiteral()
Creates and returns a new unparented null literal node.
|
NumberLiteral |
newNumberLiteral()
Creates and returns a new unparented number literal node.
|
NumberLiteral |
newNumberLiteral(String literal)
Creates and returns a new unparented number literal node.
|
PackageDeclaration |
newPackageDeclaration()
Creates an unparented package declaration node owned by this AST.
|
ParameterizedType |
newParameterizedType(Type type)
Creates and returns a new unparented parameterized type node with the
given type and an empty list of type arguments.
|
ParenthesizedExpression |
newParenthesizedExpression()
Creates and returns a new unparented parenthesized expression node
owned by this AST.
|
PostfixExpression |
newPostfixExpression()
Creates and returns a new unparented postfix expression node
owned by this AST.
|
PrefixExpression |
newPrefixExpression()
Creates and returns a new unparented prefix expression node
owned by this AST.
|
PrimitiveType |
newPrimitiveType(PrimitiveType.Code typeCode)
Creates and returns a new unparented primitive type node with the given
type code.
|
QualifiedName |
newQualifiedName(Name qualifier,
SimpleName name)
Creates and returns a new unparented qualified name node for the given
qualifier and simple name child node.
|
QualifiedType |
newQualifiedType(Type qualifier,
SimpleName name)
Creates and returns a new unparented qualified type node with
the given qualifier type and name.
|
ReturnStatement |
newReturnStatement()
Creates a new unparented return statement node owned by this AST.
|
SimpleName |
newSimpleName(String identifier)
Creates and returns a new unparented simple name node for the given
identifier.
|
SimpleType |
newSimpleType(Name typeName)
Creates and returns a new unparented simple type node with the given
type name.
|
SingleMemberAnnotation |
newSingleMemberAnnotation()
Creates and returns a new unparented single member annotation node with
an unspecified type name and value.
|
SingleVariableDeclaration |
newSingleVariableDeclaration()
Creates an unparented single variable declaration node owned by this AST.
|
StringLiteral |
newStringLiteral()
Creates and returns a new unparented string literal node for
the empty string literal.
|
SuperConstructorInvocation |
newSuperConstructorInvocation()
Creates an unparented alternate super constructor ("super(...);")
invocation statement node owned by this AST.
|
SuperFieldAccess |
newSuperFieldAccess()
Creates and returns a new unparented super field access expression node
owned by this AST.
|
SuperMethodInvocation |
newSuperMethodInvocation()
Creates an unparented "super" method invocation expression node owned by
this AST.
|
SuperMethodReference |
newSuperMethodReference()
Creates and returns a new unparented super method reference node owned by
this AST.
|
SwitchCase |
newSwitchCase()
Creates a new unparented switch case statement node owned by
this AST.
|
SwitchStatement |
newSwitchStatement()
Creates a new unparented switch statement node owned by this AST.
|
SynchronizedStatement |
newSynchronizedStatement()
Creates a new unparented synchronized statement node owned by this AST.
|
TagElement |
newTagElement()
Creates and returns a new tag element node.
|
TextElement |
newTextElement()
Creates and returns a new text element node.
|
ThisExpression |
newThisExpression()
Creates and returns a new unparented "this" expression node
owned by this AST.
|
ThrowStatement |
newThrowStatement()
Creates a new unparented throw statement node owned by this AST.
|
TryStatement |
newTryStatement()
Creates a new unparented try statement node owned by this AST.
|
TypeDeclaration |
newTypeDeclaration()
Creates an unparented class declaration node owned by this AST.
|
TypeDeclarationStatement |
newTypeDeclarationStatement(AbstractTypeDeclaration decl)
Creates a new unparented local type declaration statement node
owned by this AST, for the given type declaration.
|
TypeDeclarationStatement |
newTypeDeclarationStatement(TypeDeclaration decl)
Creates a new unparented local type declaration statement node
owned by this AST, for the given type declaration.
|
TypeLiteral |
newTypeLiteral()
Creates and returns a new unparented type literal expression node
owned by this AST.
|
TypeMethodReference |
newTypeMethodReference()
Creates an unparented type method reference node owned by this AST.
|
TypeParameter |
newTypeParameter()
Creates and returns a new unparented type parameter type node with an
unspecified type variable name and an empty list of type bounds.
|
UnionType |
newUnionType()
Creates a new unparented union type node owned by this AST.
|
VariableDeclarationExpression |
newVariableDeclarationExpression(VariableDeclarationFragment fragment)
Creates a new unparented local variable declaration expression node
owned by this AST, for the given variable declaration fragment.
|
VariableDeclarationFragment |
newVariableDeclarationFragment()
Creates an unparented variable declaration fragment node owned by this
AST.
|
VariableDeclarationStatement |
newVariableDeclarationStatement(VariableDeclarationFragment fragment)
Creates a new unparented local variable declaration statement node
owned by this AST, for the given variable declaration fragment.
|
WhileStatement |
newWhileStatement()
Creates a new unparented while statement node owned by this AST.
|
WildcardType |
newWildcardType()
Creates and returns a new unparented wildcard type node with no
type bound.
|
static CompilationUnit |
parseCompilationUnit(char[] source)
Deprecated.
Use
ASTParser instead. |
static CompilationUnit |
parseCompilationUnit(char[] source,
String unitName,
IJavaProject project)
Deprecated.
Use
ASTParser instead. |
static CompilationUnit |
parseCompilationUnit(IClassFile classFile,
boolean resolveBindings)
Deprecated.
Use
ASTParser instead. |
static CompilationUnit |
parseCompilationUnit(ICompilationUnit unit,
boolean resolveBindings)
Deprecated.
Use
ASTParser instead. |
ITypeBinding |
resolveWellKnownType(String name)
Returns the type binding for a "well known" type.
|
public static final int JLS2
JLS8
AST API instead.This API is capable of handling all constructs in the Java language as described in the Java Language Specification, Second Edition (JLS2). JLS2 is a superset of all earlier versions of the Java language, and the JLS2 API can be used to manipulate programs written in all versions of the Java language up to and including J2SE 1.4.
public static final int JLS3
JLS8
AST API instead.This API is capable of handling all constructs in the Java language as described in the Java Language Specification, Third Edition (JLS3). JLS3 is a superset of all earlier versions of the Java language, and the JLS3 API can be used to manipulate programs written in all versions of the Java language up to and including J2SE 5 (aka JDK 1.5).
public static final int JLS4
JLS8
AST API instead.This API is capable of handling all constructs in the Java language as described in the Java Language Specification, Java SE 7 Edition (JLS7) as specified by JSR336. JLS4 is a superset of all earlier versions of the Java language, and the JLS4 API can be used to manipulate programs written in all versions of the Java language up to and including Java SE 7 (aka JDK 1.7).
public static final int JLS8
This API is capable of handling all constructs in the Java language as described in the Java Language Specification, Java SE 8 Edition (JLS8) as specified by JSR337. JLS8 is a superset of all earlier versions of the Java language, and the JLS8 API can be used to manipulate programs written in all versions of the Java language up to and including Java SE 8 (aka JDK 1.8).
public AST()
AST.newAST(AST.JLS4)
instead of using this constructor.JavaCore.getDefaultOptions()
public AST(Map options)
AST.newAST(AST.JLS4)
instead of using this constructor.Following option keys are significant:
"org.eclipse.jdt.core.compiler.source"
-
indicates source compatibility mode (as per JavaCore
);
"1.3"
means the source code is as per JDK 1.3;
"1.4"
means the source code is as per JDK 1.4
("assert"
is now a keyword);
"1.5"
means the source code is as per JDK 1.5
("enum"
is now a keyword);
"1.7"
means the source code is as per JDK 1.7;
additional legal values may be added later. options
- the table of options (key type: String
;
value type: String
)JavaCore.getDefaultOptions()
public static CompilationUnit convertCompilationUnit(int level, org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration compilationUnitDeclaration, char[] source, Map options, boolean isResolved, org.eclipse.jdt.internal.core.CompilationUnit workingCopy, int reconcileFlags, IProgressMonitor monitor)
This method converts the given internal compiler AST for the given source string into a compilation unit. This method is not intended to be called by clients.
level
- the API level; one of the JLS*
level constantscompilationUnitDeclaration
- an internal AST node for a compilation unit declarationsource
- the string of the Java compilation unitoptions
- compiler optionsworkingCopy
- the working copy that the AST is created frommonitor
- the progress monitor used to report progress and request cancellation,
or null
if noneisResolved
- whether the given compilation unit declaration is resolvedpublic static CompilationUnit convertCompilationUnit(int level, org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration compilationUnitDeclaration, Map options, boolean isResolved, org.eclipse.jdt.internal.core.CompilationUnit workingCopy, int reconcileFlags, IProgressMonitor monitor)
This method converts the given internal compiler AST for the given source string into a compilation unit. This method is not intended to be called by clients.
level
- the API level; one of the JLS*
level constantscompilationUnitDeclaration
- an internal AST node for a compilation unit declarationoptions
- compiler optionsworkingCopy
- the working copy that the AST is created frommonitor
- the progress monitor used to report progress and request cancellation,
or null
if noneisResolved
- whether the given compilation unit declaration is resolvedpublic static AST newAST(int level)
Clients should use this method specifying JLS8
as the
AST level in all cases, even when dealing with source of earlier JDK versions like 1.3 or 1.4.
level
- the API level; one of the JLS*
level constantsIllegalArgumentException
- if:
JLS*
level constantspublic static CompilationUnit parseCompilationUnit(char[] source)
ASTParser
instead.
The returned compilation unit node is the root node of a new AST.
Each node in the subtree carries source range(s) information relating back
to positions in the given source string (the given source string itself
is not remembered with the AST).
The source range usually begins at the first character of the first token
corresponding to the node; leading whitespace and comments are not
included. The source range usually extends through the last character of
the last token corresponding to the node; trailing whitespace and
comments are not included. There are a handful of exceptions
(including compilation units and the various body declarations); the
specification for these node type spells out the details.
Source ranges nest properly: the source range for a child is always
within the source range of its parent, and the source ranges of sibling
nodes never overlap.
If a syntax error is detected while parsing, the relevant node(s) of the
tree will be flagged as MALFORMED
.
This method does not compute binding information; all resolveBinding
methods applied to nodes of the resulting AST return null
.
source
- the string to be parsed as a Java compilation unitASTNode.getFlags()
,
ASTNode.MALFORMED
,
ASTNode.getStartPosition()
,
ASTNode.getLength()
public static CompilationUnit parseCompilationUnit(char[] source, String unitName, IJavaProject project)
ASTParser
instead.
The returned compilation unit node is the root node of a new AST.
Each node in the subtree carries source range(s) information relating back
to positions in the given source string (the given source string itself
is not remembered with the AST).
The source range usually begins at the first character of the first token
corresponding to the node; leading whitespace and comments are not
included. The source range usually extends through the last character of
the last token corresponding to the node; trailing whitespace and
comments are not included. There are a handful of exceptions
(including compilation units and the various body declarations); the
specification for these node type spells out the details.
Source ranges nest properly: the source range for a child is always
within the source range of its parent, and the source ranges of sibling
nodes never overlap.
If a syntax error is detected while parsing, the relevant node(s) of the
tree will be flagged as MALFORMED
.
If the given project is not null
, the various names
and types appearing in the compilation unit can be resolved to "bindings"
by calling the resolveBinding
methods. These bindings
draw connections between the different parts of a program, and
generally afford a more powerful vantage point for clients who wish to
analyze a program's structure more deeply. These bindings come at a
considerable cost in both time and space, however, and should not be
requested frivolously. The additional space is not reclaimed until the
AST, all its nodes, and all its bindings become garbage. So it is very
important to not retain any of these objects longer than absolutely
necessary. Bindings are resolved at the time the AST is created. Subsequent
modifications to the AST do not affect the bindings returned by
resolveBinding
methods in any way; these methods return the
same binding as before the AST was modified (including modifications
that rearrange subtrees by reparenting nodes).
If the given project is null
, the analysis
does not go beyond parsing and building the tree, and all
resolveBinding
methods return null
from the
outset.
The name of the compilation unit must be supplied for resolving bindings.
This name should be suffixed by a dot ('.') followed by one of the
Java-like extensions
and match the name of the main
(public) class or interface declared in the source. For example, if the source
declares a public class named "Foo", the name of the compilation can be
"Foo.java". For the purposes of resolving bindings, types declared in the
source string hide types by the same name available through the classpath
of the given project.
source
- the string to be parsed as a Java compilation unitunitName
- the name of the compilation unit that would contain the source
string, or null
if javaProject
is also null
project
- the Java project used to resolve names, or
null
if bindings are not resolvedASTNode.getFlags()
,
ASTNode.MALFORMED
,
ASTNode.getStartPosition()
,
ASTNode.getLength()
public static CompilationUnit parseCompilationUnit(IClassFile classFile, boolean resolveBindings)
ASTParser
instead.IClassFile.getSource()
, and is only available for a class
files with attached source.
The returned compilation unit node is the root node of a new AST.
Each node in the subtree carries source range(s) information relating back
to positions in the source string (the source string is not remembered
with the AST).
The source range usually begins at the first character of the first token
corresponding to the node; leading whitespace and comments are not
included. The source range usually extends through the last character of
the last token corresponding to the node; trailing whitespace and
comments are not included. There are a handful of exceptions
(including compilation units and the various body declarations); the
specification for these node type spells out the details.
Source ranges nest properly: the source range for a child is always
within the source range of its parent, and the source ranges of sibling
nodes never overlap.
If a syntax error is detected while parsing, the relevant node(s) of the
tree will be flagged as MALFORMED
.
If resolveBindings
is true
, the various names
and types appearing in the compilation unit can be resolved to "bindings"
by calling the resolveBinding
methods. These bindings
draw connections between the different parts of a program, and
generally afford a more powerful vantage point for clients who wish to
analyze a program's structure more deeply. These bindings come at a
considerable cost in both time and space, however, and should not be
requested frivolously. The additional space is not reclaimed until the
AST, all its nodes, and all its bindings become garbage. So it is very
important to not retain any of these objects longer than absolutely
necessary. Bindings are resolved at the time the AST is created. Subsequent
modifications to the AST do not affect the bindings returned by
resolveBinding
methods in any way; these methods return the
same binding as before the AST was modified (including modifications
that rearrange subtrees by reparenting nodes).
If resolveBindings
is false
, the analysis
does not go beyond parsing and building the tree, and all
resolveBinding
methods return null
from the
outset.
classFile
- the Java model class file whose corresponding source code is to be parsedresolveBindings
- true
if bindings are wanted,
and false
if bindings are not of interestIllegalArgumentException
- if the given Java element does not
exist or if its source string cannot be obtainedASTNode.getFlags()
,
ASTNode.MALFORMED
,
ASTNode.getStartPosition()
,
ASTNode.getLength()
public static CompilationUnit parseCompilationUnit(ICompilationUnit unit, boolean resolveBindings)
ASTParser
instead.ICompilationUnit.getSource()
.
The returned compilation unit node is the root node of a new AST.
Each node in the subtree carries source range(s) information relating back
to positions in the source string (the source string is not remembered
with the AST).
The source range usually begins at the first character of the first token
corresponding to the node; leading whitespace and comments are not
included. The source range usually extends through the last character of
the last token corresponding to the node; trailing whitespace and
comments are not included. There are a handful of exceptions
(including compilation units and the various body declarations); the
specification for these node type spells out the details.
Source ranges nest properly: the source range for a child is always
within the source range of its parent, and the source ranges of sibling
nodes never overlap.
If a syntax error is detected while parsing, the relevant node(s) of the
tree will be flagged as MALFORMED
.
If resolveBindings
is true
, the various names
and types appearing in the compilation unit can be resolved to "bindings"
by calling the resolveBinding
methods. These bindings
draw connections between the different parts of a program, and
generally afford a more powerful vantage point for clients who wish to
analyze a program's structure more deeply. These bindings come at a
considerable cost in both time and space, however, and should not be
requested frivolously. The additional space is not reclaimed until the
AST, all its nodes, and all its bindings become garbage. So it is very
important to not retain any of these objects longer than absolutely
necessary. Bindings are resolved at the time the AST is created. Subsequent
modifications to the AST do not affect the bindings returned by
resolveBinding
methods in any way; these methods return the
same binding as before the AST was modified (including modifications
that rearrange subtrees by reparenting nodes).
If resolveBindings
is false
, the analysis
does not go beyond parsing and building the tree, and all
resolveBinding
methods return null
from the
outset.
unit
- the Java model compilation unit whose source code is to be parsedresolveBindings
- true
if bindings are wanted,
and false
if bindings are not of interestIllegalArgumentException
- if the given Java element does not
exist or if its source string cannot be obtainedASTNode.getFlags()
,
ASTNode.MALFORMED
,
ASTNode.getStartPosition()
,
ASTNode.getLength()
public int apiLevel()
JLS*
level constants
declared on AST
; assume this set is open-endedpublic ASTNode createInstance(Class nodeClass)
ASTNode
).nodeClass
- AST node classIllegalArgumentException
- if nodeClass
is
null
or is not a concrete node type class
or is not supported for this AST's API levelpublic ASTNode createInstance(int nodeType)
createInstance(ASTNode.nodeClassForType(nodeType))
nodeType
- AST node type, one of the node type
constants declared on ASTNode
IllegalArgumentException
- if nodeType
is
not a legal AST node type or if it's not supported for this AST's API levelpublic boolean hasBindingsRecovery()
public boolean hasResolvedBindings()
public boolean hasStatementsRecovery()
public long modificationCount()
The following things count as modifying an AST:
N.B. This method may be called several times in the course of a single client operation. The only promise is that the modification count increases monotonically as the AST or its nodes change; there is no promise that a modifying operation increases the count by exactly 1.
public AnnotationTypeDeclaration newAnnotationTypeDeclaration()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic AnnotationTypeMemberDeclaration newAnnotationTypeMemberDeclaration()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic AnonymousClassDeclaration newAnonymousClassDeclaration()
public ArrayAccess newArrayAccess()
public ArrayCreation newArrayCreation()
Examples:
// new String[len]
ArrayCreation ac1 = ast.newArrayCreation();
ac1.setType(
ast.newArrayType(
ast.newSimpleType(ast.newSimpleName("String"))));
ac1.dimensions().add(ast.newSimpleName("len"));
// new double[7][24][]
ArrayCreation ac2 = ast.newArrayCreation();
ac2.setType(
ast.newArrayType(
ast.newPrimitiveType(PrimitiveType.DOUBLE), 3));
ac2.dimensions().add(ast.newNumberLiteral("7"));
ac2.dimensions().add(ast.newNumberLiteral("24"));
// new int[] {1, 2}
ArrayCreation ac3 = ast.newArrayCreation();
ac3.setType(
ast.newArrayType(
ast.newPrimitiveType(PrimitiveType.INT)));
ArrayInitializer ai = ast.newArrayInitializer();
ac3.setInitializer(ai);
ai.expressions().add(ast.newNumberLiteral("1"));
ai.expressions().add(ast.newNumberLiteral("2"));
public ArrayInitializer newArrayInitializer()
public ArrayType newArrayType(Type elementType)
For JLS4 and before, the given component type may be another array type.
elementType
- element type for API level JLS8 and later, or the
component type (possibly another array type) for levels less than JLS8IllegalArgumentException
- if:
public ArrayType newArrayType(Type elementType, int dimensions)
For JLS4 and before, the element type passed in can be an array type, but in that case, the element type of the result will not be the same as what was passed in. For JLS4 and before, the dimensions cannot be 0.
elementType
- the element type (cannot be an array type for JLS8 and later)dimensions
- the number of dimensions, a non-negative numberIllegalArgumentException
- if:
public AssertStatement newAssertStatement()
public Assignment newAssignment()
public Block newBlock()
public BlockComment newBlockComment()
Note that this node type is used to recording the source range where a comment was found in the source string. These comment nodes are normally found (only) in the comment table for parsed compilation units.
public BooleanLiteral newBooleanLiteral(boolean value)
For example, the assignment expression foo = true
is generated by the following snippet:
Assignment e= ast.newAssignment();
e.setLeftHandSide(ast.newSimpleName("foo"));
e.setRightHandSide(ast.newBooleanLiteral(true));
value
- the boolean valuepublic BreakStatement newBreakStatement()
public CastExpression newCastExpression()
public CatchClause newCatchClause()
public CharacterLiteral newCharacterLiteral()
public ClassInstanceCreation newClassInstanceCreation()
public CompilationUnit newCompilationUnit()
public ConditionalExpression newConditionalExpression()
public ConstructorInvocation newConstructorInvocation()
Note that this type of node is a Statement, whereas a regular method invocation is an Expression. The only valid use of these statements are as the first statement of a constructor body.
public ContinueStatement newContinueStatement()
public CreationReference newCreationReference()
UnsupportedOperationException
- if this operation is used in a JLS2, JLS3 or JLS4 ASTpublic DoStatement newDoStatement()
public EmptyStatement newEmptyStatement()
public EnhancedForStatement newEnhancedForStatement()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic EnumConstantDeclaration newEnumConstantDeclaration()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic EnumDeclaration newEnumDeclaration()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic ExpressionMethodReference newExpressionMethodReference()
UnsupportedOperationException
- if this operation is used in a JLS2, JLS3 or JLS4 ASTpublic ExpressionStatement newExpressionStatement(Expression expression)
This method can be used to convert an expression
(Expression
) into a statement (Type
)
by wrapping it. Note, however, that the result is only legal for
limited expression types, including method invocations, assignments,
and increment/decrement operations.
expression
- the expressionIllegalArgumentException
- if:
public Dimension newDimension()
IllegalArgumentException
- if:
UnsupportedOperationException
- if this operation is used
in a JLS2, JLS3 or JLS4 ASTpublic FieldAccess newFieldAccess()
public FieldDeclaration newFieldDeclaration(VariableDeclarationFragment fragment)
This method can be used to wrap a variable declaration fragment
(VariableDeclarationFragment
) into a field declaration
suitable for inclusion in the body of a type declaration
(FieldDeclaration
implements BodyDeclaration
).
Additional variable declaration fragments can be added afterwards.
fragment
- the variable declaration fragmentIllegalArgumentException
- if:
public ForStatement newForStatement()
public IfStatement newIfStatement()
public ImportDeclaration newImportDeclaration()
public InfixExpression newInfixExpression()
public Initializer newInitializer()
public InstanceofExpression newInstanceofExpression()
public Javadoc newJavadoc()
public LabeledStatement newLabeledStatement()
public LambdaExpression newLambdaExpression()
UnsupportedOperationException
- if this operation is used in a JLS2, JLS3 or JLS4 ASTpublic LineComment newLineComment()
Note that this node type is used to recording the source range where a comment was found in the source string. These comment nodes are normally found (only) in the comment table for parsed compilation units.
public MarkerAnnotation newMarkerAnnotation()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic MemberRef newMemberRef()
Note that this node type is used only inside doc comments
(Javadoc
).
public MemberValuePair newMemberValuePair()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic MethodDeclaration newMethodDeclaration()
To create a constructor, use this method and then call
MethodDeclaration.setConstructor(true)
and
MethodDeclaration.setName(className)
.
public MethodInvocation newMethodInvocation()
public MethodRef newMethodRef()
Note that this node type is used only inside doc comments
(Javadoc
).
public MethodRefParameter newMethodRefParameter()
Note that this node type is used only inside doc comments
(Javadoc
).
public Modifier newModifier(Modifier.ModifierKeyword keyword)
keyword
- one of the modifier keyword constantsIllegalArgumentException
- if the primitive type code is invalidUnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic List newModifiers(int flags)
public protected private abstract default static final synchronized native strictfp transient volatile
This order is consistent with the recommendations in JLS8 ("*Modifier:" rules in chapters 8 and 9).
flags
- bitwise or of modifier flags declared on Modifier
Modifier
)UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic Name newName(String qualifiedName)
QualifiedName
if the name has
dots, and a SimpleName
otherwise. Each of the name
segments should be legal Java identifiers (this constraint may or may
not be enforced), and there must be at least one name segment.
The string must not contains white space, '<', '>',
'[', ']', or other any other characters that are not
part of the Java identifiers or separating '.'s.qualifiedName
- string consisting of 1 or more name segments,
each of which is a legal Java identifier, separated by single dots '.'IllegalArgumentException
- if:
public Name newName(String[] identifiers)
identifiers
- a list of 1 or more name segments, each of which
is a legal Java identifierIllegalArgumentException
- if:
public NameQualifiedType newNameQualifiedType(Name qualifier, SimpleName name)
qualifier
- the name qualifier name nodename
- the simple name being qualifiedIllegalArgumentException
- if:
UnsupportedOperationException
- if this operation is used in
a JLS2, JLS3 and JLS4 ASTpublic NormalAnnotation newNormalAnnotation()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic NullLiteral newNullLiteral()
public NumberLiteral newNumberLiteral()
"0"
.public NumberLiteral newNumberLiteral(String literal)
literal
- the token for the numeric literal as it would
appear in Java source codeIllegalArgumentException
- if the literal is nullpublic PackageDeclaration newPackageDeclaration()
public ParameterizedType newParameterizedType(Type type)
type
- the type that is parameterizedIllegalArgumentException
- if:
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic ParenthesizedExpression newParenthesizedExpression()
public PostfixExpression newPostfixExpression()
public PrefixExpression newPrefixExpression()
public PrimitiveType newPrimitiveType(PrimitiveType.Code typeCode)
typeCode
- one of the primitive type code constants declared in
PrimitiveType
IllegalArgumentException
- if the primitive type code is invalidpublic QualifiedName newQualifiedName(Name qualifier, SimpleName name)
qualifier
- the qualifier name nodename
- the simple name being qualifiedIllegalArgumentException
- if:
public QualifiedType newQualifiedType(Type qualifier, SimpleName name)
qualifier
- the qualifier type nodename
- the simple name being qualifiedIllegalArgumentException
- if:
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic ReturnStatement newReturnStatement()
public SimpleName newSimpleName(String identifier)
identifier
- the identifierIllegalArgumentException
- if the identifier is invalidpublic SimpleType newSimpleType(Name typeName)
This method can be used to convert a name (Name
) into a
type (Type
) by wrapping it.
typeName
- the name of the class or interfaceIllegalArgumentException
- if:
public SingleMemberAnnotation newSingleMemberAnnotation()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic SingleVariableDeclaration newSingleVariableDeclaration()
public StringLiteral newStringLiteral()
public SuperConstructorInvocation newSuperConstructorInvocation()
Note that this type of node is a Statement, whereas a regular super method invocation is an Expression. The only valid use of these statements are as the first statement of a constructor body.
public SuperFieldAccess newSuperFieldAccess()
public SuperMethodInvocation newSuperMethodInvocation()
public SuperMethodReference newSuperMethodReference()
public SwitchCase newSwitchCase()
public SwitchStatement newSwitchStatement()
public SynchronizedStatement newSynchronizedStatement()
public TagElement newTagElement()
Note that this node type is used only inside doc comments
(Javadoc
).
public TextElement newTextElement()
Note that this node type is used only inside doc comments
(Javadoc
).
public ThisExpression newThisExpression()
public ThrowStatement newThrowStatement()
public TryStatement newTryStatement()
public TypeDeclaration newTypeDeclaration()
To create an interface, use this method and then call
TypeDeclaration.setInterface(true)
.
public TypeDeclarationStatement newTypeDeclarationStatement(AbstractTypeDeclaration decl)
This method can be used to convert any kind of type declaration
(AbstractTypeDeclaration
) into a statement
(Statement
) by wrapping it.
decl
- the type declarationIllegalArgumentException
- if:
public TypeDeclarationStatement newTypeDeclarationStatement(TypeDeclaration decl)
This method can be used to convert a type declaration
(TypeDeclaration
) into a statement
(Statement
) by wrapping it.
decl
- the type declarationIllegalArgumentException
- if:
public TypeLiteral newTypeLiteral()
public TypeMethodReference newTypeMethodReference()
UnsupportedOperationException
- if this operation is used in a JLS2, JLS3 or JLS4 ASTpublic TypeParameter newTypeParameter()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic UnionType newUnionType()
UnsupportedOperationException
- if this operation is used in
a JLS2 or JLS3 ASTpublic IntersectionType newIntersectionType()
UnsupportedOperationException
- if this operation is used in
a JLS2, JLS3 or JLS4 ASTpublic VariableDeclarationExpression newVariableDeclarationExpression(VariableDeclarationFragment fragment)
This method can be used to convert a variable declaration fragment
(VariableDeclarationFragment
) into an expression
(Expression
) by wrapping it. Additional variable
declaration fragments can be added afterwards.
fragment
- the first variable declaration fragmentIllegalArgumentException
- if:
public VariableDeclarationFragment newVariableDeclarationFragment()
public VariableDeclarationStatement newVariableDeclarationStatement(VariableDeclarationFragment fragment)
This method can be used to convert a variable declaration fragment
(VariableDeclarationFragment
) into a statement
(Statement
) by wrapping it. Additional variable
declaration fragments can be added afterwards.
fragment
- the variable declaration fragmentIllegalArgumentException
- if:
public WhileStatement newWhileStatement()
public WildcardType newWildcardType()
UnsupportedOperationException
- if this operation is used in
a JLS2 ASTpublic ITypeBinding resolveWellKnownType(String name)
Note that bindings are generally unavailable unless requested when the AST is being built.
The following type names are supported:
"boolean"
"byte"
"char"
"double"
"float"
"int"
"long"
"short"
"void"
"java.lang.AssertionError"
(since 3.7)"java.lang.Boolean"
(since 3.1)"java.lang.Byte"
(since 3.1)"java.lang.Character"
(since 3.1)"java.lang.Class"
"java.lang.Cloneable"
"java.lang.Double"
(since 3.1)"java.lang.Error"
"java.lang.Exception"
"java.lang.Float"
(since 3.1)"java.lang.Integer"
(since 3.1)"java.lang.Long"
(since 3.1)"java.lang.Object"
"java.lang.RuntimeException"
"java.lang.Short"
(since 3.1)"java.lang.String"
"java.lang.StringBuffer"
"java.lang.Throwable"
"java.lang.Void"
(since 3.1)"java.io.Serializable"
name
- the name of a well known typenull
if the
named type is not considered well known or if no binding can be found
for it
Copyright (c) 2000, 2015 Eclipse Contributors and others. All rights reserved.Guidelines for using Eclipse APIs.