Basics
Basics" class="reference-link">Basics
Babel is a JavaScript compiler, specifically a source-to-source compiler, often called a “transpiler”. This means that you give Babel some JavaScript code, Babel modifies the code, and generates the new code back out.
ASTs" class="reference-link">ASTs
Each of these steps involve creating or working with an Abstract Syntax Tree or AST.
Babel uses an AST modified from ESTree, with the core spec located here.
function square(n) { return n * n;}
Check out AST Explorer to get a better sense of the AST nodes. Here is a link to it with the example code above pasted in.
This same program can be represented as a tree like this:
- FunctionDeclaration: - id: - Identifier: - name: square - params [1] - Identifier - name: n - body: - BlockStatement - body [1] - ReturnStatement - argument - BinaryExpression - operator: * - left - Identifier - name: n - right - Identifier - name: n
Or as a JavaScript Object like this:
{ type: "FunctionDeclaration", id: { type: "Identifier", name: "square" }, params: [{ type: "Identifier", name: "n" }], body: { type: "BlockStatement", body: [{ type: "ReturnStatement", argument: { type: "BinaryExpression", operator: "*", left: { type: "Identifier", name: "n" }, right: { type: "Identifier", name: "n" } } }] }}
You’ll notice that each level of the AST has a similar structure:
{ type: "FunctionDeclaration", id: {...}, params: [...], body: {...}}
{ type: "Identifier", name: ...}
{ type: "BinaryExpression", operator: ..., left: {...}, right: {...}}
Note: Some properties have been removed for simplicity.
Each of these are known as a Node. An AST can be made up of a single Node, or hundreds if not thousands of Nodes. Together they are able to describe the syntax of a program that can be used for static analysis.
Every Node has this interface:
interface Node { type: string;}
The type field is a string representing the type of Node the object is (e.g. "FunctionDeclaration", "Identifier", or "BinaryExpression"). Each type of Node defines an additional set of properties that describe that particular node type.
There are additional properties on every Node that Babel generates which describe the position of the Node in the original source code.
{ type: ..., start: 0, end: 38, loc: { start: { line: 1, column: 0 }, end: { line: 3, column: 1 } }, ...}
These properties start, end, loc, appear in every single Node.
Stages of Babel" class="reference-link">Stages of Babel
The three primary stages of Babel are parse, transform, generate.
Parse" class="reference-link">Parse
The parse stage, takes code and outputs an AST. There are two phases of parsing in Babel: Lexical Analysis and Syntactic Analysis.
Lexical Analysis" class="reference-link">Lexical Analysis
Lexical Analysis will take a string of code and turn it into a stream of tokens.
You can think of tokens as a flat array of language syntax pieces.
n * n;
[ { type: { ... }, value: "n", start: 0, end: 1, loc: { ... } }, { type: { ... }, value: "*", start: 2, end: 3, loc: { ... } }, { type: { ... }, value: "n", start: 4, end: 5, loc: { ... } }, ...]
Each of the types here have a set of properties describing the token:
{ type: { label: 'name', keyword: undefined, beforeExpr: false, startsExpr: true, rightAssociative: false, isLoop: false, isAssign: false, prefix: false, postfix: false, binop: null, updateContext: null }, ...}
Like AST nodes they also have a start, end, and loc.
Syntactic Analysis" class="reference-link">Syntactic Analysis
Syntactic Analysis will take a stream of tokens and turn it into an AST representation. Using the information in the tokens, this phase will reformat them as an AST which represents the structure of the code in a way that makes it easier to work with.
Transform" class="reference-link">Transform
The transform stage takes an AST and traverses through it, adding, updating, and removing nodes as it goes along. This is by far the most complex part of Babel or any compiler. This is where plugins operate and so it will be the subject of most of this handbook. So we won’t dive too deep right now.
Generate" class="reference-link">Generate
The code generation) stage takes the final AST and turns it back into a string of code, also creating source maps.
Code generation is pretty simple: you traverse through the AST depth-first, building a string that represents the transformed code.
Traversal" class="reference-link">Traversal
When you want to transform an AST you have to traverse the tree recursively.
Say we have the type FunctionDeclaration. It has a few properties: id, params, and body. Each of them have nested nodes.
{ type: "FunctionDeclaration", id: { type: "Identifier", name: "square" }, params: [{ type: "Identifier", name: "n" }], body: { type: "BlockStatement", body: [{ type: "ReturnStatement", argument: { type: "BinaryExpression", operator: "*", left: { type: "Identifier", name: "n" }, right: { type: "Identifier", name: "n" } } }] }}
So we start at the FunctionDeclaration and we know its internal properties so we visit each of them and their children in order.
Next we go to id which is an Identifier. Identifiers don’t have any child node properties so we move on.
After that is params which is an array of nodes so we visit each of them. In this case it’s a single node which is also an Identifier so we move on.
Then we hit body which is a BlockStatement with a property body that is an array of Nodes so we go to each of them.
The only item here is a ReturnStatement node which has an argument, we go to the argument and find a BinaryExpression.
The BinaryExpression has an operator, a left, and a right. The operator isn’t a node, just a value, so we don’t go to it, and instead just visit left and right.
This traversal process happens throughout the Babel transform stage.
Visitors" class="reference-link">Visitors
When we talk about “going” to a node, we actually mean we are visiting them. The reason we use that term is because there is this concept of a visitor.
Visitors are a pattern used in AST traversal across languages. Simply put they are an object with methods defined for accepting particular node types in a tree. That’s a bit abstract so let’s look at an example.
const MyVisitor = { Identifier() { console.log("Called!"); }};// You can also create a visitor and add methods on it laterlet visitor = {};visitor.MemberExpression = function() {};visitor.FunctionDeclaration = function() {}
Note: Identifier() { ... } is shorthand for Identifier: { enter() { ... } }.
This is a basic visitor that when used during a traversal will call the Identifier() method for every Identifier in the tree.
So with this code the Identifier() method will be called four times with each Identifier (including square).
function square(n) { return n * n;}
path.traverse(MyVisitor);Called!Called!Called!Called!
These calls are all on node enter. However there is also the possibility of calling a visitor method when on exit.
Imagine we have this tree structure:
- FunctionDeclaration - Identifier (id) - Identifier (params[0]) - BlockStatement (body) - ReturnStatement (body) - BinaryExpression (argument) - Identifier (left) - Identifier (right)
