public final class NodeUtil
extends java.lang.Object
Modifier and Type | Class and Description |
---|---|
static class |
NodeUtil.GoogRequire
Represents a goog.require'd namespace and property inside a module.
|
static class |
NodeUtil.ValueType |
static interface |
NodeUtil.Visitor
Interface for use with the visit method.
|
Modifier and Type | Method and Description |
---|---|
static 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 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 |
emptyFunction() |
static java.util.List<Node> |
findLhsNodesInNode(Node assigningParent)
Retrieves lhs nodes declared or assigned in a given assigning parent node.
|
static 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 Node |
getAssignedValue(Node n)
For an assignment or variable declaration get the assigned value.
|
static JSDocInfo |
getBestJSDocInfo(Node n)
Find the best JSDoc for the given node.
|
static Node |
getBestJSDocInfoNode(Node n) |
static Node |
getBestLValue(Node n)
Find the l-value that the given r-value is being assigned to.
|
static java.lang.String |
getBestLValueName(Node lValue)
Get the name of the given l-value node.
|
static Node |
getClassMembers(Node n) |
static int |
getCount(Node n,
com.google.common.base.Predicate<Node> pred,
com.google.common.base.Predicate<Node> traverseChildrenPred) |
static 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 |
getEnclosingBlock(Node n)
Finds the block containing the given node.
|
static Node |
getEnclosingBlockScopeRoot(Node n) |
static Node |
getEnclosingClass(Node n)
Finds the class containing the given node.
|
static Node |
getEnclosingFunction(Node n)
Finds the function containing the given node.
|
static Node |
getEnclosingModuleIfPresent(Node n) |
static Node |
getEnclosingNode(Node n,
com.google.common.base.Predicate<Node> pred) |
static Node |
getEnclosingScopeRoot(Node n) |
static Node |
getEnclosingScript(Node n)
Finds the script containing the given node.
|
static Node |
getEnclosingStatement(Node n) |
static Node |
getEnclosingType(Node n,
Token type)
Gets the closest ancestor to the given node of the provided type.
|
static Node |
getEs6ClassConstructorMemberFunctionDef(Node classNode) |
static Node |
getFunctionBody(Node fn)
Return a BLOCK node for the given FUNCTION node.
|
static Node |
getFunctionParameters(Node fnNode) |
static NodeUtil.GoogRequire |
getGoogRequireInfo(java.lang.String name,
Scope scope) |
static InputId |
getInputId(Node n) |
static NodeUtil.ValueType |
getKnownValueType(Node n)
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 java.lang.String |
getName(Node n) |
static Node |
getNameNode(Node n)
Gets the node of a function or class's name.
|
static java.lang.String |
getNearestFunctionName(Node n)
Gets the function's name.
|
static void |
getParamOrPatternNames(Node n,
java.util.function.Consumer<Node> cb)
Calls
cb with all NAMEs declared in a PARAM_LIST or destructuring pattern. |
static java.util.List<Node> |
getParentChangeScopeNodes(java.util.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 Node |
getRValueOfLValue(Node n)
Gets the r-value (or initializer) of a node returned by getBestLValue.
|
static StaticSourceFile |
getSourceFile(Node n) |
static java.lang.String |
getSourceName(Node n) |
static java.lang.String |
getStringValue(Node n)
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 |
isAnyFor(Node n) |
static boolean |
isAssignmentOp(Node n) |
static boolean |
isBigIntResult(Node n)
Returns true if the result of node evaluation is always a bigint
|
static boolean |
isBlocklessArrowFunctionResult(Node n) |
static boolean |
isBooleanResult(Node n) |
static boolean |
isCallOrNew(Node node) |
static boolean |
isCallTo(Node n,
Node targetMethod)
A faster version of
isCallTo(Node, String) . |
static boolean |
isCallTo(Node n,
java.lang.String qualifiedName) |
static boolean |
isClassDeclaration(Node n)
|
static boolean |
isCompoundAssignmentOp(Node n) |
static boolean |
isControlStructure(Node n)
Determines whether the given node is a FOR, DO, WHILE, WITH, or IF node.
|
static boolean |
isDeclarationLValue(Node n)
Determines whether this node is used as an L-value that is a declaration.
|
static boolean |
isEnhancedFor(Node n) |
static boolean |
isEs6Constructor(Node fnNode) |
static boolean |
isEs6ConstructorMemberFunctionDef(Node memberFunctionDef) |
static boolean |
isExprCall(Node n)
Is this node a call expression statement?
|
static boolean |
isFromTypeSummary(Node n)
Determine if the given SCRIPT is a @typeSummary file, like an i.js file
|
static boolean |
isFunctionDeclaration(Node n)
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 |
isHoistedFunctionDeclaration(Node n)
Is this node a hoisted function declaration? A function declaration in the
scope root is hoisted to the top of the scope.
|
static boolean |
isImportedName(Node n) |
static boolean |
isInFunction(Node n) |
static boolean |
isLhsByDestructuring(Node n)
Returns true if the node is a lhs value of a destructuring assignment.
|
static boolean |
isLhsOfAssign(Node n) |
static boolean |
isLiteralValue(Node n,
boolean includeFunctions)
Returns true if this is a literal value.
|
static boolean |
isLValue(Node n)
Determines whether this node is used as an L-value.
|
static boolean |
isMethodDeclaration(Node n)
Is this node a class or object literal member function?
|
static boolean |
isNameDeclaration(Node n)
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 |
isNamespaceDecl(Node n)
Returns true iff this node defines a namespace, e.g.,
/** @const * / var goog = {};
/** @const * / var goog = goog || {};
/** @const * / goog.math = goog.math || {};
|
static boolean |
isNormalGet(Node n)
Is this a GETPROP or GETELEM node?
|
static boolean |
isNormalOrOptChainCall(Node n)
Is this a CALL or OPTCHAIN_CALL?
|
static boolean |
isNormalOrOptChainGet(Node n)
Is this a GETPROP, OPTCHAIN_GETPROP, GETELEM, or OPTCHAIN_GETELEM?
|
static boolean |
isNormalOrOptChainGetProp(Node n)
Is this a GETPROP or OPTCHAIN_GETPROP?
|
static boolean |
isNullOrUndefined(Node n) |
static boolean |
isNumericResult(Node n)
Returns true if the result of node evaluation is always a number
|
static boolean |
isObjectDefinePropertiesDefinition(Node n)
Returns
true if the node is a definition with Object.defineProperties |
static boolean |
isObjectResult(Node n) |
static boolean |
isObjLitProperty(Node node)
Returns true if the node is a property of an object literal.
|
static boolean |
isOptChainGet(Node n)
Is this an OPTCHAIN_GETPROP or OPTCHAIN_GETELEM node?
|
static boolean |
isOptChainNode(Node n)
Is this a OPTCHAIN_GETPROP, OPTCHAIN_GETELEM, OPTCHAIN_CALL node?
|
static boolean |
isPrototypePropertyDeclaration(Node n) |
static boolean |
isStatement(Node n) |
static boolean |
isStatementBlock(Node n) |
static boolean |
isStatementParent(Node parent) |
static boolean |
isStringResult(Node n) |
static boolean |
isTopLevel(Node n) |
static boolean |
isUndefined(Node n) |
static boolean |
isValidQualifiedName(CompilerOptions.LanguageMode mode,
java.lang.String name)
Deprecated.
|
static boolean |
isValidQualifiedName(FeatureSet mode,
java.lang.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,
Node rhs,
Token declarationType) |
static Node |
newPropertyAccess(AbstractCompiler compiler,
Node context,
java.lang.String name)
Creates a property access on the
context tree. |
static Node |
newQName(AbstractCompiler compiler,
java.lang.String name)
Creates a node representing a qualified name.
|
static Node |
newQNameDeclaration(AbstractCompiler compiler,
java.lang.String name,
Node value,
JSDocInfo info)
Creates a node representing a qualified name.
|
static Node |
newQNameDeclaration(AbstractCompiler compiler,
java.lang.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 java.lang.String |
opToStr(Token operator)
Converts an operator's token value (see
Token ) 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. |
static java.lang.Iterable<Node> |
preOrderIterable(Node root)
Same as
preOrderIterable(Node, Predicate) but iterates over all nodes in the tree
without exception. |
static java.lang.Iterable<Node> |
preOrderIterable(Node root,
com.google.common.base.Predicate<Node> travserseNodePredicate)
Create an
Iterable 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 name
|
static java.util.List<Node> |
removeNestedChangeScopeNodes(java.util.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 alwaysMerge)
Merge a block with its parent block.
|
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.
|
public static java.lang.String getStringValue(Node n)
String()
JavaScript cast
function.
IMPORTANT: This method does not consider whether n
may have side effects.
public static java.lang.String getName(Node n)
n
- A function or class node.public static Node getNameNode(Node n)
class name {...}
var name = class {...}
qualified.name = class {...}
var name2 = class name1 {...}
qualified.name2 = class name1 {...}
n
- A function or class nodepublic static void removeName(Node n)
public static java.lang.String getNearestFunctionName(Node n)
{'name': function() ...}
{name: function() ...}
function name() ...
var name = function() ...
var obj = {name() {} ...}
qualified.name = function() ...
var name2 = function name1() ...
qualified.name2 = function name1() ...
n
- a node whose type is Token.FUNCTION
null
if it has no name@Nullable public static Node getEs6ClassConstructorMemberFunctionDef(Node classNode)
public static boolean isLiteralValue(Node n, boolean includeFunctions)
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.
includeFunctions
- If true, all function expressions will be
treated as literals.public static boolean isNamespaceDecl(Node n)
public static boolean isFromTypeSummary(Node n)
public static int precedence(Token type)
=
, &=
, +=
, etc.) which have precedence of 1, and so on.
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedencepublic static boolean isUndefined(Node n)
public static boolean isNullOrUndefined(Node n)
public static NodeUtil.ValueType getKnownValueType(Node n)
public static boolean isNumericResult(Node n)
public static boolean isBigIntResult(Node n)
public static boolean isBooleanResult(Node n)
public static boolean isStringResult(Node n)
public static boolean isObjectResult(Node n)
public static boolean isAssignmentOp(Node n)
public static boolean isCompoundAssignmentOp(Node n)
public static Node getEnclosingType(Node n, Token type)
public static Node getEnclosingClass(Node n)
public static Node getEnclosingFunction(Node n)
public static Node getEnclosingScript(Node n)
public static Node getEnclosingBlock(Node n)
public static boolean isInFunction(Node n)
public static Node getEnclosingNode(Node n, com.google.common.base.Predicate<Node> pred)
public static boolean isNormalOrOptChainGet(Node n)
public static boolean isNormalOrOptChainGetProp(Node n)
public static boolean isNormalOrOptChainCall(Node n)
public static boolean isNormalGet(Node n)
public static boolean isOptChainGet(Node n)
public static boolean isOptChainNode(Node n)
public static boolean isNameDeclaration(Node n)
n
- The noden
is VAR, LET or CONSTpublic static Node getAssignedValue(Node n)
public static boolean isExprCall(Node n)
n
- The noden
is EXPR_RESULT and n
's
first child is CALLpublic static boolean isEnhancedFor(Node n)
public static boolean isAnyFor(Node n)
public static boolean isControlStructure(Node n)
public static boolean isStatementBlock(Node n)
public static boolean isStatement(Node n)
public static boolean isStatementParent(Node parent)
public static void deleteNode(Node n, AbstractCompiler compiler)
public static void deleteFunctionCall(Node n, AbstractCompiler compiler)
undefined
.public static void deleteChildren(Node n, AbstractCompiler compiler)
public static void removeChild(Node parent, Node node)
public static void replaceDeclarationChild(Node declChild, Node newStatement)
declChild
- The name node to be replaced.newStatement
- The statement to replace with.public static boolean tryMergeBlock(Node block, boolean alwaysMerge)
public static boolean canMergeBlock(Node block)
public static boolean isCallOrNew(Node node)
node
- A nodepublic static Node getFunctionBody(Node fn)
public static boolean isFunctionDeclaration(Node n)
isFunctionExpression(com.google.javascript.rhino.Node)
).public static boolean isMethodDeclaration(Node n)
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]() {}
}
public static boolean isClassDeclaration(Node n)
public static boolean isHoistedFunctionDeclaration(Node n)
isFunctionDeclaration(com.google.javascript.rhino.Node)
).public static boolean isNameDeclOrSimpleAssignLhs(Node n, Node parent)
n
- The nodeparent
- Parent of the nodepublic static boolean isLValue(Node n)
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".
n
- The nodepublic static boolean isDeclarationLValue(Node n)
x = 5;
is an L-value but does not declare a variable.
public static boolean isLhsOfAssign(Node n)
public static boolean isImportedName(Node n)
public static Node getDeclaringParent(Node targetNode)
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
targetNode
- a NAME, OBJECT_PATTERN, or ARRAY_PATTERNjava.lang.IllegalStateException
- if targetNode is not actually used as a declaration targetpublic static Node getRootTarget(Node targetNode)
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
targetNode
- java.lang.IllegalStateException
- if targetNode is not actually used as a targetpublic static boolean isLhsByDestructuring(Node n)
For example, x in var [x] = [1];
, var [...x] = [1];
, and var {a: x} =
{a: 1}
or a.b in ([a.b] = [1]);
or ({key: a.b} = {key: 1});
public static java.lang.String opToStr(Token operator)
Token
) to a string
representation.operator
- the operator's token value to convertnull
if the token value is
not an operatorpublic static Node newDeclaration(Node lhs, @Nullable Node rhs, Token declarationType)
public static Node newQName(AbstractCompiler compiler, java.lang.String name)
name
- A qualified name (e.g. "foo" or "foo.bar.baz")public static Node newPropertyAccess(AbstractCompiler compiler, Node context, java.lang.String name)
context
tree.public static Node newQNameDeclaration(AbstractCompiler compiler, java.lang.String name, Node value, JSDocInfo info)
name
- A qualified name (e.g. "foo" or "foo.bar.baz")public static Node newQNameDeclaration(AbstractCompiler compiler, java.lang.String name, Node value, JSDocInfo info, Token type)
name
- A qualified name (e.g. "foo" or "foo.bar.baz")type
- Must be VAR, CONST, or LET. Ignored if name
is dotted.public static Node getRootOfQualifiedName(Node qName)
@Deprecated public static boolean isValidQualifiedName(CompilerOptions.LanguageMode mode, java.lang.String name)
public static boolean isValidQualifiedName(FeatureSet mode, java.lang.String name)
public static java.util.List<Node> findLhsNodesInNode(Node assigningParent)
An assigning parent node is one that assigns a value to one or more LHS nodes.
public static boolean isObjectDefinePropertiesDefinition(Node n)
true
if the node is a definition with Object.definePropertiespublic static boolean isPrototypePropertyDeclaration(Node n)
true
if the node an assignment to a prototype property of
some constructor.public static Node newUndefinedNode(Node srcReferenceNode)
public static Node emptyFunction()
public static boolean has(Node node, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred)
public static Node findPreorder(Node node, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred)
public static int getCount(Node n, com.google.common.base.Predicate<Node> pred, com.google.common.base.Predicate<Node> traverseChildrenPred)
public static void visitPreOrder(Node node, NodeUtil.Visitor visitor)
public static void visitPreOrder(Node node, NodeUtil.Visitor visitor, com.google.common.base.Predicate<Node> traverseChildrenPred)
public static void visitPostOrder(Node node, NodeUtil.Visitor visitor)
public static void visitPostOrder(Node node, NodeUtil.Visitor visitor, com.google.common.base.Predicate<Node> traverseChildrenPred)
public static java.lang.Iterable<Node> preOrderIterable(Node root, com.google.common.base.Predicate<Node> travserseNodePredicate)
Iterable
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.
root
- Root of the tree.travserseNodePredicate
- Matches nodes in the tree whose children should be traversed.Stream
,
Streams.stream(Iterable)
public static java.lang.Iterable<Node> preOrderIterable(Node root)
preOrderIterable(Node, Predicate)
but iterates over all nodes in the tree
without exception.public static Node getFunctionParameters(Node fnNode)
fnNode
- The function.public static java.lang.String getSourceName(Node n)
n
- The node.public static StaticSourceFile getSourceFile(Node n)
n
- The node.public static InputId getInputId(Node n)
n
- The node.@Nullable public static JSTypeExpression getDeclaredTypeExpression(Node declaration)
@Nullable public static JSDocInfo getBestJSDocInfo(Node n)
public static Node getBestLValue(Node n)
public static Node getRValueOfLValue(Node n)
public static java.lang.String getBestLValueName(@Nullable Node lValue)
public static boolean isTopLevel(Node n)
public static boolean isEs6ConstructorMemberFunctionDef(Node memberFunctionDef)
public static boolean isEs6Constructor(Node fnNode)
public static boolean isCallTo(Node n, java.lang.String qualifiedName)
public static boolean isCallTo(Node n, Node targetMethod)
isCallTo(Node, String)
.n
- node to check if a calltargetMethod
- the prebuilt AST getprop node that represents the method to checkpublic static void markFunctionsDeleted(Node node, AbstractCompiler compiler)
public static java.util.List<Node> getParentChangeScopeNodes(java.util.List<Node> scopeNodes)
public static java.util.List<Node> removeNestedChangeScopeNodes(java.util.List<Node> scopeNodes)
public static boolean isObjLitProperty(Node node)
public static boolean isBlocklessArrowFunctionResult(Node n)
public static void getParamOrPatternNames(Node n, java.util.function.Consumer<Node> cb)
cb
with all NAMEs declared in a PARAM_LIST or destructuring pattern.@Nullable public static NodeUtil.GoogRequire getGoogRequireInfo(java.lang.String name, Scope scope)
Copyright © 2009-2020 Google. All Rights Reserved.