Class AstNode
- java.lang.Object
-
- org.mozilla.javascript.Node
-
- org.mozilla.javascript.ast.AstNode
-
- Direct Known Subclasses:
ArrayLiteral,BigIntLiteral,Block,CatchClause,Comment,ConditionalExpression,ElementGet,EmptyExpression,EmptyStatement,ErrorNode,ExpressionStatement,FunctionCall,IfStatement,InfixExpression,Jump,KeywordLiteral,LabeledStatement,Name,NumberLiteral,ObjectLiteral,ParenthesizedExpression,RegExpLiteral,ReturnStatement,StringLiteral,SwitchCase,TaggedTemplateLiteral,TemplateCharacters,TemplateLiteral,ThrowStatement,TryStatement,UnaryExpression,UpdateExpression,VariableDeclaration,VariableInitializer,WithStatement,XmlFragment,XmlLiteral,XmlRef,Yield
public abstract class AstNode extends Node implements java.lang.Comparable<AstNode>
Base class for AST node types. The goal of the AST is to represent the physical source code, to make it useful for code-processing tools such as IDEs or pretty-printers. The parser must not rewrite the parse tree when producing this representation.The
AstNodehierarchy sits atop the olderNodeclass, which was designed for code generation. TheNodeclass is a flexible, weakly-typed class suitable for creating and rewriting code trees, but using it requires you to remember the exact ordering of the child nodes, which are kept in a linked list. TheAstNodehierarchy is a strongly-typed facade with named accessors for children and common properties, but under the hood it's still using a linked list of child nodes. It isn't a very good idea to use the child list directly unless you know exactly what you're doing. Note thatAstNoderecords additional information, including the node's position, length, and parent node. Also, someAstNodesubclasses record some of their child nodes in instance members, since they are not needed for code generation. In a nutshell, only the code generator should be mixing and matchingAstNodeandNodeobjects.All offset fields in all subclasses of AstNode are relative to their parent. For things like paren, bracket and keyword positions, the position is relative to the current node. The node start position is relative to the parent node.
During the actual parsing, node positions are absolute; adding the node to its parent fixes up the offsets to be relative. By the time you see the AST (e.g. using the
Visitorinterface), the offsets are relative.AstNodeobjects have property lists accessible via theNode.getProp(int)andNode.putProp(int, java.lang.Object)methods. The property lists are integer-keyed with arbitraryObjectvalues. For the most part the parser generating the AST avoids using properties, preferring fields for elements that are always set. Property lists are intended for user-defined annotations to the tree. The Rhino code generator acts as a client and uses node properties extensively. You are welcome to use the property-list API for anything your client needs.This hierarchy does not have separate branches for expressions and statements, as the distinction in JavaScript is not as clear-cut as in Java or C++.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static classAstNode.DebugPrintVisitorstatic classAstNode.PositionComparator-
Nested classes/interfaces inherited from class org.mozilla.javascript.Node
Node.NodeIterator
-
-
Field Summary
Fields Modifier and Type Field Description protected AstNodeinlineCommentprotected intlengthprotected AstNodeparentprotected intposition-
Fields inherited from class org.mozilla.javascript.Node
ARROW_FUNCTION_PROP, ATTRIBUTE_FLAG, BOTH, CASEARRAY_PROP, CATCH_SCOPE_PROP, CONTROL_BLOCK_PROP, DECR_FLAG, DESCENDANTS_FLAG, DESTRUCTURING_ARRAY_LENGTH, DESTRUCTURING_NAMES, DESTRUCTURING_PARAMS, DIRECTCALL_PROP, END_DROPS_OFF, END_RETURNS, END_RETURNS_VALUE, END_UNREACHED, END_YIELDS, EXPRESSION_CLOSURE_PROP, first, FUNCTION_PROP, GENERATOR_END_PROP, INCRDECR_PROP, ISNUMBER_PROP, JSDOC_PROP, LABEL_ID_PROP, last, LAST_PROP, LEFT, lineno, LOCAL_BLOCK_PROP, LOCAL_PROP, MEMBER_TYPE_PROP, NAME_PROP, next, NON_SPECIALCALL, OBJECT_IDS_PROP, PARENTHESIZED_PROP, POST_FLAG, PROPERTY_FLAG, propListHead, REGEXP_PROP, RIGHT, SHORTHAND_PROPERTY_NAME, SKIP_INDEXES_PROP, SPECIALCALL_EVAL, SPECIALCALL_PROP, SPECIALCALL_WITH, TARGETBLOCK_PROP, TEMPLATE_LITERAL_PROP, TRAILING_COMMA, type, VARIABLE_PROP
-
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description voidaddChild(AstNode kid)Adds a child or function to the end of the block.protected voidassertNotNull(java.lang.Object arg)Bounces an IllegalArgumentException up if arg isnull.static java.lang.RuntimeExceptioncodeBug()intcompareTo(AstNode other)Permits AST nodes to be sorted based on start position and length.java.lang.StringdebugPrint()Returns a debugging representation of the parse tree starting at this node.intdepth()Returns the depth of this node.intgetAbsolutePosition()Returns the absolute document position of the node.AstRootgetAstRoot()Returns the root of the tree containing this node.FunctionNodegetEnclosingFunction()Returns the innermost enclosing function, ornullif not in a function.ScopegetEnclosingScope()Returns the innermost enclosingScopenode, ornullif we're not nested in a scope.AstNodegetInlineComment()intgetLength()Returns node lengthintgetLineno()Return the line number recorded for this node.AstNodegetParent()Returns the node parent, ornullif it has noneintgetPosition()Returns relative position in parentbooleanhasSideEffects()java.lang.StringmakeIndent(int indent)Constructs an indentation string.static java.lang.StringoperatorToString(int op)Returns the string name for this operator.protected <T extends AstNode>
voidprintList(java.util.List<T> items, java.lang.StringBuilder sb)Prints a comma-separated item list into aStringBuilder.voidsetBounds(int position, int end)Sets the node start and end positions.voidsetInlineComment(AstNode inlineComment)voidsetLength(int length)Sets node lengthvoidsetParent(AstNode parent)Sets the node parent.voidsetPosition(int position)Sets relative position in parentvoidsetRelative(int parentPosition)Make this node's position relative to a parent.java.lang.StringshortName()Returns a short, descriptive name for the node, such as "ArrayComprehension".java.lang.StringtoSource()Prints the source indented to depth 0.abstract java.lang.StringtoSource(int depth)Emits source code for this node.abstract voidvisit(NodeVisitor visitor)Visits this node and its children in an arbitrary order.-
Methods inherited from class org.mozilla.javascript.Node
addChildAfter, addChildBefore, addChildrenToBack, addChildrenToFront, addChildToBack, addChildToFront, getBigInt, getChildBefore, getDouble, getExistingIntProp, getFirstChild, getIntProp, getJsDoc, getJsDocNode, getLastChild, getLastSibling, getNext, getProp, getScope, getString, getType, hasChildren, hasConsistentReturnUsage, iterator, labelId, labelId, newNumber, newString, newString, newTarget, putIntProp, putProp, removeChild, removeChildren, removeProp, replaceChild, replaceChildAfter, resetTargets, setBigInt, setDouble, setJsDocNode, setLineno, setScope, setString, setType, toString, toStringTree
-
-
-
-
Constructor Detail
-
AstNode
public AstNode()
-
AstNode
public AstNode(int pos)
Constructs a new AstNode- Parameters:
pos- the start position
-
AstNode
public AstNode(int pos, int len)Constructs a new AstNode- Parameters:
pos- the start positionlen- the number of characters spanned by the node in the source text
-
-
Method Detail
-
getPosition
public int getPosition()
Returns relative position in parent
-
setPosition
public void setPosition(int position)
Sets relative position in parent
-
getAbsolutePosition
public int getAbsolutePosition()
Returns the absolute document position of the node. Computes it by adding the node's relative position to the relative positions of all its parents.
-
getLength
public int getLength()
Returns node length
-
setLength
public void setLength(int length)
Sets node length
-
setBounds
public void setBounds(int position, int end)Sets the node start and end positions. Computes the length as (end-position).
-
setRelative
public void setRelative(int parentPosition)
Make this node's position relative to a parent. Typically only used by the parser when constructing the node.- Parameters:
parentPosition- the absolute parent position; the current node position is assumed to be absolute and is decremented by parentPosition.
-
getParent
public AstNode getParent()
Returns the node parent, ornullif it has none
-
setParent
public void setParent(AstNode parent)
Sets the node parent. This method automatically adjusts the current node's start position to be relative to the new parent.- Parameters:
parent- the new parent. Can benull.
-
addChild
public void addChild(AstNode kid)
Adds a child or function to the end of the block. Sets the parent of the child to this node, and fixes up the start position of the child to be relative to this node. Sets the length of this node to include the new child.- Parameters:
kid- the child- Throws:
java.lang.IllegalArgumentException- if kid isnull
-
getAstRoot
public AstRoot getAstRoot()
Returns the root of the tree containing this node.- Returns:
- the
AstRootat the root of this node's parent chain, ornullif the topmost parent is not anAstRoot.
-
toSource
public abstract java.lang.String toSource(int depth)
Emits source code for this node. Callee is responsible for calling this function recursively on children, incrementing indent as appropriate.Note: if the parser was in error-recovery mode, some AST nodes may have
nullchildren that are expected to be non-nullwhen no errors are present. In this situation, the behavior of thetoSourcemethod is undefined:toSourceimplementations may assume that the AST node is error-free, since it is intended to be invoked only at runtime after a successful parse.- Parameters:
depth- the current recursion depth, typically beginning at 0 when called on the root node.
-
toSource
public java.lang.String toSource()
Prints the source indented to depth 0.
-
makeIndent
public java.lang.String makeIndent(int indent)
Constructs an indentation string.- Parameters:
indent- the number of indentation steps
-
shortName
public java.lang.String shortName()
Returns a short, descriptive name for the node, such as "ArrayComprehension".
-
operatorToString
public static java.lang.String operatorToString(int op)
Returns the string name for this operator.- Parameters:
op- the token type, e.g.Token.ADDorToken.TYPEOF- Returns:
- the source operator string, such as "+" or "typeof"
-
visit
public abstract void visit(NodeVisitor visitor)
Visits this node and its children in an arbitrary order.It's up to each node subclass to decide the order for processing its children. The subclass also decides (and should document) which child nodes are not passed to the
NodeVisitor. For instance, nodes representing keywords likeeachorinmay not be passed to the visitor object. The visitor can simply query the current node for these children if desired.Generally speaking, the order will be deterministic; the order is whatever order is decided by each child node. Normally child nodes will try to visit their children in lexical order, but there may be exceptions to this rule.
- Parameters:
visitor- the object to call with this node and its children
-
hasSideEffects
public boolean hasSideEffects()
- Overrides:
hasSideEffectsin classNode
-
assertNotNull
protected void assertNotNull(java.lang.Object arg)
Bounces an IllegalArgumentException up if arg isnull.- Parameters:
arg- any method argument- Throws:
java.lang.IllegalArgumentException- if the argument isnull
-
printList
protected <T extends AstNode> void printList(java.util.List<T> items, java.lang.StringBuilder sb)
Prints a comma-separated item list into aStringBuilder.- Parameters:
items- a list to printsb- aStringBuilderinto which to print
-
codeBug
public static java.lang.RuntimeException codeBug() throws java.lang.RuntimeException- Throws:
java.lang.RuntimeException- See Also:
Kit.codeBug()
-
getEnclosingFunction
public FunctionNode getEnclosingFunction()
Returns the innermost enclosing function, ornullif not in a function. Begins the search with this node's parent.- Returns:
- the
FunctionNodeenclosing this node, elsenull
-
getEnclosingScope
public Scope getEnclosingScope()
Returns the innermost enclosingScopenode, ornullif we're not nested in a scope. Begins the search with this node's parent. Note that this is not the same as the defining scope for aName.- Returns:
- the
Scopeenclosing this node, elsenull
-
compareTo
public int compareTo(AstNode other)
Permits AST nodes to be sorted based on start position and length. This makes it easy to sort Comment and Error nodes into a set of other AST nodes: just put them all into aSortedSet, for instance.- Specified by:
compareToin interfacejava.lang.Comparable<AstNode>- Parameters:
other- another node- Returns:
- -1 if this node's start position is less than
other's start position. If tied, -1 if this node's length is less thanother's length. If the lengths are equal, sorts abitrarily on hashcode unless the nodes are the same perObject.equals(java.lang.Object).
-
depth
public int depth()
Returns the depth of this node. The root is depth 0, its children are depth 1, and so on.- Returns:
- the node depth in the tree
-
getLineno
public int getLineno()
Return the line number recorded for this node. If no line number was recorded, searches the parent chain.
-
debugPrint
public java.lang.String debugPrint()
Returns a debugging representation of the parse tree starting at this node.- Returns:
- a very verbose indented printout of the tree. The format of each line is: abs-pos name position length [identifier]
-
getInlineComment
public AstNode getInlineComment()
-
setInlineComment
public void setInlineComment(AstNode inlineComment)
-
-