Class NodeUtil
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final record
Represents a goog.require'd namespace and property inside a module.static enum
static interface
Interface for use with the visit method. -
Method Summary
Modifier and TypeMethodDescriptionstatic boolean
canMergeBlock
(Node block) A check inside a block to see if there are const, let, class, or function declarations to be safe and not hoist them into the upper block.static com.google.common.collect.ImmutableSet
<String> collectExternVariableNames
(AbstractCompiler compiler, Node externs) static int
countAstSize
(Node n) static void
deleteChildren
(Node n, AbstractCompiler compiler) Permanently delete all the children of the given node, including reporting changes.static void
deleteFunctionCall
(Node n, AbstractCompiler compiler) Permanently delete the given call from the AST while maintaining a valid node structure, as well as report the related AST changes to the given compiler.static void
deleteNode
(Node n, AbstractCompiler compiler) Permanently delete the given node from the AST, as well as report the related AST changes/deletions to the given compiler.static Node
static int
estimateNumLines
(Node scriptNode) Estimates the number of lines in the file of this script node.static @Nullable Node
findPreorder
(Node node, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred) Returns the first Node matching the given pred via a pre-order traversal.static @Nullable Node
For an assignment or variable declaration get the assigned value.static @Nullable JSDocInfo
Find the best JSDoc for the given node.static @Nullable Node
Deprecated.because we want to control the input node tokens accepted by this function.static @Nullable Node
Find the best JSDocInfo node for the given node.static @Nullable Node
Find the l-value that the given r-value is being assigned to.static @Nullable String
getBestLValueName
(@Nullable Node lValue) Get the name of the given l-value node.static Node
Returns the call target for a call expression, resolving an indirected call (`(0, foo)()`) if present.static Node
static int
getCount
(Node n, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred) static @Nullable JSTypeExpression
getDeclaredTypeExpression
(Node declaration) Return declared JSDoc type for the given name declaration, or null if none present.static Node
getDeclaringParent
(Node targetNode) Returns the node that is effectively declaring the given target.static Node
Finds the block containing the given node.static Node
static Node
Finds the class containing the given node.static Node
Finds the function containing the given node.static Node
Return the nearest enclosing hoist scope root node, null for the global scope.static Node
static Node
getEnclosingNode
(Node n, com.google.common.base.Predicate<Node> pred) static Node
static Node
Finds the script containing the given node.static Node
static Node
getEnclosingType
(Node n, Token type) Gets the closest ancestor to the given node of the provided type.static @Nullable Node
getEs6ClassConstructorMemberFunctionDef
(Node classNode) static Node
getFunctionBody
(Node fn) Return a BLOCK node for the given FUNCTION node.static Node
getFunctionParameters
(Node fnNode) static @Nullable NodeUtil.GoogRequire
getGoogRequireInfo
(Var var) static @Nullable NodeUtil.GoogRequire
getGoogRequireInfo
(Node nameNode) static @Nullable NodeUtil.GoogRequire
getGoogRequireInfo
(String name, Scope scope) static @Nullable InputId
getInputId
(Node n) static NodeUtil.ValueType
Evaluate a node's token and attempt to determine which primitive value type it could resolve to Without proper type information some assumptions had to be made for operations that could result in a BigInt or a Number.static @Nullable Node
static @Nullable String
static @Nullable Node
getNameNode
(Node n) Gets the node of a function or class's name.static @Nullable String
Gets the function's name.static void
getParamOrPatternNames
(Node n, Consumer<Node> cb) Callscb
with all NAMEs declared in a PARAM_LIST or destructuring pattern.getParentChangeScopeNodes
(List<Node> scopeNodes) Returns the list of scope nodes which are parents of the provided list of scope nodes.static Node
getRootOfQualifiedName
(Node qName) Gets the root node of a qualified name.static Node
getRootTarget
(Node targetNode) Returns the outermost target enclosing the given assignment target.static @Nullable Node
Gets the r-value (or initializer) of a node returned by getBestLValue.static StaticSourceFile
static String
static @Nullable String
Gets the value of a node as a String, or null if it cannot be converted.static boolean
has
(Node node, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred) static boolean
static boolean
Returns true if the operator is an assignment type operator.static boolean
Returns true if the result of node evaluation is always a bigintstatic boolean
static boolean
static boolean
isCallOrNew
(Node node) static boolean
A faster version ofisCallTo(Node, String)
.static boolean
isCallTo
(Node n, QualifiedName qualifiedName) static boolean
static boolean
Is this a class declaration.static boolean
static boolean
Determines whether the given node is a FOR, DO, WHILE, WITH, or IF node.static boolean
Determines whether this node is used as an L-value that is a declaration.static boolean
isEmptyBlock
(Node block) Returns whether this a BLOCK node with no children.static boolean
static boolean
isEs6Constructor
(Node fnNode) static boolean
isEs6ConstructorMemberFunctionDef
(Node memberFunctionDef) static boolean
isExprCall
(Node n) Is this node a call expression statement?static boolean
isExpressionResultUsed
(Node expr) static boolean
Determine if the given SCRIPT is a @typeSummary file, like an i.js filestatic boolean
Is this node a function declaration? A function declaration is a function that has a name that is added to the current scope (i.e.static boolean
static boolean
static boolean
Is this node a hoisted function declaration? A function declaration in the scope root is hoisted to the top of the scope.static boolean
static boolean
static boolean
isInFunction
(Node n) static boolean
Returns true if the node is a lhs value of a destructuring assignment.static boolean
static boolean
isLiteralValue
(Node n, boolean includeFunctions) Returns true if this is a literal value.static boolean
Returns true if the operator is a logical assignment type operator.static boolean
Determines whether the given node is a FOR, DO, or WHILE node.static boolean
Determines whether this node is used as an L-value.static boolean
Is this node a class or object literal member function?static boolean
Is this node a name declaration?static boolean
isNameDeclOrSimpleAssignLhs
(Node n, Node parent) Determines whether this node is strictly on the left hand side of an assign or var initialization.static boolean
isNamedExportsLiteral
(Node objectLiteral) Whether this is an assignment to 'exports' that creates named exports.static boolean
Returns true iff this node defines a namespace, e.g.,static boolean
isNormalGet
(Node n) Is this a GETPROP or GETELEM node?static boolean
Is this a CALL or OPTCHAIN_CALL?static boolean
Is this a GETPROP, OPTCHAIN_GETPROP, GETELEM, or OPTCHAIN_GETELEM?static boolean
Is this a GETPROP or OPTCHAIN_GETPROP?static boolean
static boolean
Returns true if the result of node evaluation is always a numberstatic boolean
Returnstrue
if the node is a definition with Object.definePropertiesstatic boolean
static boolean
isObjLitProperty
(Node node) Returns true if the node is a property of an object literal.static boolean
Is this an OPTCHAIN_GETPROP or OPTCHAIN_GETELEM node?static boolean
Is this a OPTCHAIN_GETPROP, OPTCHAIN_GETELEM, OPTCHAIN_CALL node?static boolean
static boolean
Whether the given node's subtree may contain statements, excepting nested functionsstatic boolean
isStatement
(Node n) static boolean
static boolean
isStatementParent
(Node parent) static boolean
static boolean
isTopLevel
(Node n) static boolean
isUndefined
(Node n) static boolean
isValidQualifiedName
(CompilerOptions.LanguageMode mode, String name) Deprecated.static boolean
isValidQualifiedName
(FeatureSet mode, String name) Determines whether the given name is a valid qualified name.static void
markFunctionsDeleted
(Node node, AbstractCompiler compiler) Recurses through a tree, marking all function nodes deleted.static Node
newDeclaration
(Node lhs, @Nullable Node rhs, Token declarationType) static Node
newPropertyAccess
(AbstractCompiler compiler, Node context, String name) Creates a property access on thecontext
tree.static Node
newQName
(AbstractCompiler compiler, String name) Creates a node representing a qualified name.static Node
newQNameDeclaration
(AbstractCompiler compiler, String name, Node value, JSDocInfo info) Creates a node representing a qualified name.static Node
newQNameDeclaration
(AbstractCompiler compiler, String name, Node value, JSDocInfo info, Token type) Creates a node representing a qualified name.static Node
newUndefinedNode
(Node srcReferenceNode) Create a node for an empty result expression: "void 0"static @Nullable String
Converts an operator's token value (seeToken
) to a string representation.static int
precedence
(Token type) The comma operator has the lowest precedence, 0, followed by the assignment operators (=
,&=
,+=
, etc.) which have precedence of 1, and so on.preOrderIterable
(Node root) Same aspreOrderIterable(Node, Predicate)
but iterates over all nodes in the tree without exception.preOrderIterable
(Node root, com.google.common.base.Predicate<Node> travserseNodePredicate) Create anIterable
over the given node and all descendents.static void
removeChild
(Node parent, Node node) Safely remove children while maintaining a valid node structure.static void
removeName
(Node n) Set the given function/class node to an empty nameremoveNestedChangeScopeNodes
(List<Node> scopeNodes) Removes any scope nodes from the provided list that are nested within some other scope node also in the list.static void
replaceDeclarationChild
(Node declChild, Node newStatement) Replace the child of a var/let/const declaration (usually a name) with a new statement.static boolean
tryMergeBlock
(Node block, boolean ignoreBlockScopedDeclarations) Merge a block with its parent block.static void
visitLhsNodesInDestructuringPattern
(Node destructuringPattern, Consumer<Node> consumer) Retrieves lhs nodes declared or assigned in a given destructuring pattern node.static void
visitLhsNodesInNode
(Node assigningParent, Consumer<Node> consumer) Retrieves lhs nodes declared or assigned in a given assigning parent node.static void
visitPostOrder
(Node node, NodeUtil.Visitor visitor) A post-order traversal, calling Visitor.visit for each decendent.static void
visitPostOrder
(Node node, NodeUtil.Visitor visitor, com.google.common.base.Predicate<Node> traverseChildrenPred) A post-order traversal, calling Visitor.visit for each node in the tree.static void
visitPreOrder
(Node node, NodeUtil.Visitor visitor) A pre-order traversal, calling Visitor.visit for each decendent.static void
visitPreOrder
(Node node, NodeUtil.Visitor visitor, com.google.common.base.Predicate<Node> traverseChildrenPred) A pre-order traversal, calling Visitor.visit for each node in the tree.
-
Method Details
-
getStringValue
Gets the value of a node as a String, or null if it cannot be converted. When it returns a non-null String, this method effectively emulates theString()
JavaScript cast function.IMPORTANT: This method does not consider whether
n
may have side effects. -
getName
- Parameters:
n
- A function or class node.- Returns:
- The name of the given function or class, if it has one.
-
getNameNode
Gets the node of a function or class's name. This method recognizes five forms:class name {...}
var name = class {...}
qualified.name = class {...}
var name2 = class name1 {...}
qualified.name2 = class name1 {...}
- Parameters:
n
- A function or class node- Returns:
- the node best representing the class's name
-
removeName
Set the given function/class node to an empty name -
getNearestFunctionName
Gets the function's name. This method recognizes the forms:{'name': function() ...}
{name: function() ...}
function name() ...
var name = function() ...
var obj = {name() {} ...}
qualified.name = function() ...
var name2 = function name1() ...
qualified.name2 = function name1() ...
- Parameters:
n
- a node whose type isToken.FUNCTION
- Returns:
- the function's name, or
null
if it has no name
-
getClassMembers
-
getEs6ClassConstructorMemberFunctionDef
-
isLiteralValue
Returns true if this is a literal value. We define a literal value as any node that evaluates to the same thing regardless of when or where it is evaluated. So /xyz/ and [3, 5] are literals, but the name a is not.Function literals do not meet this definition, because they lexically capture variables. For example, if you have
function() { return a; }
If it is evaluated in a different scope, then it captures a different variable. Even if the function did not read any captured variables directly, it would still fail this definition, because it affects the lifecycle of variables in the enclosing scope.However, a function literal with respect to a particular scope is a literal.
- Parameters:
includeFunctions
- If true, all function expressions will be treated as literals.
-
isEmptyBlock
Returns whether this a BLOCK node with no children.- Parameters:
block
- The node.
-
isNamespaceDecl
Returns true iff this node defines a namespace, e.g.,/** @const * / var goog = {}; /** @const * / var goog = goog || {}; /** @const * / goog.math = goog.math || {};
-
isFromTypeSummary
Determine if the given SCRIPT is a @typeSummary file, like an i.js file -
precedence
The comma operator has the lowest precedence, 0, followed by the assignment operators (=
,&=
,+=
, etc.) which have precedence of 1, and so on.See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
-
isUndefined
-
isNullOrUndefined
-
getKnownValueType
Evaluate a node's token and attempt to determine which primitive value type it could resolve to Without proper type information some assumptions had to be made for operations that could result in a BigInt or a Number. If there is not enough information available to determine one or the other then we assume Number in order to maintain historical behavior of the compiler and avoid breaking projects that relied on this behavior. -
isNumericResult
Returns true if the result of node evaluation is always a number -
isBigIntResult
Returns true if the result of node evaluation is always a bigint -
isBooleanResult
- Returns:
- Whether the result of node evaluation is always a boolean
-
isStringResult
- Returns:
- Whether the result of node evaluation is always a string
-
isObjectResult
- Returns:
- Whether the result of node evaluation is always an object
-
isAssignmentOp
Returns true if the operator is an assignment type operator. Note: The logical assignments (i.e. ASSIGN_OR, ASSIGN_AND, ASSIGN_COALESCE) follow short-circuiting behavior, and the RHS may not always be evaluated. They are still considered AssignmentOps (may be optimized). -
isLogicalAssignmentOp
Returns true if the operator is a logical assignment type operator. -
isCompoundAssignmentOp
-
getEnclosingType
Gets the closest ancestor to the given node of the provided type. -
getEnclosingClass
Finds the class containing the given node. -
getEnclosingModuleIfPresent
-
getEnclosingFunction
Finds the function containing the given node. -
getEnclosingScript
Finds the script containing the given node. -
getEnclosingBlock
Finds the block containing the given node. -
getEnclosingBlockScopeRoot
-
getEnclosingScopeRoot
-
getEnclosingHoistScopeRoot
Return the nearest enclosing hoist scope root node, null for the global scope. There are currently 4 such roots to consider: the global, module, function, and class static blocks. -
isHoistScopeRoot
-
isInFunction
-
getEnclosingStatement
-
getEnclosingNode
-
isNormalOrOptChainGet
Is this a GETPROP, OPTCHAIN_GETPROP, GETELEM, or OPTCHAIN_GETELEM? -
isNormalOrOptChainGetProp
Is this a GETPROP or OPTCHAIN_GETPROP? -
isNormalOrOptChainCall
Is this a CALL or OPTCHAIN_CALL? -
isNormalGet
Is this a GETPROP or GETELEM node? -
isOptChainGet
Is this an OPTCHAIN_GETPROP or OPTCHAIN_GETELEM node? -
isOptChainNode
Is this a OPTCHAIN_GETPROP, OPTCHAIN_GETELEM, OPTCHAIN_CALL node? -
isNameDeclaration
Is this node a name declaration?- Parameters:
n
- The node- Returns:
- True if
n
is VAR, LET or CONST
-
getAssignedValue
For an assignment or variable declaration get the assigned value.- Returns:
- The value node representing the new value.
-
isExprCall
Is this node a call expression statement?- Parameters:
n
- The node- Returns:
- True if
n
is EXPR_RESULT andn
's first child is CALL
-
isEnhancedFor
-
isAnyFor
-
isLoopStructure
Determines whether the given node is a FOR, DO, or WHILE node. -
getLoopCodeBlock
- Parameters:
n
- The node to inspect.- Returns:
- If the node, is a FOR, WHILE, or DO, it returns the node for the code BLOCK, null otherwise.
-
isControlStructure
Determines whether the given node is a FOR, DO, WHILE, WITH, or IF node. -
isStatementBlock
- Returns:
- Whether the node is of a type that contain other statements.
-
isStatement
- Returns:
- Whether the node is used as a statement.
-
isStatementParent
-
deleteNode
Permanently delete the given node from the AST, as well as report the related AST changes/deletions to the given compiler. -
deleteFunctionCall
Permanently delete the given call from the AST while maintaining a valid node structure, as well as report the related AST changes to the given compiler. In some cases, this is done by deleting the parent from the AST and is come cases expression is replaced byundefined
. -
deleteChildren
Permanently delete all the children of the given node, including reporting changes. -
removeChild
Safely remove children while maintaining a valid node structure. In some cases, this is done by removing the parent from the AST as well. -
replaceDeclarationChild
Replace the child of a var/let/const declaration (usually a name) with a new statement. Preserves the order of side effects for all the other declaration children.- Parameters:
declChild
- The name node to be replaced.newStatement
- The statement to replace with.
-
tryMergeBlock
Merge a block with its parent block.- Parameters:
ignoreBlockScopedDeclarations
- merge the block regardless of any inner block-scoped declarations that may cause name collisions. use if e.g. the AST is normalized- Returns:
- Whether the block was removed.
-
canMergeBlock
A check inside a block to see if there are const, let, class, or function declarations to be safe and not hoist them into the upper block.- Returns:
- Whether the block can be removed
-
isCallOrNew
- Parameters:
node
- A node- Returns:
- Whether the call is a NEW or CALL node.
-
getFunctionBody
Return a BLOCK node for the given FUNCTION node. -
getCallTargetResolvingIndirectCalls
Returns the call target for a call expression, resolving an indirected call (`(0, foo)()`) if present. -
isNamedExportsLiteral
Whether this is an assignment to 'exports' that creates named exports.- exports = {a, b}; // named export, returns true.
- exports = 0; // namespace export, returns false.
- exports = {a: 0, b}; // namespace export, returns false.
-
isFunctionDeclaration
Is this node a function declaration? A function declaration is a function that has a name that is added to the current scope (i.e. a function that is not part of a expression; seeisFunctionExpression(com.google.javascript.rhino.Node)
). -
isMethodDeclaration
Is this node a class or object literal member function?examples:
class C { f() {} get x() { return this.x_; } set x(v) { this.x_ = v; } [someExpr]() {} } obj = { f() {} get x() { return this.x_; } set x(v) { this.x_ = v; } [someExpr]() {} }
-
isClassDeclaration
Is this a class declaration. -
isHoistedFunctionDeclaration
Is this node a hoisted function declaration? A function declaration in the scope root is hoisted to the top of the scope. SeeisFunctionDeclaration(com.google.javascript.rhino.Node)
). -
isNameDeclOrSimpleAssignLhs
Determines whether this node is strictly on the left hand side of an assign or var initialization. Notably, this does not include all L-values, only statements where the node is used only as an L-value.- Parameters:
n
- The nodeparent
- Parent of the node- Returns:
- True if n is the left hand of an assign
-
isLValue
Determines whether this node is used as an L-value. Notice that sometimes names are used as both L-values and R-values.We treat "var x;" and "let x;" as an L-value because it's syntactically similar to "var x = undefined", even though it's technically not an L-value. But it kind of makes sense if you treat it as "assignment to 'undefined' at the top of the scope".
- Parameters:
n
- The node- Returns:
- True if n is an L-value.
-
isDeclarationLValue
Determines whether this node is used as an L-value that is a declaration.x = 5;
is an L-value but does not declare a variable. -
isLhsOfAssign
-
isImportedName
-
getDeclaringParent
Returns the node that is effectively declaring the given target.Examples:
const a = 1; // getDeclaringParent(a) returns CONST let {[expression]: [x = 3]} = obj; // getDeclaringParent(x) returns LET function foo({a, b}) {}; // getDeclaringParent(a) returns PARAM_LIST function foo(a = 1) {}; // getDeclaringParent(a) returns PARAM_LIST function foo({a, b} = obj) {}; // getDeclaringParent(a) returns PARAM_LIST function foo(...a) {}; // getDeclaringParent(a) returns PARAM_LIST function foo() {}; // gotRootTarget(foo) returns FUNCTION class foo {}; // gotRootTarget(foo) returns CLASS import foo from './foo'; // getDeclaringParent(foo) returns IMPORT import {foo} from './foo'; // getDeclaringParent(foo) returns IMPORT import {foo as bar} from './foo'; // getDeclaringParent(bar) returns IMPORT } catch (err) { // getDeclaringParent(err) returns CATCH
- Parameters:
targetNode
- a NAME, OBJECT_PATTERN, or ARRAY_PATTERN- Returns:
- node of type LET, CONST, VAR, FUNCTION, CLASS, PARAM_LIST, CATCH, or IMPORT
- Throws:
IllegalStateException
- if targetNode is not actually used as a declaration target
-
getRootTarget
Returns the outermost target enclosing the given assignment target.Returns targetNode itself if there is no enclosing target.
Examples:
const a = 1; // getRootTarget(a) returns a let {[expression]: [x = 3]} = obj; // getRootTarget(x) returns {[expression]: [x = 3]} {a = 1} = obj; // getRootTarget(a) returns {a = 1} {[expression]: [x = 3]} = obj; // getRootTarget(x) returns {[expression]: [x = 3]} function foo({a, b}) {}; // getRootTarget(a) returns {a, b} function foo(a = 1) {}; // getRootTarget(a) returns a function foo({a, b} = obj) {}; // getRootTarget(a) returns a function foo(...a) {}; // getRootTarget(a) returns a function foo() {}; // gotRootTarget(foo) returns foo class foo {}; // gotRootTarget(foo) returns foo import foo from './foo'; // getRootTarget(foo) returns foo import {foo} from './foo'; // getRootTarget(foo) returns foo import {foo as bar} from './foo'; // getRootTarget(bar) returns bar
- Throws:
IllegalStateException
- if targetNode is not actually used as a target
-
isLhsByDestructuring
Returns true if the node is a lhs value of a destructuring assignment.For example, x in
var [x] = [1];
,var [...x] = [1];
, andvar {a: x} = {a: 1}
or a.b in([a.b] = [1]);
or({key: a.b} = {key: 1});
-
opToStr
Converts an operator's token value (seeToken
) to a string representation.- Parameters:
operator
- the operator's token value to convert- Returns:
- the string representation or
null
if the token value is not an operator
-
newDeclaration
-
newQName
Creates a node representing a qualified name.- Parameters:
name
- A qualified name (e.g. "foo" or "foo.bar.baz")- Returns:
- A NAME or GETPROP node
-
newPropertyAccess
Creates a property access on thecontext
tree. -
newQNameDeclaration
public static Node newQNameDeclaration(AbstractCompiler compiler, String name, Node value, JSDocInfo info) Creates a node representing a qualified name.- Parameters:
name
- A qualified name (e.g. "foo" or "foo.bar.baz")- Returns:
- A VAR node, or an EXPR_RESULT node containing an ASSIGN or NAME node.
-
newQNameDeclaration
public static Node newQNameDeclaration(AbstractCompiler compiler, String name, Node value, JSDocInfo info, Token type) Creates a node representing a qualified name.- Parameters:
name
- A qualified name (e.g. "foo" or "foo.bar.baz")type
- Must be VAR, CONST, or LET. Ignored ifname
is dotted.- Returns:
- A VAR/CONST/LET node, or an EXPR_RESULT node containing an ASSIGN or NAME node.
-
getRootOfQualifiedName
Gets the root node of a qualified name. Must be either NAME, THIS or SUPER. -
isValidQualifiedName
@InlineMe(replacement="NodeUtil.isValidQualifiedName(mode.toFeatureSet(), name)", imports="com.google.javascript.jscomp.NodeUtil") @Deprecated public static boolean isValidQualifiedName(CompilerOptions.LanguageMode mode, String name) Deprecated. -
isValidQualifiedName
Determines whether the given name is a valid qualified name. -
visitLhsNodesInNode
Retrieves lhs nodes declared or assigned in a given assigning parent node.An assigning parent node is one that assigns a value to one or more LHS nodes.
-
visitLhsNodesInDestructuringPattern
public static void visitLhsNodesInDestructuringPattern(Node destructuringPattern, Consumer<Node> consumer) Retrieves lhs nodes declared or assigned in a given destructuring pattern node. -
isObjectDefinePropertiesDefinition
Returnstrue
if the node is a definition with Object.defineProperties -
isPrototypePropertyDeclaration
- Returns:
true
if the node an assignment to a prototype property of some constructor.
-
newUndefinedNode
Create a node for an empty result expression: "void 0" -
emptyFunction
-
isShallowStatementTree
Whether the given node's subtree may contain statements, excepting nested functionsThis is useful for traversing all statements in a given script or function without traversing into nested functions, so it will return true for e.g. a BLOCK or SWITCH statement.
-
has
public static boolean has(Node node, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred) - Returns:
- Whether the predicate is true for the node or any of its descendants.
-
findPreorder
public static @Nullable Node findPreorder(Node node, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred) Returns the first Node matching the given pred via a pre-order traversal. -
getCount
public static int getCount(Node n, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred) - Returns:
- The number of times the predicate is true for the node or any of its descendants.
-
visitPreOrder
A pre-order traversal, calling Visitor.visit for each decendent. -
visitPreOrder
public static void visitPreOrder(Node node, NodeUtil.Visitor visitor, com.google.common.base.Predicate<Node> traverseChildrenPred) A pre-order traversal, calling Visitor.visit for each node in the tree. Children of nodes that do not match the predicate will not be visited. -
visitPostOrder
A post-order traversal, calling Visitor.visit for each decendent. -
visitPostOrder
public static void visitPostOrder(Node node, NodeUtil.Visitor visitor, com.google.common.base.Predicate<Node> traverseChildrenPred) A post-order traversal, calling Visitor.visit for each node in the tree. Children of nodes that do not match the predicate will not be visited. -
preOrderIterable
public static Iterable<Node> preOrderIterable(Node root, com.google.common.base.Predicate<Node> travserseNodePredicate) Create anIterable
over the given node and all descendents. Nodes are given in depth-first pre-order ( document source order).This has the benefit over the visitor patten that it is iterative and can be used with Java 8 Stream API for searching, filtering, transforms, and other functional processing.
The given predicate determines whether a node's children will be iterated over. If a node does not match the predicate, none of its children will be visited.
- Parameters:
root
- Root of the tree.travserseNodePredicate
- Matches nodes in the tree whose children should be traversed.- See Also:
-
preOrderIterable
Same aspreOrderIterable(Node, Predicate)
but iterates over all nodes in the tree without exception. -
getFunctionParameters
- Parameters:
fnNode
- The function.- Returns:
- The Node containing the Function parameters.
-
getSourceName
- Parameters:
n
- The node.- Returns:
- The source name property on the node or its ancestors.
-
getSourceFile
- Parameters:
n
- The node.- Returns:
- The source name property on the node or its ancestors.
-
getInputId
- Parameters:
n
- The node.- Returns:
- The InputId property on the node or its ancestors.
-
getDeclaredTypeExpression
Return declared JSDoc type for the given name declaration, or null if none present. -
getBestJSDocInfo
Find the best JSDoc for the given node. -
getBestJsDocInfoNodeStrict
Find the best JSDocInfo node for the given node. This version is stricter thangetBestJSDocInfoNode
in that it only accepts a node that is either a lhs "let, const, var" name node, or a RHS class/function, or a class/function declaration, or an export.- Throws:
IllegalStateException
- if any other input node token is provided.
-
getBestJSDocInfoNode
Deprecated.because we want to control the input node tokens accepted by this function. UsegetBestJSDocInfoNodeStrict
instead.Find the best JSDocInfo node for the given node. -
getBestLValue
Find the l-value that the given r-value is being assigned to. -
getRValueOfLValue
Gets the r-value (or initializer) of a node returned by getBestLValue. -
getBestLValueName
Get the name of the given l-value node. -
isExpressionResultUsed
- Returns:
- true iff the result of the expression is consumed.
-
countAstSize
-
isGoogProvideCall
-
isGoogModuleCall
-
isTopLevel
-
isEs6ConstructorMemberFunctionDef
-
isEs6Constructor
-
isCallTo
-
isCallTo
-
isCallTo
A faster version ofisCallTo(Node, String)
.- Parameters:
n
- node to check if a calltargetMethod
- the prebuilt AST getprop node that represents the method to check
-
collectExternVariableNames
public static com.google.common.collect.ImmutableSet<String> collectExternVariableNames(AbstractCompiler compiler, Node externs) -
markFunctionsDeleted
Recurses through a tree, marking all function nodes deleted. -
getParentChangeScopeNodes
Returns the list of scope nodes which are parents of the provided list of scope nodes. -
removeNestedChangeScopeNodes
Removes any scope nodes from the provided list that are nested within some other scope node also in the list. Returns the modified list. -
isObjLitProperty
Returns true if the node is a property of an object literal. -
isBlocklessArrowFunctionResult
- Returns:
- Whether the node represents the return value of a blockless Arrow function
-
getParamOrPatternNames
Callscb
with all NAMEs declared in a PARAM_LIST or destructuring pattern. -
getGoogRequireInfo
-
getGoogRequireInfo
-
getGoogRequireInfo
-
estimateNumLines
Estimates the number of lines in the file of this script node.This method returns the line number of the last node in the script +1. This is not strictly the number of lines in the file (consider trailing comments or whitespace), but should be strongly correlated with it. If perfect accuracy is desired the original source file will have to be read.
-