Basics·续1
As we traverse down each branch of the tree we eventually hit dead ends where we need to traverse back up the tree to get to the next node. Going down the tree we enter each node, then going back up we exit each node.
Let’s walk through what this process looks like for the above tree.
-
Enter FunctionDeclaration
-
Enter Identifier (id)
-
Hit dead end
-
Exit Identifier (id)
-
Enter Identifier (params[0])
-
Hit dead end
-
Exit Identifier (params[0])
-
Enter BlockStatement (body)
-
Enter ReturnStatement (body)
-
Enter BinaryExpression (argument)
-
Enter Identifier (left)
-
Hit dead end
-
Exit Identifier (left)
-
Enter Identifier (right)
-
Hit dead end
-
Exit Identifier (right)
-
Exit BinaryExpression (argument)
-
Exit ReturnStatement (body)
-
Exit BlockStatement (body)
-
Exit FunctionDeclaration
So when creating a visitor you have two opportunities to visit a node.
const MyVisitor = { Identifier: { enter() { console.log("Entered!"); }, exit() { console.log("Exited!"); } }};
If necessary, you can also apply the same function for multiple visitor nodes by separating them with a | in the method name as a string like Identifier|MemberExpression.
Example usage in the flow-comments plugin
const MyVisitor = { "ExportNamedDeclaration|Flow"(path) {}};
You can also use aliases as visitor nodes (as defined in babel-types).
For example,
Function is an alias for FunctionDeclaration, FunctionExpression, ArrowFunctionExpression, ObjectMethod and ClassMethod.
const MyVisitor = { Function(path) {}};
Paths" class="reference-link">Paths
An AST generally has many Nodes, but how do Nodes relate to one another? We could have one giant mutable object that you manipulate and have full access to, or we can simplify this with Paths.
A Path is an object representation of the link between two nodes.
For example if we take the following node and its child:
{ type: "FunctionDeclaration", id: { type: "Identifier", name: "square" }, ...}
And represent the child Identifier as a path, it looks something like this:
{ "parent": { "type": "FunctionDeclaration", "id": {...}, .... }, "node": { "type": "Identifier", "name": "square" }}
It also has additional metadata about the path:
{ "parent": {...}, "node": {...}, "hub": {...}, "contexts": [], "data": {}, "shouldSkip": false, "shouldStop": false, "removed": false, "state": null, "opts": null, "skipKeys": null, "parentPath": null, "context": null, "container": null, "listKey": null, "inList": false, "parentKey": null, "key": null, "scope": null, "type": null, "typeAnnotation": null}
As well as tons and tons of methods related to adding, updating, moving, and removing nodes, but we’ll get into those later.
In a sense, paths are a reactive representation of a node’s position in the tree and all sorts of information about the node. Whenever you call a method that modifies the tree, this information is updated. Babel manages all of this for you to make working with nodes easy and as stateless as possible.
Paths in Visitors" class="reference-link">Paths in Visitors
When you have a visitor that has a Identifier() method, you’re actually visiting the path instead of the node. This way you are mostly working with the reactive representation of a node instead of the node itself.
const MyVisitor = { Identifier(path) { console.log("Visiting: " + path.node.name); }};
a + b + c;
path.traverse(MyVisitor);Visiting: aVisiting: bVisiting: c
State" class="reference-link">State
State is the enemy of AST transformation. State will bite you over and over again and your assumptions about state will almost always be proven wrong by some syntax that you didn’t consider.
Take the following code:
function square(n) { return n * n;}
Let’s write a quick hacky visitor that will rename n to x.
let paramName;const MyVisitor = { FunctionDeclaration(path) { const param = path.node.params[0]; paramName = param.name; param.name = "x"; }, Identifier(path) { if (path.node.name === paramName) { path.node.name = "x"; } }};
This might work for the above code, but we can easily break that by doing this:
function square(n) { return n * n;}n;
The better way to deal with this is recursion. So let’s make like a Christopher Nolan film and put a visitor inside of a visitor.
const updateParamNameVisitor = { Identifier(path) { if (path.node.name === this.paramName) { path.node.name = "x"; } }};const MyVisitor = { FunctionDeclaration(path) { const param = path.node.params[0]; const paramName = param.name; param.name = "x"; path.traverse(updateParamNameVisitor, { paramName }); }};path.traverse(MyVisitor);
Of course, this is a contrived example but it demonstrates how to eliminate global state from your visitors.
Scopes" class="reference-link">Scopes
Next let’s introduce the concept of a scope). JavaScript has lexical scoping#Lexical_scoping_vs._dynamic_scoping), which is a tree structure where blocks create new scope.
// global scopefunction scopeOne() { // scope 1 function scopeTwo() { // scope 2 }}
Whenever you create a reference in JavaScript, whether that be by a variable, function, class, param, import, label, etc., it belongs to the current scope.
var global = "I am in the global scope";function scopeOne() { var one = "I am in the scope created by `scopeOne()`"; function scopeTwo() { var two = "I am in the scope created by `scopeTwo()`"; }}
Code within a deeper scope may use a reference from a higher scope.
function scopeOne() { var one = "I am in the scope created by `scopeOne()`"; function scopeTwo() { one = "I am updating the reference in `scopeOne` inside `scopeTwo`"; }}
A lower scope might also create a reference of the same name without modifying it.
function scopeOne() { var one = "I am in the scope created by `scopeOne()`"; function scopeTwo() { var one = "I am creating a new `one` but leaving reference in `scopeOne()` alone."; }}
When writing a transform, we want to be wary of scope. We need to make sure we don’t break existing code while modifying different parts of it.
We may want to add new references and make sure they don’t collide with existing ones. Or maybe we just want to find where a variable is referenced. We want to be able to track these references within a given scope.
A scope can be represented as:
{ path: path, block: path.node, parentBlock: path.parent, parent: parentScope, bindings: [...]}
When you create a new scope you do so by giving it a path and a parent scope. Then during the traversal process it collects all the references (“bindings”) within that scope.
Once that’s done, there’s all sorts of methods you can use on scopes. We’ll get into those later though.
Bindings" class="reference-link">Bindings
References all belong to a particular scope; this relationship is known as a binding.
function scopeOnce() { var ref = "This is a binding"; ref; // This is a reference to a binding function scopeTwo() { ref; // This is a reference to a binding from a lower scope }}
A single binding looks like this:
{ identifier: node, scope: scope, path: path, kind: 'var', referenced: true, references: 3, referencePaths: [path, path, path], constant: false, constantViolations: [path]}
With this information you can find all the references to a binding, see what type of binding it is (parameter, declaration, etc.), lookup what scope it belongs to, or get a copy of its identifier. You can even tell if it’s constant and if not, see what paths are causing it to be non-constant.
Being able to tell if a binding is constant is useful for many purposes, the largest of which is minification.
