← Runtimes
Runtimes

Parsing, syntax trees, and intermediate forms

Tokens, a tree, then instructions: each stage decides something.

Compilers make source meaning inspectable by turning text into structured representations.

Outcome

Predict a tree from a language’s precedence and associativity, lower a tree to instructions in postorder, and find a faulty stage by the first representation that is wrong.

Terminology (7)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Token
One meaningful piece of source text: a number, a name, an operator.
Syntax tree
The structure a parser builds from tokens; each operation is a node whose children are its operands.
Precedence
Which operators bind tighter, and so sit lower in the tree.
Associativity
How operators of equal precedence group: from the left or from the right.
Intermediate representation (IR)
A compiler representation used between source parsing and later execution/code generation. It may use instructions, blocks or graphs; this lab uses a simple stack instruction list.
Postorder
Visiting a node’s children before the node itself, so operands come before their operator.
Bytecode
V8’s Ignition instructions, which it interprets before optimizing hot functions.

Why compilers use several representations

Source text serves the programmer; a compiler needs explicit structure to analyze and transform it. Parsing determines how the meaningful pieces of that text fit together. The resulting syntax tree represents operations and operands, rather than just their positions on a line.

An intermediate representation, or IR, expresses the computation in a form suited to later compiler work. It may be a tree, a graph or instructions for a particular machine model. Moving between forms must preserve the language’s meaning, even when the later form looks different. Inspecting these boundaries helps separate a grouping decision from a later transformation.

01Grouping

How does the parser group an expression?

A checkout team is porting its pricing expressions from Go to another language. The same price-table key now selects a different row, although both programs accept it. Follow the expression through tokens and grouping before changing its arithmetic, then use the same representations to inspect the small compiler that runs the checkout’s saved pricing rules.

A lexer turns text into tokens: numbers, names, operators. A parser arranges the tokens into a tree. Precedence decides which operator sits lower in the tree; associativity decides how operators of equal precedence group.

Each program prints three expressions from a checkout pricing service: a net price after a coupon and a store credit, a shipping charge, and a price-table key that packs the customer tier above two flag bits and sets the low one. Their values depend only on the tree the parser built.

TypeScript uses JavaScript’s expression grammar: * above +, and + above <<.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Three checkout pricing expressions whose values depend only on how the parser groups them.

const subtotal = 10;
const coupon = 4;
const credit = 3;
const fee = 5;
const qty = 4;
const unit = 3;
const tier = 1;

console.log(`subtotal - coupon - credit = ${subtotal - coupon - credit}`);
console.log(`fee + qty * unit = ${fee + qty * unit}`);
console.log(`tier << 2 + 1 = ${tier << 2 + 1}`);
The first two lines print 3 and 17. What does the third line print?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --strict && node main.js

The examples use small pure integer expressions, avoiding overflow and shift-width differences. The quoted outputs and intermediate forms are historical captures from 1 November 2026, with toolchain versions recorded in the author evidence. Put each example in the shown file to inspect it; the second example’s first comment names its inspection command. New versions and flags can change diagnostics and IR spelling.

02Intermediate forms

What does a toolchain make of the tree?

The checkout’s rule compiler next needs instructions for its stack machine. A postorder walk fits this target: finish the left child, finish the right child, then emit the operator that consumes those values. Production compilers use many intermediate forms, including control-flow graphs and SSA values; they can share or reorder computations. Their representations need to preserve the source meaning, not reproduce a literal tree walk.

Each program defines netPrice(subtotal, coupon, credit) = subtotal - coupon - credit and prints netPrice(10, 4, 3). The first comment line names the command that shows the toolchain’s own form of that function.

In the recorded Node/V8 build, this inspection command prints Ignition bytecode for an accumulator machine. tsc emits the JavaScript that V8 reads; this is not the lab’s stack instruction set.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// One function to inspect: node --print-bytecode --print-bytecode-filter=netPrice main.js

function netPrice(subtotal: number, coupon: number, credit: number): number {
  return subtotal - coupon - credit;
}

console.log(netPrice(10, 4, 3));
The rule compiler lowers subtotal - coupon - credit for a stack machine whose sub pops the right operand, then the left, and pushes left - right. Which instruction order is correct?

03Finding the stage

Which stage is wrong?

When a compiled pricing rule charges the wrong amount, compare each representation with what it should be: tokens, then tree, then instructions. The first one that is wrong belongs to the stage at fault.

A parser can also stop after a complete prefix. In this lab, operands and groups inside that prefix are well formed; malformed examples add tokens afterward, such as the final 3 in 5 + qty 3 or the unmatched closing parenthesis in fee - 1). A caller that compiles only that prefix silently prices a different rule. Missing operands and unmatched opening parentheses require diagnostics beyond the supplied primary parser and are outside this exercise’s input profile.

The rule compiler prints its tokens, its tree and its instructions. A test cart with a 10 subtotal, a 4 coupon and a 3 credit runs the rule 10 - 4 - 3 and is charged 9 instead of 3. The tokens are right, and the tree prints as (10 - (4 - 3)). Where is the fault?

04Practice

Finish the pricing-rule compiler

The lab is the checkout’s bounded pricing-rule compiler: a lexer, a precedence parser and a stack-code generator. Its ASCII names, integer arithmetic and instructions are authored rules, not a simulation of any of the four native toolchains. Each level supplies the parts that already work. Hard accepts complete expression prefixes and detects extra suffix tokens; the supplied parser assumes complete operands and matched inner groups.

The pricing-rule compiler

Split a pricing rule into tokens, group its operators, then compile it to stack instructions.

  1. easy · R-PARSE-V4-1 Split a rule into tokens
  2. medium · R-PARSE-V4-2 Group operators
  3. hard · R-PARSE-V4-3 Compile to a stack machine
In the frontend A tree preview can be only a parsed prefix Optional

The pricing-rule editor receives this declared parser result for 5 + qty 3: tree is (5 + qty), remaining is ["3"]. The helper follows the bounded grammar from the lab. These Save buttons are under review: what does a nonempty tree actually establish?

A readable preview is useful feedback, but it does not establish that the entire input was consumed. Keep the editor’s validation boundary tied to the whole rule it will save.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';
import { useState } from 'react';

declare function parseRule(text: string): {
  tree: string;
  remaining: string[];
};

export default function RuleEditor() {
  const [rule, setRule] = useState('5 + qty 3');
  const preview = parseRule(rule);
  return (
	<>
	  <input value={rule} onChange={(event) => setRule(event.target.value)} />
	  <pre>{preview.tree}</pre>
	  <button disabled={!preview.tree}>Save</button>
	</>
  );
}

Controlled input keeps the current text. Rendering a parser result and checking its tree field does not inspect the remaining tokens.

Sources: React: input,Svelte: derived state.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.