Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Compilers Basics
Handbook~16 min readSystemsworked math + runnable code
The Compilers Basics Handbook

Text becomes
meaning.

You type 2 + 3 * 4 and a machine somehow knows the answer is 14, not 20 — that multiplication happens first. How does a flat string of characters become a meaning, with rules like precedence baked in? A compiler does it in stages: chop the text into tokens, reorder them by precedence into a form that's trivial to run, then run it. That's the whole shape of every compiler and interpreter, from a four-function calculator to a language that powers the world. This handbook builds the tiny version end to end, and it actually runs.

01

A pipeline of stages

A compiler turns source text into something runnable, and the secret is that it never does it all at once — it's a pipeline of stages, each with one clear job. First, tokenizing (lexing) chops the raw characters into meaningful atoms: numbers, operators, identifiers, keywords. Then parsing arranges those tokens into a structure that captures the grammar — crucially, which operations bind to which (precedence). Then evaluation or code generation turns that structure into a result or into machine code.

An interpreter shares the same front end — tokenize, parse — but evaluates the structure directly instead of emitting code; a compiler emits code to run later. Either way, the shape is identical: text → tokens → structure → meaning, one well-defined transformation at a time. That staging is what makes something as daunting as "understand a programming language" tractable: no single step is hard, and each hands a cleaner representation to the next. We'll build the smallest real instance — an arithmetic calculator that respects precedence — because it contains the whole idea in miniature.

The one-sentence version

A compiler is a pipeline — tokenize the text, parse tokens by precedence into an easy-to-run form (Reverse Polish Notation via shunting-yard), then evaluate on a stack — and that same three-stage shape scales from a calculator to a full language.

02

Tokenizing

The first stage, lexical analysis, scans the character stream and groups characters into tokens — the words of the language. Given "12 + 3", the lexer emits [12, +, 3]: it recognizes that the adjacent digits 1 and 2 form one number token, treats + as an operator token, and throws away the whitespace. It turns a flat, characterwise string into a clean sequence of typed units.

This matters because it frees every later stage from dealing with raw characters. The parser doesn't want to worry about whether a number is one digit or seven, where spaces go, or how to skip a comment — the lexer has already resolved all of that, handing up a tidy token stream. In a real language the lexer also recognizes string literals, identifiers, keywords versus names, and multi-character operators like == or ->. But the essence is exactly the calculator's: read left to right, accumulate characters into the token they belong to, and emit clean atoms. Get the atoms right and the hard part — structure — has something orderly to work on.

03

Parsing precedence

Now the crux: 2 + 3 * 4 must mean 2 + (3 * 4), not (2 + 3) * 4. Encoding that is the parser's job, and the classic compact way is Dijkstra's shunting-yard algorithm, which converts our normal infix notation into Reverse Polish Notation (RPN, postfix) — a form with no parentheses and no ambiguity, trivial to evaluate.

Shunting-yard: 3 + 4 * 2 → 3 4 2 * +
numberGoes straight to output.
operatorPop stack ops of higher/equal precedence to output first, then push this one.
"("Push it; on ")" flush output back to the matching "(".
endPop any remaining operators to output → the RPN.

The precedence lives in one comparison: when * is on the stack and + arrives, * (higher precedence) is popped to output first, so it will be applied before +. That single rule is where "multiplication binds tighter" is encoded. Parentheses override it by forcing everything inside to flush before the closing ). The output, RPN, is then evaluated with a plain stack: push numbers, and on each operator pop the top two, apply, push the result. All the precedence complexity moved into the parse; evaluation is dead simple. (Real compilers usually build an explicit tree — an AST — but RPN captures the same precedence resolution in the clearest possible form.)

04

The pipeline math

The whole calculator is the composition of three functions — the classic compiler pipeline in miniature:

calc(src)  =  eval_rpn( to_rpn( tokenize(src) ) )

tokenize: string → tokens. to_rpn: infix tokens → postfix (shunting-yard). eval_rpn: postfix → value (stack).

Shunting-yard's precedence rule is the single comparison that makes * bind before +, and stack evaluation folds the RPN into a number:

on operator t:  pop while  prec(top) ≥ prec(t)  ⟹  2 + 3 * 4 → RPN  2 3 4 * + → 14  (not 20)

Because 3*4 is computed before the +, the answer is 14; parentheses (2+3)*4 flush the + first and give 20. The runnable version below is the whole tokenize → RPN → eval pipeline.

RUN IT YOURSELF

A calculator, in three stages

This is a whole (tiny) compiler front-to-back. tokenize chops the string into number and operator tokens, keeping multi-digit numbers whole. to_rpn is the shunting-yard algorithm: it reorders the infix tokens into Reverse Polish Notation, and the one precedence comparison is where "*" is made to bind tighter than "+". eval_rpn runs the RPN on a stack — push numbers, pop two and apply on each operator. So 2 + 3 * 4 is 14, not 20, and parentheses override precedence. It is deliberately minimal: non-negative whole numbers, binary operators only, and no input checking, so -7 / 2 crashes and malformed input like 2 3 + 4 can return a wrong answer silently (the self-check below explains each). Change the expression and watch the tokens, the RPN, and the result.

CPython · WebAssembly
05

Scaling to real languages

The calculator is small, but the skeleton is exactly what a production compiler uses — just with more stages bolted on:

StageCalculator · real compiler
LexDigits/operators → tokens · plus identifiers, keywords, strings, comments, positions for error messages.
ParseShunting-yard → RPN · a full grammar → an abstract syntax tree (AST) for statements, functions, types.
Analyze(none) · semantic analysis: type checking, scope/name resolution, catching errors before running.
Optimize(none) · transform the IR — constant folding, dead-code elimination, inlining — for faster output.
GenerateEvaluate on a stack · emit machine code or bytecode (or interpret the AST directly).

The shape never changes: text becomes tokens becomes a tree becomes lower-level code. A modern compiler adds an intermediate representation (IR) in the middle so optimization and code generation can target many source languages and many CPUs through a shared core (that's the whole idea behind LLVM). And an interpreter simply stops after building the tree and walks it. Even the thing turning your prompts into tokens for a language model is a lexer at heart. Once you see the pipeline in the calculator, you see it everywhere — the difference between a toy and a real compiler is the number of stages and the richness of each, not the shape.

06

Pitfalls

The first classic mistake is parsing with regexes or string splitting. It works for the simplest inputs and then collapses the moment you hit nesting — parentheses inside parentheses, precedence, function calls. Regular expressions genuinely cannot parse a nested grammar (it's a formal-language fact, not a skill issue); you need a real parser with a stack or recursion. Reaching for str.split to "parse" structured input is a trap that always ends in a rewrite.

Two more. Conflating the stages: trying to tokenize and evaluate in one pass tangles concerns and makes precedence and errors nearly impossible to get right — keep lex, parse, and evaluate as separate, testable steps, exactly as the pipeline prescribes. And ignoring error handling: real input is malformed — unmatched parentheses, stray operators, unexpected end — and a parser must report where and why, not crash or silently produce garbage (this is why lexers track line and column positions). The payoff for respecting the pipeline is huge: parsing and interpreting stop being intimidating and become a sequence of small, well-understood transformations you can build and test one at a time. The whole handbook is that realization — a compiler is not magic, it's a pipeline: chop into tokens, reorder by precedence, evaluate on a stack, and repeat the pattern all the way up to a real language.

Worth knowing

Don't parse nested grammars with regexes — you need a stack-based parser. Keep lex, parse, and evaluate as separate testable stages, and track positions so you can report where an error is. The calculator's tokenize→RPN→eval pipeline is the same skeleton a real compiler scales up.

By the numbers

Worked example: 2 * (3 + 4) - 5, token by token

Feed 2 * (3 + 4) - 5 to the page’s code. tokenize gives nine tokens. Here is what to_rpn does with each one, with the output list and the operator stack after the step.

TokenRule that firesOutputOp stack
2number: straight to output2(empty)
*stack empty: push2*
(always push2* (
3number2 3* (
+top is (, not an operator: push2 3* ( +
4number2 3 4* ( +
)pop to output until (, drop the (2 3 4 +*
-* has prec 2 ≥ 1: pop it, then push -2 3 4 + *-
5number2 3 4 + * 5-
endpop everything left2 3 4 + * 5 -(empty)

The two highlighted rows are where the meaning is decided. The ( shielded + from the * below it, so the sum is grouped first. Then - forced the waiting * out before itself. Now eval_rpn runs the postfix on a stack: push 2, 3, 4; + pops 4 and 3 and pushes 7; * pops 7 and 2 and pushes 14; push 5; - pops 5 and 14 and pushes 9. Pop order matters: the first pop is the right operand, which is why the code writes b, a = stack.pop(), stack.pop(). Swap them and 14 - 5 becomes 5 - 14.

Trade-offs

Complexity and trade-offs of each stage

For an input of n characters (or tokens):

CaseTimeSpaceWhy
TokenizeO(n)O(n) tokensEach character is looked at once, left to right.
Shunting-yardO(n)O(n) operator stackEach operator is pushed once and popped once, so the inner while loops add up to n in total. The stack grows with nesting depth.
Evaluate RPNO(n)O(n) value stackOne push per number, one pop-pop-push per operator. 1 2 3 4 + + + holds four values at once.
Recursive descent / Pratt parserO(n)O(depth) call stackWhat most hand-written compilers use instead. It builds a tree directly and handles statements, calls and unary operators naturally.
General CFG parser (CYK, Earley)O(n³) worst caseO(n²) tableAccepts any grammar, even ambiguous ones. Language designers pick grammars a linear parser can handle instead.
Tree-walking vs bytecodeSame O(work) per runAST vs flat codeWalking the tree is simplest. Compiling once to bytecode or machine code cuts the per-node overhead on every later run.

The whole front end is linear, which is why compilers can parse millions of lines quickly. The slow parts of a real compiler are analysis and optimization, not reading the text.

In the wild

Where this shows up in real-world systems and interviews

  • CPython is this pipeline

    Python source is tokenized, parsed to an AST, compiled to bytecode, and run on a stack-based virtual machine. The ast module shows you the tree and dis shows the bytecode. Disassemble a + b * c and the instructions come out in RPN order: load a, load b, load c, multiply, add.

  • Stack machines everywhere

    JVM bytecode and WebAssembly are stack machines too, and so is eval_rpn. Postfix code is easy to generate and easy to verify, so it became the common format between a compiler front end and the machine that runs it.

  • Queries, formulas and configs

    A SQL database tokenizes and parses each query into a tree, then plans and optimizes it before running it. Spreadsheet formulas, template languages, JSON and regex engines all start with a lexer and a parser. When a tool reports “unexpected token at line 3, column 14”, that is the lexer’s position tracking at work.

  • The interview version

    “Evaluate an expression with + - * / and parentheses” and “evaluate Reverse Polish Notation” are classic interview problems, and this page’s code solves both. Interviewers then probe the edges: unary minus, malformed input, and division. Python’s // floors, so -7 // 2 is -4, while C and Java truncate to -3. Ask which one they want.

Self-check

Check yourself

What RPN and value does the page’s code give for 8 - 3 - 2? What if the pop rule used > instead of >=?

With >=, the second - pops the first one (equal precedence), giving 8 3 - 2 - = 3, the correct left-to-right answer. With >, nothing pops, the RPN is 8 3 2 - -, meaning 8 - (3 - 2) = 7. The = in >= is what makes operators left-associative.

You add ^ for powers, with the highest precedence. Why must 2 ^ 3 ^ 2 be 512, and what changes in to_rpn?

Powers group from the right: 2 ^ (3 ^ 2) = 29 = 512, not (23)2 = 64. A right-associative operator must not pop an equal-precedence operator, so for ^ the loop pops only while prec(top) > prec(t). Precedence decides which operator binds tighter; associativity decides ties.

Predict what the page’s code does with -7 / 2.

It crashes. The lexer has no idea of a negative number, so the tokens are - 7 / 2, the RPN is 7 2 / -, and the final - tries to pop two values from a stack holding one: IndexError. The fix belongs in the lexer or parser: a - at the start, after ( or after another operator is unary. Emit a separate neg token with higher precedence that pops one operand.

Try "2 + 3)", "(2 + 3" and "2 3 + 4". Which fail loudly, and which return a wrong answer silently?

2 + 3) returns 5: the stray ) is ignored. (2 + 3 crashes, because the leftover ( is flushed into the output and treated as an operator. 2 3 + 4 silently returns 2: the RPN is 2 3 4 +, the stack ends as [2, 7], and the code returns stack[0]. The silent wrong answer is the worst of the three. A real parser raises an error with a position for an unmatched bracket, and checks that exactly one value is left at the end.

Frequently asked

Quick answers

What does a compiler do?

Turns source text into runnable output in stages: tokenize → parse into structure → analyze/optimize → generate code. An interpreter evaluates the structure directly.

What is tokenizing?

Scanning characters into meaningful tokens — "12 + 3" becomes [12, +, 3] — so later stages work on clean atoms, not raw characters.

What is shunting-yard?

Dijkstra's algorithm converting infix to postfix (RPN) using an operator stack; its precedence comparison is where "*" is made to bind tighter than "+".

How is RPN evaluated?

With one stack: push numbers, and on each operator pop the top two, apply, push the result. No precedence rules needed — the order encodes them.

▶  Watch it explained

How regex engines work: the Thompson NFA

Finished this one? 0 / 209 Handbooks done
NextThe Operating Systems Fundamentals Handbook Next on the “How computers actually work” ladder · rung 3 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks