目录
正在加载目录…
正在阅读专栏 The Super Tiny Compiler 专栏 第 6 篇 · 共 7 篇 · 86%

Code Generator:从 AST 输出 JavaScript

发布于 2026-09-16 20:31 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 630 · 预计阅读 2 分钟 👁 10 次阅读

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) {

参考资料

← 返回列表
← 上一篇 Transformer:旧 AST 到新 AST 下一篇 → Compiler:串起完整 pipeline

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论