Code Generator:从 AST 输出 JavaScript
The Super Tiny Compiler:从 AST 输出 JavaScript
codeGenerator 递归遍历 transformed AST,把各 node 打印成一段 JavaScript source string。
TL;DR
- 本篇对应 compiler pipeline 的
Code Generator阶段。 - 源码中的 code、comments、AST node names 和错误文本全部保留原样。
- 重点关注本阶段的输入、输出以及它如何与前后阶段衔接。
本篇目标
现在已经有了面向 JavaScript 的 AST,最后一个独立阶段是 code generation。codeGenerator 根据 node 的 type 选择输出规则,并递归生成 children 的 source。
Program 用 newline 连接 statements;CallExpression 输出 callee、括号和逗号分隔的 arguments;ExpressionStatement 添加 semicolon;literal 和 identifier 则直接输出自身表示。
源码
下面保留原项目 code generator 的完整实现。
javascript
// We'll break things down by the `type` of the `node`.
switch (node.type) {
// If we have a `Program` node. We will map through each node in the `body`
// and run them through the code generator and join them with a newline.
case 'Program':
return node.body.map(codeGenerator)
.join('\n');
// For `ExpressionStatement` we'll call the code generator on the nested
// expression and we'll add a semicolon...
case 'ExpressionStatement':
return (
codeGenerator(node.expression) +
';' // << (...because we like to code the *correct* way)
);
// For `CallExpression` we will print the `callee`, add an open
// parenthesis, we'll map through each node in the `arguments` array and run
// them through the code generator, joining them with a comma, and then
// we'll add a closing parenthesis.
case 'CallExpression':
return (
codeGenerator(node.callee) +
'(' +
node.arguments.map(codeGenerator)
.join(', ') +
')'
);
// For `Identifier` we'll just return the `node`'s name.
case 'Identifier':
return node.name;
// For `NumberLiteral` we'll just return the `node`'s value.
case 'NumberLiteral':
return node.value;
// For `StringLiteral` we'll add quotations around the `node`'s value.
case 'StringLiteral':
return '"' + node.value + '"';
// And if we haven't recognized the node, we'll throw an error.
default:
throw new TypeError(node.type);
}
}
/**
* ============================================================================
* (۶* ‘ヮ’)۶”
* !!!!!!!!THE COMPILER!!!!!!!!
* ============================================================================
*/
/**
* FINALLY! We'll create our `compiler` function. Here we will link together
* every part of the pipeline.
*
* 1. input => tokenizer => tokens
* 2. tokens => parser => ast
* 3. ast => transformer => newAst
* 4. newAst => generator => output
*/
function compiler(input) {
参考资料
评论 (0)