Sub topic 1
Where lexing, parsing, and translation fit in a compiler
Prerequisites
This chapter assumes you know regular expressions, finite automata at a basic level, context-free grammars, and tree structures. You should be comfortable reading set notation and recursive definitions.
The compiler front end
A compiler turns source code into machine code in stages. The front end reads the source and checks its structure. The lexical analyzer (lexer) reads characters and produces tokens. The parser consumes those tokens and builds a parse tree that shows how they fit the grammar. Later phases translate that tree into intermediate code.
Tokens, lexemes, and patterns
A token is a category such as NUM or ID. A lexeme is the actual text that matches a token, such as 12 or total. A pattern is the rule that decides which lexemes belong to a token. Patterns are usually written as regular expressions.
Regular expressions and automata
A regular expression like [A-Za-z_]\w* describes identifiers. A finite automaton recognizes the same language. A nondeterministic finite automaton (NFA) can have several moves for one input symbol. A deterministic finite automaton (DFA) has exactly one move, so a lexer can run it quickly. Standard constructions convert a regular expression to an NFA, and the subset construction converts that NFA to a DFA.
Maximal munch and rule priority
When several patterns match at one position, the lexer uses maximal munch: it takes the longest possible lexeme. If two rules match the same longest lexeme, the rule listed first wins. Lexical errors occur when no pattern matches at the current position.
import re
TOKEN_SPEC = [
("NUM", r"\d+"),
("ID", r"[A-Za-z_]\w*"),
("OP", r"[+\-*/()=]"),
("WS", r"\s+"),
]
MASTER = re.compile("|".join(f"(?P<{name}>{pattern})" for name, pattern in TOKEN_SPEC))
def tokenize(text):
pos = 0
while pos < len(text):
m = MASTER.match(text, pos)
if m is None:
raise SyntaxError(f"bad character {text[pos]!r} at position {pos}")
if m.lastgroup != "WS":
yield (m.lastgroup, m.group())
pos = m.end()
print(list(tokenize("x = 12 + y")))
# [('ID', 'x'), ('OP', '='), ('NUM', '12'), ('OP', '+'), ('ID', 'y')]Context-free grammars
A context-free grammar (CFG) has terminals (token names), nonterminals (named categories), productions, and a start symbol. Consider this grammar:
E -> E + E | idA derivation replaces nonterminals step by step until only terminals remain. A leftmost derivation always expands the leftmost nonterminal. A rightmost derivation always expands the rightmost one. For id + id, the leftmost derivation is:
E => E + E => id + E => id + idA parse tree shows the same derivation as a tree. Each internal node is a nonterminal, and its children follow the production used. Because this grammar allows two different parse trees for id + id + id, it is ambiguous. Ambiguity is resolved later by rewriting the grammar.
Exercise
Exercise
The lexer receives the text iffy, and the grammar has a keyword rule for if and an ID rule. Which token does maximal munch produce?
Show answer
It produces ID with the lexeme iffy. Maximal munch takes the longest match, which is the full four-character string, so the keyword rule for if does not apply.