Sub topic 5
Building a Lexer and Introducing Context-Free Grammars
Prerequisites and the lexer’s job
This chapter assumes you know regular expressions, finite automata, sets, and basic recursion. A lexical analyzer, or lexer, reads characters and produces tokens. A token is a category and its text, such as ("NUM", "12") or ("ID", "total").
A lexer usually follows this process:
A token rule has a name and a pattern. For example:
| Token | Pattern | Example |
|---|---|---|
| `NUM` | one or more digits | `123` |
| `ID` | letter or underscore, followed by word characters | `count_1` |
| `OP` | one operator character | `+` |
Maximal munch and rule priority
Maximal munch means choosing the longest token that begins at the current position. For input >=, a lexer should choose >= rather than > followed by = if both rules exist.
If two rules match the same longest text, rule priority resolves the tie. Many lexers choose the rule listed first. Therefore, place keywords before the general identifier rule when their text overlaps.
The lexer must also detect gaps. If no rule matches the current character, it should report the character and its position instead of silently skipping it.
import re
TOKEN_SPEC = [
("IF", r"if"),
("ID", r"[A-Za-z_]\w*"),
("NUM", r"\d+"),
("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):
match = MASTER.match(text, pos)
if match is None:
raise SyntaxError(f"bad character {text[pos]!r} at {pos}")
if match.lastgroup != "WS":
yield match.lastgroup, match.group()
pos = match.end()
print(list(tokenize("if total = 12")))Context-free grammars
After lexing, a parser checks whether the token sequence has the required structure. A context-free grammar, or CFG, describes that structure with nonterminals, terminals, productions, and a start symbol.
For simple expressions:
E -> E + T | T
T -> T * F | F
F -> ( E ) | idHere, E, T, and F are nonterminals. +, *, (, ), and id are terminals. A production replaces one nonterminal with a sequence of symbols.
This grammar gives multiplication higher precedence than addition because T groups multiplication inside an expression. The parser consumes the lexer’s tokens and constructs a derivation or parse tree. Later chapters use this grammar to build predictive and shift-reduce parsers.
Exercise
With rules for = and ==, which rule should usually appear first, and why?
Show answer
The == rule should appear first. Both rules can begin at the same position, but maximal munch must select the longer token ==.