public class ASTParser
extends java.lang.Object
Example: Create basic AST from source string
char[] source = ...; ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(source); JavaScriptUnit result = (JavaScriptUnit) parser.createAST(null);Once a configured parser instance has been used to create an AST, the settings are automatically reset to their defaults, ready for the parser instance to be reused.
There are a number of configurable features:
char[]
,
IJavaScriptUnit
,
or IClassFile
, and limited
to a specified subrange.Modifier and Type | Field and Description |
---|---|
static int |
K_CLASS_BODY_DECLARATIONS
Kind constant used to request that the source be parsed
as a sequence of class body declarations.
|
static int |
K_COMPILATION_UNIT
Kind constant used to request that the source be parsed
as a javaScript unit.
|
static int |
K_EXPRESSION
Kind constant used to request that the source be parsed
as a single expression.
|
static int |
K_STATEMENTS
Kind constant used to request that the source be parsed
as a sequence of statements.
|
Modifier and Type | Method and Description |
---|---|
ASTNode |
createAST(IProgressMonitor monitor)
Creates an abstract syntax tree.
|
void |
createASTs(IJavaScriptUnit[] compilationUnits,
java.lang.String[] bindingKeys,
ASTRequestor requestor,
IProgressMonitor monitor)
Creates ASTs for a batch of javaScript units.
|
IBinding[] |
createBindings(IJavaScriptElement[] elements,
IProgressMonitor monitor)
Creates bindings for a batch of JavaScript elements.
|
static ASTParser |
newParser(int level)
Creates a new object for creating a JavaScript abstract syntax tree
(AST) following the specified set of API rules.
|
void |
setBindingsRecovery(boolean enabled)
Requests that the validator should perform bindings recovery.
|
void |
setCompilerOptions(java.util.Map options)
Sets the validator options to be used when parsing.
|
void |
setFocalPosition(int position)
Requests an abridged abstract syntax tree.
|
void |
setKind(int kind)
Sets the kind of constructs to be parsed from the source.
|
void |
setProject(IJavaScriptProject project)
Sets the JavaScript project used when resolving bindings.
|
void |
setResolveBindings(boolean bindings)
Requests that the validator should provide binding information for
the AST nodes it creates.
|
void |
setSource(char[] source)
Sets the source code to be parsed.
|
void |
setSource(IClassFile source)
Sets the source code to be parsed.
|
void |
setSource(IJavaScriptUnit source)
Sets the source code to be parsed.
|
void |
setSource(ITypeRoot source)
Sets the source code to be parsed.
|
void |
setSourceRange(int offset,
int length)
Sets the subrange of the source code to be parsed.
|
void |
setStatementsRecovery(boolean enabled)
Requests that the validator should perform statements recovery.
|
void |
setUnitName(java.lang.String unitName)
Sets the name of the javaScript unit that would hypothetically contains
the source string.
|
void |
setWorkingCopyOwner(WorkingCopyOwner owner)
Sets the working copy owner using when resolving bindings, where
null means the primary owner. |
public static final int K_EXPRESSION
public static final int K_STATEMENTS
public static final int K_CLASS_BODY_DECLARATIONS
public static final int K_COMPILATION_UNIT
public static ASTParser newParser(int level)
level
- the API level; one of the LEVEL constants
declared on AST
public void setBindingsRecovery(boolean enabled)
Default to false
.
This should be set to true only if bindings are resolved. It has no effect if there is no binding resolution.
enabled
- true
if incomplete bindings are expected,
and false
if only complete bindings are expected.IBinding.isRecovered()
public void setCompilerOptions(java.util.Map options)
Note that setSource(IClassFile)
,
setSource(IJavaScriptUnit)
,
and setProject(IJavaScriptProject)
reset the validator options
based on the JavaScript project. In other cases, validator options default
to JavaScriptCore.getOptions()
. In either case, and especially
in the latter, the caller should carefully weight the consequences of
allowing validator options to be defaulted as opposed to being
explicitly specified for the ASTParser
instance.
For instance, there is a validator option called "Source Compatibility Mode"
which determines which JDK level the source code is expected to meet.
If you specify "1.4", then "assert" is treated as a keyword and disallowed
as an identifier; if you specify "1.3", then "assert" is allowed as an
identifier. So this particular setting has a major bearing on what is
considered syntactically legal. By explicitly specifying the setting,
the client control exactly how the parser works. On the other hand,
allowing default settings means the parsing behaves like other JDT tools.
options
- the table of options (key type: String
;
value type: String
), or null
to set it back to the defaultpublic void setResolveBindings(boolean bindings)
Default to false
(no bindings).
If setResolveBindings(true)
, the various names
and types appearing in the AST 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 setResolveBindings(false)
(the default), the analysis
does not go beyond parsing and building the tree, and all
resolveBinding
methods return null
from the
outset.
When bindings are requested, instead of considering javaScript units on disk only
one can supply a WorkingCopyOwner
. Working copies owned
by this owner take precedence over the underlying javaScript units when looking
up names and drawing the connections.
Binding information is obtained from the JavaScript model.
This means that the javaScript unit must be located relative to the
JavaScript model. This happens automatically when the source code comes from
either setSource(IJavaScriptUnit)
or setSource(IClassFile)
.
When source is supplied by setSource(char[])
,
the location must be extablished explicitly by calling
setProject(IJavaScriptProject)
and setUnitName(String)
.
Note that the validator options that affect doc comment checking may also
affect whether any bindings are resolved for nodes within doc comments.
bindings
- true
if bindings are wanted,
and false
if bindings are not of interestpublic void setFocalPosition(int position)
When true
the resulting AST does not have nodes for
the entire javaScript unit. Rather, the AST is only fleshed out
for the node that include the given source position. This kind of limited
AST is sufficient for certain purposes but totally unsuitable for others.
In places where it can be used, the limited AST offers the advantage of
being smaller and faster to construct.
The AST will include nodes for all of the javaScript unit's functions, top-level vars, package, import, and top-level type declarations. It will also always contain nodes for all the body declarations for those top-level types, as well as body declarations for any member types. However, some of the body declarations may be abridged. In particular, the statements ordinarily found in the body of a method declaration node will not be included (the block will be empty) unless the source position falls somewhere within the source range of that method declaration node. The same is true for initializer declarations; the statements ordinarily found in the body of initializer node will not be included unless the source position falls somewhere within the source range of that initializer declaration node. Field declarations are never abridged. Note that the AST for the body of that one unabridged method (or initializer) is 100% complete; it has all its statements, including any local or anonymous type declarations embedded within them. When the the given position is not located within the source range of any body declaration of a top-level type, the AST returned will be a skeleton that includes nodes for all and only the major declarations; this kind of AST is still quite useful because it contains all the constructs that introduce names visible to the world outside the javaScript unit.
position
- a position into the corresponding body declarationpublic void setKind(int kind)
When the parse is successful the result returned includes the ASTs for the requested source:
K_JAVASCRIPT_UNIT
: The result node
is a JavaScriptUnit
.K_CLASS_BODY_DECLARATIONS
: The result node
is a TypeDeclaration
whose
bodyDeclarations
are the new trees. Other aspects of the type declaration are unspecified.K_STATEMENTS
: The result node is a
Block
whose statements
are the new trees. Other aspects of the block are unspecified.K_EXPRESSION
: The result node is a subclass of
Expression
. Other aspects of the expression are unspecified.JavaScriptUnit
node, to allow the
client to retrieve the following pieces of information
available there:
source[offset]
through source[offset+length-1]
).source
; line positions are for the subrange scanned.JavaScriptUnit
node are unspecified, including
the exact arrangment of intervening nodes.
Lexical or syntax errors detected while parsing can result in
a result node being marked as MALFORMED
.
In more severe failure cases where the parser is unable to
recognize the input, this method returns
a JavaScriptUnit
node with at least the
validator messages.
Each node in the subtree (other than the contrived nodes) carries source range(s) information relating back to positions in the given source (the given source 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 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.
Binding information is only computed when kind
is
K_JAVASCRIPT_UNIT
.
kind
- the kind of construct to parse: one of
#K_JAVASCRIPT_UNIT
,
K_CLASS_BODY_DECLARATIONS
,
K_EXPRESSION
,
K_STATEMENTS
public void setSource(char[] source)
source
- the source string to be parsed,
or null
if nonepublic void setSource(IJavaScriptUnit source)
setProject(source.getJavaProject())
source
- the JavaScript model javaScript unit whose source code
is to be parsed, or null
if nonepublic void setSource(IClassFile source)
This method automatically sets the project (and compiler
options) based on the given javaScript unit, in a manner
equivalent to setProject(source.getJavaProject())
.
source
- the JavaScript file whose corresponding source code
is to be parsed, or null
if nonepublic void setSource(ITypeRoot source)
This method automatically sets the project (and compiler
options) based on the given javaScript unit, in a manner
equivalent to setProject(source.getJavaProject())
.
source
- the JavaScript model javaScript unit whose corresponding source code
is to be parsed, or null
if nonepublic void setSourceRange(int offset, int length)
offset
0 and length
-1).offset
- the index of the first character to parselength
- the number of characters to parse, or -1 if
the remainder of the source string ispublic void setStatementsRecovery(boolean enabled)
Default to false
.
enabled
- true
if statements containing syntax errors are wanted,
and false
if these statements aren't wanted.public void setWorkingCopyOwner(WorkingCopyOwner owner)
null
means the primary owner. Defaults to the primary owner.owner
- the owner of working copies that take precedence over underlying
javaScript units, or null
if the primary owner should be usedpublic void setUnitName(java.lang.String unitName)
setSource(char[])
and setProject(IJavaScriptProject)
to locate the javaScript unit relative to a JavaScript project.
Defaults to none (null
).
The name of the javaScript unit must be supplied for resolving bindings.
This name should be suffixed by a dot ('.') followed by one of the
JavaScript-like extensions
.
This name must represent the full path of the unit inside the given project. For example, if the source declares a public class named "Foo" in a project "P", the name of the javaScript unit must be "/P/Foo.js". If the source declares a public class name "Bar" in a package "p1.p2" in a project "P", the name of the javaScript unit must be "/P/p1/p2/Bar.js".
unitName
- the name of the javaScript unit that would contain the source
string, or null
if nonepublic void setProject(IJavaScriptProject project)
setCompilerOptions(project.getOptions(true));See
setCompilerOptions(Map)
for a discussion of
the pros and cons of using these options vs specifying
validator options explicitly.
This setting is used in conjunction with setSource(char[])
.
For the purposes of resolving bindings, types declared in the
source string will hide types by the same name available
through the includepath of the given project.
Defaults to none (null
).project
- the JavaScript project used to resolve names, or
null
if nonepublic ASTNode createAST(IProgressMonitor monitor)
A successful call to this method returns all settings to their default values so the object is ready to be reused.
monitor
- the progress monitor used to report progress and request cancelation,
or null
if noneJavaScriptUnit
in the case of severe parsing errorsjava.lang.IllegalStateException
- if the settings provided
are insufficient, contradictory, or otherwise unsupportedpublic void createASTs(IJavaScriptUnit[] compilationUnits, java.lang.String[] bindingKeys, ASTRequestor requestor, IProgressMonitor monitor)
When bindings are being resolved, all javaScript units must
come from the same JavaScript project, which must be set beforehand
with setProject
.
The javaScript units are processed one at a time in no
specified order. For each of the javaScript units in turn,
ASTParser.createAST
is called to parse it
and create a corresponding AST. The calls to
ASTParser.createAST
all employ the same settings.ASTRequestor.acceptAST
is called passing
the javaScript unit and the corresponding AST to
requestor
.
Note also the following parser parameters are used, regardless of what may have been specified:
K_JAVASCRIPT_UNIT
(0, -1)
The bindingKeys
parameter specifies bindings keys
(IBinding.getKey()
) that are to be looked up. These keys may
be for elements either inside or outside the set of compilation
units being processed. When bindings are being resolved,
the keys and corresponding bindings (or null
if none) are
passed to ASTRequestor.acceptBinding
. Note that binding keys
for elements outside the set of javaScript units being processed are looked up
after all ASTRequestor.acceptAST
callbacks have been made.
Binding keys for elements inside the set of javaScript units being processed
are looked up and reported right after the corresponding
ASTRequestor.acceptAST
callback has been made.
No ASTRequestor.acceptBinding
callbacks are made unless
bindings are being resolved.
A successful call to this method returns all settings to their default values so the object is ready to be reused.
compilationUnits
- the javaScript units to create ASTs forbindingKeys
- the binding keys to create bindings forrequestor
- the AST requestor that collects abtract syntax trees and bindingsmonitor
- the progress monitor used to report progress and request cancelation,
or null
if nonejava.lang.IllegalStateException
- if the settings provided
are insufficient, contradictory, or otherwise unsupportedpublic IBinding[] createBindings(IJavaScriptElement[] elements, IProgressMonitor monitor)
IJavaScriptUnit
s or in IClassFile
s.
All enclosing javaScript units must
come from the same JavaScript project, which must be set beforehand
with setProject
.
All elements must exist. If one doesn't exist, an IllegalStateException
is thrown.
The returned array has the same size as the given elements array. At a given position
it contains the binding of the corresponding JavaScript element, or null
if no binding could be created.
Note also the following parser parameters are used, regardless of what may have been specified:
true
K_JAVASCRIPT_UNIT
(0, -1)
A successful call to this method returns all settings to their default values so the object is ready to be reused.
elements
- the JavaScript elements to create bindings fornull
s
if some bindings could not be createdjava.lang.IllegalStateException
- if the settings provided
are insufficient, contradictory, or otherwise unsupportedCopyright (c) IBM Corp. and others 2000, 2010. All Rights Reserved.