From Text to Tree: How a Compiler Reads Code

Before a compiler can check or optimize anything, it turns characters into tokens and tokens into a tree. Here is what each step does.

Front End2 min read
Front End

A compiler first sees a program as plain characters. Two early stages turn them into a structure it can reason about: the lexer groups characters into tokens, and the parser arranges the tokens into a syntax tree.

Lexing: Characters to Tokens

A token is the smallest unit that carries meaning: a keyword, a name, a number or an operator. The lexer also drops what the grammar does not need, such as whitespace and comments.

main.rsRust
let total = price * 3;
tokens
KEYWORD letIDENT totalEQ =IDENT priceSTAR *INT 3SEMI ;

Most token kinds can be described with regular expressions, which is why lexers are usually written as a simple state machine that reads one character at a time. Some compilers generate this code with a tool; rustc's lexer is written by hand.

Parsing: Tokens to a Tree

The parser checks that the tokens follow the grammar and builds a tree that records which part belongs to which. The tree makes operator precedence explicit: in a + b * c the multiplication sits deeper in the tree, so it is evaluated first.

syntax tree
Let├─ name: total└─ Binary(*) ├─ Path(price) └─ Literal(3)

A common way to write a parser by hand is recursive descent: each grammar rule becomes a function, and that function calls the functions of the rules it contains.

Errors Are Part of the Job

Code that is still being written is often incomplete. A good parser does not stop at the first error: it reports a clear message, skips ahead to the next safe point (for example the start of the next statement) and keeps going. That way a single run can report more than one error.

The lexer and the parser are the very front of the front end. Everything after them, such as name resolution, type checking and IR generation, works on the tree, not on the text.

Sources

  1. A. V. Aho, M. S. Lam, R. Sethi, J. D. Ullman. Compilers: Principles, Techniques, and Tools, 2nd ed., Addison-Wesley, 2006, ch. 3 (lexical analysis) and ch. 4 (syntax analysis).
  2. R. Nystrom. Crafting Interpreters, “Scanning” and “Parsing Expressions”. craftinginterpreters.com/scanning, craftinginterpreters.com/parsing-expressions
  3. The Rust Reference, “Tokens”. doc.rust-lang.org/reference/tokens
  4. Rust Compiler Development Guide, “Lexing and parsing”. rustc-dev-guide.rust-lang.org/the-parser