Compilers and interpreters · Part 28 of 36

From text to tree: lexing and parsing

Expert 20 min

Tokens, grammars, recursive-descent parsing, operator precedence and abstract syntax trees — with a tiny calculator.

What you will learn

  • You can split source text into tokens.
  • You can write a grammar and a recursive-descent parser for arithmetic.
  • You can explain what an abstract syntax tree represents.

Before this: Graphs: breadth-first, depth-first and Dijkstra

The pipeline

Whether a language is compiled ahead of time (C, Rust, Go) or run by an interpreter (Python, JavaScript), the front end looks the same:

  1. Lexing (scanning): characters → tokens.
  2. Parsing: tokens → a tree that shows the structure.
  3. Semantic analysis: resolve names, check types, report errors.
  4. Then either interpret the tree/bytecode or generate code (machine code, bytecode, WebAssembly).
The compiler pipeline from source text through tokens, syntax tree and bytecode to execution
Source → tokens → AST → bytecode or machine code
Blocks of coloured shapes being sorted into a small tree structure

Lexing

The lexer groups characters into tokens — the words of the language — and throws away spaces and comments.

price * (1 + tax) becomes IDENT(price) STAR LPAREN NUMBER(1) PLUS IDENT(tax) RPAREN.

Lexers are usually a loop with a few cases: digits start a number, letters an identifier or keyword, quotes a string, and so on.

Grammar and precedence

A grammar describes which token sequences are valid. For arithmetic with the usual precedence (× before +):

expr   → term (("+" | "-") term)*
term   → factor (("*" | "/") factor)*
factor → NUMBER | IDENT | "(" expr ")" | "-" factor

Each rule handles one precedence level; lower rules bind more tightly. This layering is what makes 1 + 2 * 3 mean 1 + (2 * 3).

Recursive descent

The simplest hand-written parser turns each rule into a function:

function parseExpr() {
  let node = parseTerm();
  while (peek() === "+" || peek() === "-") {
    const op = next();
    node = { type: "binary", op, left: node, right: parseTerm() };
  }
  return node;
}
function parseTerm() {
  let node = parseFactor();
  while (peek() === "*" || peek() === "/") {
    const op = next();
    node = { type: "binary", op, left: node, right: parseFactor() };
  }
  return node;
}
function parseFactor() {
  const t = next();
  if (/^\d/.test(t)) return { type: "num", value: Number(t) };
  if (t === "(") { const e = parseExpr(); expect(")"); return e; }
  if (t === "-") return { type: "neg", arg: parseFactor() };
  throw new SyntaxError(`Unexpected ${t}`);
}

The loops make operators left-associative: 8 - 3 - 2 is (8 - 3) - 2 = 3. GCC, Clang and V8 use hand-written recursive-descent parsers; CPython replaced its old LL(1) parser with a PEG parser in Python 3.9 (2020). Parser generators (yacc/Bison, ANTLR, tree-sitter for editors) build parsers from a grammar file.

Abstract syntax trees

The parser's output is an abstract syntax tree (AST): brackets and separators are gone, only structure remains. price * (1 + tax) becomes a * node with price on the left and a + node on the right.

Many tools work on ASTs: formatters (Prettier, Black), linters (ESLint, Ruff), bundlers, refactoring tools and syntax highlighting. Python exposes its AST with the ast module — ast.dump(ast.parse("1 + 2 * 3")) shows the tree.

Evaluating the tree

A tree-walking interpreter evaluates the AST recursively:

function evaluate(n, env) {
  switch (n.type) {
    case "num": return n.value;
    case "neg": return -evaluate(n.arg, env);
    case "binary": {
      const a = evaluate(n.left, env), b = evaluate(n.right, env);
      return n.op === "+" ? a + b : n.op === "-" ? a - b : n.op === "*" ? a * b : a / b;
    }
  }
}

That is a complete, safe calculator — no eval, so user input can never run arbitrary code. This is exactly how safe formula fields in spreadsheets and apps work.

Key points

  • Front end: lexing (characters → tokens), parsing (tokens → tree), semantic checks.
  • A grammar's layering of rules defines precedence; loops give left associativity.
  • Recursive descent turns each grammar rule into a function.
  • The AST keeps structure only; formatters, linters and refactorings work on it.
  • A tree-walking evaluator is a safe alternative to eval for formulas.

Flashcards

Question: What does a lexer produce?
Answer: A sequence of tokens.
Question: Why does 1 + 2 * 3 parse as 1 + (2 * 3)?
Answer: Multiplication is handled by a lower, tighter-binding grammar rule (term) than addition (expr).
Question: What kind of parser has CPython used since Python 3.9?
Answer: A PEG parser.
Question: Why use your own expression evaluator instead of eval?
Answer: It only understands the grammar you allow, so input can't run arbitrary code.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. With the grammar from the lesson, what does 8 - 3 - 2 evaluate to?

    Show the answer

    3

    Left associativity: (8 − 3) − 2 = 3.

    Source: Crafting Interpreters, ch. 6

  2. Order the front-end stages.

    Show the answer

    Lexing → Parsing → Semantic analysis → Interpretation or code generation

    Characters become tokens, tokens a tree, the tree is checked and then executed or compiled.

    Source: Aho et al., ch. 1

  3. In the AST of price * (1 + tax), which node is at the root?

    • The * node
    • The + node
    • price
    • The parentheses
    Show the answer

    The * node

    The multiplication is applied last, so it is the root; parentheses leave no node.

    Source: Crafting Interpreters, ch. 5

  4. Python’s standard library module for syntax trees is called ___.

    Show the answer

    ast

    ast.parse() returns the abstract syntax tree of Python code.

    Source: Python docs, ast

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.