This module provides an efficient, modular, Esprima-compatible implementation of the abstract syntax tree type hierarchy pioneered by the Mozilla Parser API.
Installation
From NPM:
npm install ast-types
From GitHub:
cd path/to/node_modules
git clone git://github.com/benjamn/ast-types.git
cd ast-types
npm install .
Basic Usage
;; var fooId = b;var ifFoo = b; assert;assert;assert; assert;assert; assert;assert;assert;assert;
AST Traversal
Because it understands the AST type system so thoroughly, this library is able to provide excellent node iteration and traversal mechanisms.
If you want complete control over the traversal, and all you need is a way
of enumerating the known fields of your AST nodes and getting their
values, you may be interested in the primitives getFieldNames
and
getFieldValue
:
; const partialFunExpr = type: "FunctionExpression" ; // Even though partialFunExpr doesn't actually contain all the fields that// are expected for a FunctionExpression, types.getFieldNames knows:console;// [ 'type', 'id', 'params', 'body', 'generator', 'expression',// 'defaults', 'rest', 'async' ] // For fields that have default values, types.getFieldValue will return// the default if the field is not actually defined.console;// false
Two more low-level helper functions, eachField
and someField
, are
defined in terms of getFieldNames
and getFieldValue
:
// Iterate over all defined fields of an object, including those missing// or undefined, passing each field name and effective value (as returned// by getFieldValue) to the callback. If the object has no corresponding// Def, the callback will never be called. { ;} // Similar to eachField, except that iteration stops as soon as the// callback returns a truthy value. Like Array.prototype.some, the final// result is either true or false to indicates whether the callback// returned true for any element or not. { return ;}
So here's how you might make a copy of an AST node:
;const copy = {};
But that's not all! You can also easily visit entire syntax trees using
the powerful types.visit
abstraction.
Here's a trivial example of how you might assert that arguments.callee
is never used in ast
:
;; ;
Here's a slightly more involved example of transforming ...rest
parameters into browser-runnable ES5 JavaScript:
; // Reuse the same AST structure for Array.prototype.slice.call.var sliceExpr = b; ;
Here's how you might use types.visit
to implement a function that
determines if a given function node refers to this
:
{ nFunction; var result = false; ; return result;}
As you might guess, when an AbortRequest
is thrown from a subtree, the
exception will propagate from the corresponding calls to this.traverse
in the ancestor visitor methods. If you decide you want to cancel the
request, simply catch the exception and call its .cancel()
method. The
rest of the subtree beneath the try
-catch
block will be abandoned, but
the remaining siblings of the ancestor node will still be visited.
NodePath
The NodePath
object passed to visitor methods is a wrapper around an AST
node, and it serves to provide access to the chain of ancestor objects
(all the way back to the root of the AST) and scope information.
In general, path.node
refers to the wrapped node, path.parent.node
refers to the nearest Node
ancestor, path.parent.parent.node
to the
grandparent, and so on.
Note that path.node
may not be a direct property value of
path.parent.node
; for instance, it might be the case that path.node
is
an element of an array that is a direct child of the parent node:
pathnode === pathparentnodeelements3
in which case you should know that path.parentPath
provides
finer-grained access to the complete path of objects (not just the Node
ones) from the root of the AST:
// In reality, path.parent is the grandparent of path:pathparentPathparentPath === pathparent // The path.parentPath object wraps the elements array (note that we use// .value because the elements array is not a Node):pathparentPathvalue === pathparentnodeelements // The path.node object is the fourth element in that array:pathparentPathvalue3 === pathnode // Unlike path.node and path.value, which are synonyms because path.node// is a Node object, path.parentPath.node is distinct from// path.parentPath.value, because the elements array is not a// Node. Instead, path.parentPath.node refers to the closest ancestor// Node, which happens to be the same as path.parent.node:pathparentPathnode === pathparentnode // The path is named for its index in the elements array:pathname === 3 // Likewise, path.parentPath is named for the property by which// path.parent.node refers to it:pathparentPathname === "elements" // Putting it all together, we can follow the chain of object references// from path.parent.node all the way to path.node by accessing each// property by name:pathparentnodepathparentPathnamepathname === pathnode
These NodePath
objects are created during the traversal without
modifying the AST nodes themselves, so it's not a problem if the same node
appears more than once in the AST (like Array.prototype.slice.call
in
the example above), because it will be visited with a distict NodePath
each time it appears.
Child NodePath
objects are created lazily, by calling the .get
method
of a parent NodePath
object:
// If a NodePath object for the elements array has never been created// before, it will be created here and cached in the future:pathvalue === pathvalueelements3 // Alternatively, you can pass multiple property names to .get instead of// chaining multiple .get calls:pathvalue === pathvalueelements0
NodePath
objects support a number of useful methods:
// Replace one node with another node:var fifth = path;fifth; // Now do some stuff that might rearrange the list, and this replacement// remains safe:fifth; // Replace the third element in an array with two new nodes:path; // Remove a node and its parent if it would leave a redundant AST node://e.g. var t = 1, y =2; removing the `t` and `y` declarators results in `var undefined`.path; //returns the closest parent `NodePath`. // Remove a node from a list of nodes:path; // Add three new nodes to the beginning of a list of nodes:path; // Remove and return the first node in a list of nodes:path; // Push two new nodes onto the end of a list of nodes:path; // Remove and return the last node in a list of nodes:path; // Insert a new node before/after the seventh node in a list of nodes:var seventh = path;seventh;seventh; // Insert a new element at index 5 in a list of nodes:path;
Scope
The object exposed as path.scope
during AST traversals provides
information about variable and function declarations in the scope that
contains path.node
. See scope.ts for its public
interface, which currently includes .isGlobal
, .getGlobalScope()
,
.depth
, .declares(name)
, .lookup(name)
, and .getBindings()
.
Custom AST Node Types
The ast-types
module was designed to be extended. To that end, it
provides a readable, declarative syntax for specifying new AST node types,
based primarily upon the require("ast-types").Type.def
function:
; const def = Type;const string = builtInTypes; // Suppose you need a named File type to wrap your Programs. ; // Prevent further modifications to the File type (and any other// types newly introduced by def(...)).; // The b.file builder function is now available. It expects two// arguments, as named by .build("name", "program") above.const main = b; assert;assert;// etc. // If you pass the wrong type of arguments, or fail to pass enough// arguments, an AssertionError will be thrown. b;// ==> AssertionError: {"body":[],"type":"BlockStatement","loc":null} does not match type string b;// ==> AssertionError: {"type":"ThisExpression","loc":null} does not match type Program
The def
syntax is used to define all the default AST node types found in
babel-core.ts,
babel.ts,
core.ts,
es-proposals.ts,
es6.ts,
es7.ts,
es2020.ts,
esprima.ts,
flow.ts,
jsx.ts,
type-annotations.ts,
and
typescripts.ts,
so you have
no shortage of examples to learn from.