CSC 396 · Automata theory, Computability and Formal Languages
Our notes
2 min readThe front end of a compiler
- Lexical analysis (scanner): groups characters into tokens (identifiers, numbers, keywords, operators) using regular expressions and finite automata. Spaces and comments are thrown away.
- Syntax analysis (parser): checks the token sequence against the grammar and builds a parse tree.
- Semantic analysis: type checking, declarations.
Example: total := total + 15 gives tokens id(total), :=, id(total), +, num(15).
Pattern matching
Patterns (regular expressions) describe tokens:
- identifier: letter (letter | digit)*
- number: digit digit*
The scanner takes the longest match (so "total1" is one identifier, not total then 1) and gives keywords priority over identifiers.
Pattern matching in text (searching for a word in a document) uses the same automata; algorithms such as Knuth-Morris-Pratt (1977) avoid re-reading text.
Top-down parsing
Start from S and try to derive the input, left to right.
Recursive descent: one procedure per variable. For E → T E′, E′ → + T E′ | ε, T → F T′, T′ → * F T′ | ε, F → ( E ) | id:
- procedure E: call T; call E′.
- procedure E′: if the next token is +, match +, call T, call E′; otherwise do nothing (ε).
- procedure F: if the next token is (, match (, call E, match ); else match id.
It needs a grammar without left recursion and where one token of look-ahead decides each choice (LL(1)).
Bottom-up parsing
Start from the tokens and reduce them to S, finding the rightmost derivation in reverse.
Shift-reduce with a stack: shift tokens onto the stack; when the top matches a rule's right side (a handle), reduce it to the left side.
Trace id + id with E → E + T | T, T → id:
| Stack | Input | Action |
|---|---|---|
| id + id | shift | |
| id | + id | reduce T → id |
| T | + id | reduce E → T |
| E | + id | shift |
| E + | id | shift |
| E + id | reduce T → id | |
| E + T | reduce E → E + T | |
| E | accept |
LR parsers (and tools like yacc and bison) build tables that decide when to shift and when to reduce.
Error handling
A parser should report the line and what it expected ("; expected") and recover to find more errors, for example by skipping to the next semicolon (panic mode).
Exams usually ask
- Describe the phases of a compiler's front end.
- Write a recursive descent parser for a small grammar.
- Trace a shift-reduce parse.
Common mistake
Using recursive descent on a left-recursive grammar. E → E + T makes procedure E call itself immediately without reading anything, and it never stops; remove the left recursion first.
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.