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

Transformer:旧 AST 到新 AST

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

The Super Tiny Compiler:把旧 AST 改写为新 AST

transformer 借助 traverser,将 Lisp 风格的 AST 转为更接近 JavaScript 的 AST:CallExpression、Identifier、arguments 和 ExpressionStatement。

TL;DR

  • 本篇对应 compiler pipeline 的 Transformer 阶段。
  • 源码中的 code、comments、AST node names 和错误文本全部保留原样。
  • 重点关注本阶段的输入、输出以及它如何与前后阶段衔接。

本篇目标

transformer 是这条 pipeline 中最能体现“编译就是转换”的阶段。它接收 Lisp AST,并通过 traverser 创建一棵新的 AST。原 AST 中的 CallExpression 使用 name 和 params;新 AST 将其改写为 JavaScript 风格的 callee、arguments,顶层 call 还会包装成 ExpressionStatement。

实现使用一个简单的 context reference:旧 AST node 的 _context 指向新 AST 中对应的 children array。这样 visitor 在遍历旧树时,就能把转换后的 nodes 放入正确位置。

源码

下面保留原项目 transformer 的完整实现。

javascript
function transformer(ast) {

  // We'll create a `newAst` which like our previous AST will have a program
  // node.
  let newAst = {
    type: 'Program',
    body: [],
  };

  // Next I'm going to cheat a little and create a bit of a hack. We're going to
  // use a property named `context` on our parent nodes that we're going to push
  // nodes to their parent's `context`. Normally you would have a better
  // abstraction than this, but for our purposes this keeps things simple.
  //
  // Just take note that the context is a reference *from* the old ast *to* the
  // new ast.
  ast._context = newAst.body;

  // We'll start by calling the traverser function with our ast and a visitor.
  traverser(ast, {

    // The first visitor method accepts any `NumberLiteral`
    NumberLiteral: {
      // We'll visit them on enter.
      enter(node, parent) {
        // We'll create a new node also named `NumberLiteral` that we will push to
        // the parent context.
        parent._context.push({
          type: 'NumberLiteral',
          value: node.value,
        });
      },
    },

    // Next we have `StringLiteral`
    StringLiteral: {
      enter(node, parent) {
        parent._context.push({
          type: 'StringLiteral',
          value: node.value,
        });
      },
    },

    // Next up, `CallExpression`.
    CallExpression: {
      enter(node, parent) {

        // We start creating a new node `CallExpression` with a nested
        // `Identifier`.
        let expression = {
          type: 'CallExpression',
          callee: {
            type: 'Identifier',
            name: node.name,
          },
          arguments: [],
        };

        // Next we're going to define a new context on the original
        // `CallExpression` node that will reference the `expression`'s arguments
        // so that we can push arguments.
        node._context = expression.arguments;

        // Then we're going to check if the parent node is a `CallExpression`.
        // If it is not...
        if (parent.type !== 'CallExpression') {

          // We're going to wrap our `CallExpression` node with an
          // `ExpressionStatement`. We do this because the top level
          // `CallExpression` in JavaScript are actually statements.
          expression = {
            type: 'ExpressionStatement',
            expression: expression,
          };
        }

        // Last, we push our (possibly wrapped) `CallExpression` to the `parent`'s
        // `context`.
        parent._context.push(expression);
      },
    }
  });

  // At the end of our transformer function we'll return the new ast that we
  // just created.
  return newAst;
}

/**
 * ============================================================================
 *                               ヾ(〃^∇^)ノ♪
 *                            THE CODE GENERATOR!!!!
 * ============================================================================
 */

/**
 * Now let's move onto our last phase: The Code Generator.
 *
 * Our code generator is going to recursively call itself to print each node in
 * the tree into one giant string.
 */

function codeGenerator(node) {

参考资料

← 返回列表
← 上一篇 Traverser:递归访问 AST 下一篇 → Code Generator:从 AST 输出 JavaScript

评论 (0)

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