Sub topic 6
Building a lexer: maximal munch, rule priority, and lexical errors
This chapter assumes you know regular expressions, NFAs and DFAs, and the idea of a token, a lexeme and a pattern from earlier chapters. Here you turn a set of token patterns into a working scanner and learn the rules that settle conflicts between patterns.
What a lexer must decide
A lexer reads characters and returns tokens one at a time. At each position it must answer two questions.
- Which pattern applies?
- How many characters belong to the lexeme?
Many patterns can match at the same place. In iffy = 3, the keyword pattern if matches the first two characters, and the identifier pattern matches iffy. Two rules settle this.
Maximal munch
Maximal munch (also called the longest-match rule) says the lexer takes the longest prefix of the remaining input that matches any token pattern. Under this rule iffy is one identifier. The input <= is one relational operator, not < followed by =. The input 12.5 is one number if the number pattern allows a fraction.
Rule priority
Sometimes two patterns match the same longest prefix. The input if matches both the keyword pattern and the identifier pattern with length 2. The tie-break is rule priority: the pattern listed first wins. So keyword rules go before the identifier rule. This is the convention in Lex and Flex.
Together the two rules read as follows. Choose the longest match. Among patterns that give that length, choose the earliest one in the specification.
| Input | Candidate matches | Result |
|---|---|---|
| `if` | keyword `if` (2), identifier (2) | keyword, by priority |
| `iffy` | keyword `if` (2), identifier (4) | identifier, by length |
| `<=` | `<` (1), `<=` (2) | `<=`, by length |
| `x2y` | identifier (3) | identifier |
How a DFA lexer implements maximal munch
A lexer built from a DFA does not stop at the first accepting state. It keeps reading while the DFA has a transition, and it remembers the last accepting state it passed and the input position at that time. When the DFA gets stuck, the lexer goes back to the remembered position and emits the token for that accepting state.
The steps are:
- Start in the start state with
last_accept = none. - Read a character and move. If the new state is accepting, record the token class and the position.
- If there is no transition, stop. If
last_acceptis set, emit that token and restart from the recorded position. If it is not set, report a lexical error.
This explains a classic GATE-style case. Take the patterns a, abc and a*b hmm, more simply a, abb, a*b+. For the input aabb, the DFA passes a (accepting for rule 1), then fails to extend abb, but a*b+ matches all of aabb. The longest match is aabb.
Rule priority also fits in the DFA. A DFA state is a set of NFA states. If that set contains accepting states of several rules, the DFA state accepts the rule that comes first in the specification.
Backing up and lookahead
Backing up costs rescanning. Take the patterns ab and abcd, and the input abce. The DFA reads abc, fails on e, and rewinds to after ab. The lexer emits ab, then restarts at c. In the worst case a lexer can rescan characters many times, which makes scanning quadratic in the input length. Real languages are built so that rewinding is short, usually by one or two characters.
Some tokens need lookahead, which is reading ahead without consuming. In Fortran, DO 5 I = 1,25 is a loop, while DO 5 I = 1.25 is an assignment to a variable named DO5I. The lexer cannot decide until it sees , or .. Lex handles this with the trailing-context operator /.
Implementing it in Python
The lexer below follows both rules. Python's | takes the first alternative that matches, not the longest, so the code tries every rule and keeps the longest match. A strict > comparison keeps the earlier rule on ties.
import re
RULES = [
("IF", r"if"),
("ID", r"[A-Za-z_]\w*"),
("NUM", r"\d+(\.\d+)?"),
("LE", r"<="),
("LT", r"<"),
("EQ", r"=="),
("ASSIGN", r"="),
("WS", r"\s+"),
]
COMPILED = [(name, re.compile(pat)) for name, pat in RULES]
def tokenize(text):
pos = 0
while pos < len(text):
best_name, best_end = None, pos
for name, rx in COMPILED:
m = rx.match(text, pos)
if m and m.end() > best_end: # strict > keeps the earlier rule on ties
best_name, best_end = name, m.end()
if best_name is None:
raise SyntaxError(f"lexical error: bad character {text[pos]!r} at position {pos}")
if best_name != "WS":
yield (best_name, text[pos:best_end])
pos = best_end
print(list(tokenize("if iffy <= 12.5")))
# [('IF', 'if'), ('ID', 'iffy'), ('LE', '<='), ('NUM', '12.5')]If ID came before IF in RULES, the input if would become an identifier, because the lengths tie and the earlier rule wins.
Lexical errors
A lexical error happens when no pattern matches a prefix of the remaining input, for example the character @ in a language that does not use it. The lexer in the code above raises an error with the position. A lexer detects few kinds of errors, because it sees only a small window of the program. If fi (x == 1) appears, the lexer returns fi as an identifier and leaves the mistake to a later phase.
Common recovery strategies are:
- Panic mode: delete characters until a valid token starts.
- Delete one character from the remaining input.
- Insert a missing character.
- Replace one character with another.
- Transpose two adjacent characters.
The last four try to find the smallest number of edits, called the minimum distance, that turns the input into a valid lexeme. They are costly, so most compilers use panic mode.
A catch-all rule is another approach. A final rule that matches any single character and returns an error token lets the lexer continue and report many errors in one run. Because it matches only one character, maximal munch never lets it win over a real token.
Common errors
- Putting the identifier rule before the keyword rules, so no keyword is ever recognized.
- Forgetting that
12.5may be one token under maximal munch, which changes how1.followed by.5would be handled. - Assuming the lexer stops at the first accepting state. It must continue until it is stuck.
- Treating a misspelled keyword such as
whielas a lexical error. It is a valid identifier, and the parser reports the problem.
Exercise
A lexer has these rules in order: R1 a, R2 a*b, R3 ab*. Using maximal munch and rule priority, what tokens does it return for the input aabab?
Show answer
At position 0, R1 matches a (1), R2 matches aab (3), and R3 matches a (1). The longest is R2 with aab. From position 3 the input is ab. R1 matches a (1), R2 matches ab (2), and R3 matches ab (2). The longest length is 2, and R2 and R3 tie, so priority gives R2. The tokens are R2 aab and R2 ab.
Exercise
A DFA-based scanner has rules R1 if and R2 [a-z]+. Which rule does the DFA state reached after reading if accept, and why? What does it do on the input ifx?
Show answer
That DFA state contains the accepting NFA states of both R1 and R2, and R1 comes first, so it accepts R1. On ifx the DFA moves on to a state that only R2 accepts. It records R2 at length 3, gets stuck at the end of the input, and emits ifx as R2.