Lesson 5 of 15

AST Node Types

Abstract Syntax Trees

Tokens are a flat list. To understand structure, we build a tree. For 3 + 4 * 2, the tree shows that 4 * 2 is grouped together:

    (+)
   /   \
  3    (*)
      /   \
     4     2

Each node in the tree is called an AST node. We represent them as plain objects:

// A number literal
{ type: "NumberLiteral", value: 42 }

// A binary operation (left op right)
{ type: "BinaryExpr", op: "+", left: ..., right: ... }

Node Types We Need

Node TypeFieldsExample
NumberLiteralvalue42
StringLiteralvalue"hello"
BinaryExprop, left, right3 + 4

Printing an AST

To verify our tree, we can write a function that converts it to a string:

function printAST(node) {
    if (node.type === "NumberLiteral") return String(node.value);
    if (node.type === "BinaryExpr") {
        return "(" + node.op + " " + printAST(node.left) + " " + printAST(node.right) + ")";
    }
}

This produces a Lisp-like format: (+ 3 (* 4 2)).

Your Task

Write helper functions num(n), str(s), and binop(op, left, right) that create AST nodes. Then write printAST(node) to display them. For StringLiteral, print the value in double quotes.

Node.js loading...
Loading...
Click "Run" to execute your code.