The pipeline
A compiler is a chain of small translations. Each stage takes one representation and produces a simpler, more precise one.
| Stage | Input → output | For x = 1 + 2 * 3 |
|---|---|---|
| Lexing | Characters → tokens | x = 1 + 2 * 3 |
| Parsing | Tokens → syntax tree | =(x, +(1, *(2, 3))) |
| Analysis | Tree → checked tree | x is an integer; every name is defined. |
| Optimization | Tree or IR → faster IR | 1 + 2 * 3 folds to 7 at compile time. |
| Code generation | IR → instructions | mov eax, 7 |
The front end (lexing, parsing, analysis) understands the language. The back end (optimization, code generation) understands the machine. Projects like LLVM share one back end across many languages, which is how Rust, Swift and Clang all reach the same CPUs.
A tiny compiler
The code below compiles arithmetic like 2 * (3 + 4) into instructions for a tiny stack machine, then runs them. It has all three core stages:
tokenizeturns"12+(3)"into["12", "+", "(", "3", ")"].compileis a recursive descent parser: one function per grammar rule.exprhandles+and-,termhandles*, andfactorhandles numbers and parentheses. Becauseexprcallsterm, multiplication binds tighter than addition.- Code generation happens as it parses. After both sides of an operator are compiled, it emits the operator, giving postfix order:
1 + 2 * 3becomespush 1, push 2, push 3, mul, add.
def tokenize(source):
"""Lexing: turn characters into tokens."""
tokens, i = [], 0
while i < len(source):
ch = source[i]
if ch.isspace():
i += 1
elif ch.isdigit():
j = i
while j < len(source) and source[j].isdigit():
j += 1
tokens.append(source[i:j])
i = j
elif ch in "+-*()":
tokens.append(ch)
i += 1
else:
raise SyntaxError(f"unexpected character {ch!r}")
return tokens
def compile_expr(source):
"""Parsing and code generation: tokens in, stack-machine instructions out."""
tokens, code, pos = tokenize(source), [], 0
def peek():
return tokens[pos] if pos < len(tokens) else None
def take():
nonlocal pos
pos += 1
return tokens[pos - 1]
def expr(): # expr := term (("+" | "-") term)*
term()
while peek() in ("+", "-"):
op = take()
term()
code.append("add" if op == "+" else "sub")
def term(): # term := factor ("*" factor)*
factor()
while peek() == "*":
take()
factor()
code.append("mul")
def factor(): # factor := number | "(" expr ")"
tok = take() if peek() is not None else None
if tok == "(":
expr()
if peek() != ")":
raise SyntaxError("expected )")
take()
elif tok is not None and tok.isdigit():
code.append("push " + tok)
else:
raise SyntaxError(f"unexpected {tok!r}")
expr()
if peek() is not None:
raise SyntaxError(f"unexpected {peek()!r}")
return code
def run(code):
"""A tiny virtual machine: every instruction works on a stack."""
stack = []
for ins in code:
if ins.startswith("push "):
stack.append(int(ins[5:]))
else:
b, a = stack.pop(), stack.pop()
stack.append(a + b if ins == "add" else a - b if ins == "sub" else a * b)
return stack.pop()// Lexing: turn characters into tokens.
function tokenize(source) {
const tokens = [];
let i = 0;
while (i < source.length) {
const ch = source[i];
if (/\s/.test(ch)) {
i++;
} else if (/[0-9]/.test(ch)) {
let j = i;
while (j < source.length && /[0-9]/.test(source[j])) j++;
tokens.push(source.slice(i, j));
i = j;
} else if ('+-*()'.includes(ch)) {
tokens.push(ch);
i++;
} else {
throw new SyntaxError(`unexpected character ${JSON.stringify(ch)}`);
}
}
return tokens;
}
// Parsing and code generation: tokens in, stack-machine instructions out.
function compile(source) {
const tokens = tokenize(source);
const code = [];
let pos = 0;
const peek = () => tokens[pos];
function expr() { // expr := term (("+" | "-") term)*
term();
while (peek() === '+' || peek() === '-') {
const op = tokens[pos++];
term();
code.push(op === '+' ? 'add' : 'sub');
}
}
function term() { // term := factor ("*" factor)*
factor();
while (peek() === '*') {
pos++;
factor();
code.push('mul');
}
}
function factor() { // factor := number | "(" expr ")"
const tok = tokens[pos++];
if (tok === '(') {
expr();
if (peek() !== ')') throw new SyntaxError('expected )');
pos++;
} else if (tok !== undefined && /^[0-9]+$/.test(tok)) {
code.push('push ' + tok);
} else {
throw new SyntaxError(`unexpected ${JSON.stringify(tok)}`);
}
}
expr();
if (pos < tokens.length) throw new SyntaxError(`unexpected ${JSON.stringify(peek())}`);
return code;
}
// A tiny virtual machine: every instruction works on a stack.
function run(code) {
const stack = [];
for (const ins of code) {
if (ins.startsWith('push ')) {
stack.push(Number(ins.slice(5)));
continue;
}
const b = stack.pop();
const a = stack.pop();
stack.push(ins === 'add' ? a + b : ins === 'sub' ? a - b : a * b);
}
return stack.pop();
}import (
"fmt"
"strconv"
"strings"
"unicode"
)
func isDigit(r rune) bool { return r >= '0' && r <= '9' }
// tokenize is lexing: it turns characters into tokens.
func tokenize(source string) ([]string, error) {
var tokens []string
runes := []rune(source)
for i := 0; i < len(runes); {
ch := runes[i]
switch {
case unicode.IsSpace(ch):
i++
case isDigit(ch):
j := i
for j < len(runes) && isDigit(runes[j]) {
j++
}
tokens = append(tokens, string(runes[i:j]))
i = j
case strings.ContainsRune("+-*()", ch):
tokens = append(tokens, string(ch))
i++
default:
return nil, fmt.Errorf("unexpected character %q", ch)
}
}
return tokens, nil
}
type parser struct {
tokens []string
pos int
code []string
}
func (p *parser) peek() string {
if p.pos < len(p.tokens) {
return p.tokens[p.pos]
}
return ""
}
// expr := term (("+" | "-") term)*
func (p *parser) expr() error {
if err := p.term(); err != nil {
return err
}
for p.peek() == "+" || p.peek() == "-" {
op := p.peek()
p.pos++
if err := p.term(); err != nil {
return err
}
if op == "+" {
p.code = append(p.code, "add")
} else {
p.code = append(p.code, "sub")
}
}
return nil
}
// term := factor ("*" factor)*
func (p *parser) term() error {
if err := p.factor(); err != nil {
return err
}
for p.peek() == "*" {
p.pos++
if err := p.factor(); err != nil {
return err
}
p.code = append(p.code, "mul")
}
return nil
}
// factor := number | "(" expr ")"
func (p *parser) factor() error {
tok := p.peek()
p.pos++
switch {
case tok == "(":
if err := p.expr(); err != nil {
return err
}
if p.peek() != ")" {
return fmt.Errorf("expected )")
}
p.pos++
case tok != "" && isDigit(rune(tok[0])):
p.code = append(p.code, "push "+tok)
default:
return fmt.Errorf("unexpected %q", tok)
}
return nil
}
// compile parses and generates code: tokens in, stack-machine instructions out.
func compile(source string) ([]string, error) {
tokens, err := tokenize(source)
if err != nil {
return nil, err
}
p := &parser{tokens: tokens}
if err := p.expr(); err != nil {
return nil, err
}
if p.pos < len(tokens) {
return nil, fmt.Errorf("unexpected %q", tokens[p.pos])
}
return p.code, nil
}
// run is a tiny virtual machine: every instruction works on a stack.
func run(code []string) int {
var stack []int
for _, ins := range code {
if n, ok := strings.CutPrefix(ins, "push "); ok {
v, _ := strconv.Atoi(n)
stack = append(stack, v)
continue
}
a, b := stack[len(stack)-2], stack[len(stack)-1]
stack = stack[:len(stack)-2]
switch ins {
case "add":
stack = append(stack, a+b)
case "sub":
stack = append(stack, a-b)
default:
stack = append(stack, a*b)
}
}
return stack[len(stack)-1]
}// Lexing: turn characters into tokens.
fn tokenize(source: &str) -> Result<Vec<String>, String> {
let chars: Vec<char> = source.chars().collect();
let mut tokens = Vec::new();
let mut i = 0;
while i < chars.len() {
let ch = chars[i];
if ch.is_whitespace() {
i += 1;
} else if ch.is_ascii_digit() {
let start = i;
while i < chars.len() && chars[i].is_ascii_digit() {
i += 1;
}
tokens.push(chars[start..i].iter().collect());
} else if "+-*()".contains(ch) {
tokens.push(ch.to_string());
i += 1;
} else {
return Err(format!("unexpected character {:?}", ch));
}
}
Ok(tokens)
}
struct Parser {
tokens: Vec<String>,
pos: usize,
code: Vec<String>,
}
impl Parser {
fn peek(&self) -> Option<&str> {
self.tokens.get(self.pos).map(|s| s.as_str())
}
// expr := term (("+" | "-") term)*
fn expr(&mut self) -> Result<(), String> {
self.term()?;
loop {
let op = match self.peek() {
Some("+") => "add",
Some("-") => "sub",
_ => break,
};
self.pos += 1;
self.term()?;
self.code.push(op.to_string());
}
Ok(())
}
// term := factor ("*" factor)*
fn term(&mut self) -> Result<(), String> {
self.factor()?;
while self.peek() == Some("*") {
self.pos += 1;
self.factor()?;
self.code.push("mul".to_string());
}
Ok(())
}
// factor := number | "(" expr ")"
fn factor(&mut self) -> Result<(), String> {
let tok = self.peek().map(|t| t.to_string());
self.pos += 1;
match tok {
Some(t) if t == "(" => {
self.expr()?;
if self.peek() != Some(")") {
return Err("expected )".to_string());
}
self.pos += 1;
}
Some(t) if t.chars().all(|c| c.is_ascii_digit()) => self.code.push(format!("push {}", t)),
other => return Err(format!("unexpected {:?}", other)),
}
Ok(())
}
}
// Parsing and code generation: tokens in, stack-machine instructions out.
fn compile(source: &str) -> Result<Vec<String>, String> {
let mut p = Parser { tokens: tokenize(source)?, pos: 0, code: Vec::new() };
p.expr()?;
if let Some(t) = p.peek() {
return Err(format!("unexpected {:?}", t));
}
Ok(p.code)
}
// A tiny virtual machine: every instruction works on a stack.
fn run(code: &[String]) -> i64 {
let mut stack: Vec<i64> = Vec::new();
for ins in code {
if let Some(n) = ins.strip_prefix("push ") {
stack.push(n.parse().unwrap());
continue;
}
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
stack.push(match ins.as_str() {
"add" => a + b,
"sub" => a - b,
_ => a * b,
});
}
stack.pop().unwrap()
}run is a virtual machine. Each push puts a number on a stack; each operator pops two and pushes the result. The Java JVM, Python’s bytecode and WebAssembly are all stack machines built on the same idea.
Compilers vs interpreters
| Compiler | Interpreter | |
|---|---|---|
| When it translates | Before the program runs | While it runs |
| Startup | Slower build, then fast start | Starts at once |
| Speed | Usually faster | Usually slower |
| Errors | Many caught before running | Found when the line runs |
Most modern runtimes mix both. A just-in-time (JIT) compiler starts by interpreting, watches which code runs often, and compiles just that to machine code.
Common mistakes
- Thinking compiled means bug-free. A compiler checks syntax and, in typed languages, types. It can’t check that your logic is right; that’s what testing is for.
- Parsing with regular expressions. Regexes can’t match nested structure like parentheses. Real languages need a parser.
- Ignoring warnings. Compiler warnings are cheap bug reports. Most teams build with warnings treated as errors.
Check yourself
Check yourself
Which stage turns total = price 2 into the tokens total, =, price, , 2?
The lexer groups characters into tokens. The parser then arranges those tokens into a tree.
Check yourself
What does the stack machine in the example leave on the stack after push 4, push 3, sub?
sub pops 3, then 4, and pushes 4 − 3 = 1. The order matters: the value pushed first is the left operand.
Sources
- Alfred Aho, Monica Lam, Ravi Sethi and Jeffrey Ullman, Compilers: Principles, Techniques, and Tools, 2nd edition (2006).
- Robert Nystrom, Crafting Interpreters (2021), craftinginterpreters.com.
- Chris Lattner and Vikram Adve, “LLVM: A Compilation Framework for Lifelong Program Analysis & Transformation,” CGO 2004.
Finished this page?
Your list