Sub topic 1
Where Lexing, Parsing, and Translation Fit in a Compiler
Prerequisites
This chapter assumes you know:
- Regular expressions and finite automata at an introductory level.
- Context-free grammars, at the level of reading a production such as
E -> E + T. - Stacks, trees, and recursion.
- Basic set notation.
Nothing here requires computing anything yet. The chapter sets up the map that the remaining chapters fill in.
The compiler as a pipeline
A compiler translates a source program into a target program, usually machine code. It does this in phases. Each phase reads one representation of the program and writes the next one.
The phases split into two groups:
- Front end (analysis): works out what the source program means. It covers lexical analysis, syntax analysis, semantic analysis, and intermediate code generation. It depends on the source language and not on the target machine.
- Back end (synthesis): builds the target program. It covers code optimization and code generation. It depends on the target machine.
This tutorial covers the front end: the lexer, the parser, and syntax-directed translation.
What each front-end phase does
| Phase | Consumes | Produces | Formal tool |
|---|---|---|---|
| Lexical analysis | Stream of characters | Stream of tokens | Regular expressions, finite automata |
| Syntax analysis (parsing) | Stream of tokens | Parse tree or syntax tree | Context-free grammars |
| Semantic analysis and translation | Parse tree | Annotated tree, intermediate code | Syntax-directed definitions and schemes |
Lexical analysis
The lexical analyzer (lexer or scanner) groups characters into tokens. It also removes whitespace and comments, and it can record identifiers in the symbol table. Later chapters define tokens, lexemes, and patterns precisely. For now, a token is a category such as identifier or number. Each token usually carries an attribute, such as a pointer to the symbol table entry or the numeric value.
Syntax analysis
The parser checks that the token stream follows the grammar of the language. It builds a tree that shows how the tokens group into expressions, statements, and blocks. It reports a syntax error when no valid structure exists.
Semantic analysis and translation
Semantic analysis checks rules that a context-free grammar cannot express. Examples are declaring a variable before use, matching types, and passing the right number of arguments. Syntax-directed translation attaches rules to grammar productions. These rules compute values, check types, or emit code while the parser works.
A worked example
Take the statement:
position = initial + rate * 60The phases process it as follows.
- Lexer. It outputs the token stream
<id,1> <=> <id,2> <+> <id,3> <*> <num,60>. The numbers 1 to 3 index the symbol table entries forposition,initial, andrate. - Parser. It builds a tree in which
*bindsrateand60first, then+combinesinitialwith that product, then=assigns the result. The shape of the tree encodes operator precedence. - Semantic analysis. Suppose all three identifiers are floats. The analyzer inserts a conversion for the integer constant 60.
- Intermediate code. The translator emits three-address code:
t1 = inttofloat(60)
t2 = id3 * t1
t3 = id2 + t2
id1 = t3The optimizer and code generator then work on this output. The front end ends here.
Why lexing and parsing are separate
Regular expressions are enough for tokens. A grammar is needed for structure. A finite automaton cannot count, so it cannot check that parentheses are balanced to arbitrary depth. A context-free grammar can. Splitting the work gives three benefits:
- Simpler design. The parser never deals with whitespace or comments.
- Efficiency. Lexing is a tight loop over characters, and specialized buffering makes it fast.
- Portability. Character-set and file-format details stay in the lexer.
In practice the parser drives the lexer. It calls a routine like getNextToken() whenever it needs more input. Most parsers in this tutorial use one token of lookahead.
Where each kind of error is caught
GATE questions often ask which phase detects a given error.
| Error | Phase |
|---|---|
| Illegal character, such as `@` in a language that does not allow it | Lexical |
| Unterminated string literal | Lexical |
| Identifier that begins with a digit and has no valid token interpretation | Lexical |
| Missing semicolon, unbalanced parentheses | Syntax |
| `else` without a matching `if` | Syntax |
| Use of an undeclared variable | Semantic |
| Adding a string to an integer in a statically typed language | Semantic |
| Division by zero that depends on runtime input | Run time, not compile time |
Why this order matters for the rest of the tutorial
The next chapters follow the data flow. First comes the lexer, covering tokens, regular expressions, automata, and maximal munch. Then comes the parser, covering grammars, derivations, ambiguity, FIRST and FOLLOW sets, LL(1) parsing, and the LR family. The last part covers syntax-directed definitions and schemes, which reuse the parser's tree to compute meaning.
Exercise
For each error, name the phase that detects it: (a) the character # appears where the language has no such symbol, (b) x = (3 + 4; is missing a closing parenthesis, (c) y = z + 1 where z was never declared.
Show answer
(a) Lexical analysis, because no token pattern matches #. (b) Syntax analysis, because the token sequence does not match any production of the grammar. (c) Semantic analysis, because the grammar cannot express declaration rules, and the symbol table lookup for z fails.
Exercise
A lexer produces <id,1> <=> <num,5> <+> <num,7>. What does the parser consume, and what does it produce?
Show answer
The parser consumes this token stream, not the original characters. It checks the stream against the grammar and produces a parse tree (or syntax tree) in which 5 + 7 is grouped under the assignment to the identifier with symbol table entry 1.