本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
1Lexical Analysis
Type if n<=0 into a compiler and it sees seven characters: i, f, a space, n, <, =, 0. It does not yet know that if is a keyword, that <= is one operator and not two, or that the space mattered only because it kept if away from n: ifn<=0 would have been a single name followed by an operator and a number. The first job of a compiler is to cut the characters into words. This chapter builds the part that does it, twice: once by hand, the way production compilers are usually written, and once from regular expressions, the way a scanner generator does it, and checks that the two agree on thousands of inputs. On the way it meets the rule that decides where a word ends, a token set on which that rule makes the scanner read a quadratic number of characters, and a fix.
The whole of Part I builds one compiler, for a small language called Moor (after the town of Brenmoor), in Rust. Each chapter adds one module and never edits the earlier ones: this chapter’s files are included unchanged by every later one.
1.1 The phases of a compiler
You already know
Compiling a C file runs a preprocessor, a compiler proper, an assembler and a linker, each a separate program with its own input and output (Year 1 volume, From Source Code to a Running Program). A regular expression denotes a set of strings; Thompson’s construction turns it into an automaton with spontaneous transitions, the subset construction makes that automaton deterministic, and Moore’s algorithm minimises it (Year 2 volume, Finite Automata and Regular Expressions and the Limits of Regular Languages).
The compiler proper is itself a pipeline. Each stage reads the previous stage’s output, checks one kind of correctness, and hands on a form of the program that is a little further from the text and a little closer to the machine.
Definition 1.1 (Compiler phases)
A compiler phase is one stage of a compiler: a function from one representation of the program to the next, which may reject the program with an error. The phases that depend on the source language and not on the target machine (cutting into tokens, parsing, checking names and types) form the front end; those that depend on the target machine and not on the source language (choosing instructions, assigning registers, laying out the stack frame) form the back end.
Between them, most compilers have a middle: phases that rewrite an intermediate form belonging to neither the language nor the machine, to make the program faster. The split pays for itself as soon as there are two languages or two machines: front ends and back ends that share one intermediate form make compilers from parts. The figure below follows one Moor statement through the phases this book writes, with the chapter that writes each.
ID and NUM stand for an identifier and a number token). The middle phases work on three-address code, which belongs to neither language; here the optimiser removes a useless copy, and the code generator keeps price, rate and total in registers.Each phase may reject the program, and the kind of error tells which phase found it. The scanner rejects a character that starts no word (# in Moor). The parser rejects words in an impossible order (total = = 3). Semantic analysis rejects a well-formed sentence that means nothing (total = true + 1, or a name declared nowhere). Nothing after it should reject a program that got that far: the back end may be slow or clever, but it must not fail.
Moor is small on purpose: every feature is there because a chapter needs it. The program below is the running example of this Part; the rest of the language is in the chapters that compile it.
// hello.moor -- the running example of Part I
fn square(x: int) -> int {
return x * x;
}
fn main() {
var n = 7;
if n >= 0 && square(n) != 50 { print(square(n)); }
}
if, operators of one and two characters. code/bachelor-3/01-lexical-analysis/listings/hello.moor1.2 Tokens, lexemes and spans
The scanner’s output is a sequence of tokens. The words need care, because three different things are often all called a “token”.
Definition 1.2 (Token, lexeme, token class)
A token class is a set of strings, given by a pattern (in practice a regular expression), that the parser treats alike: identifier, number, the keyword while, the operator <=. A lexeme is one substring of the source that belongs to a token class. A token is the pair of a token class and the information the later phases need about the lexeme: its value for a number, its spelling for an identifier, nothing more for a keyword or an operator.
In var n = 7; the lexemes are var, n, =, 7 and ;; the tokens are the keyword var, an identifier spelled n, the operator =, the number 7 and the semicolon. The parser never sees the spaces. A keyword is a token class of its own, not an identifier with a special spelling: the grammar of the next chapter says “while, then an expression, then a block”, and that is easy only if while arrives as its own kind of token.
Listing 1.2 is Moor’s token type. Each variant of TokenKind is one token class; two of them carry data. A token also carries where it came from.
/// A stretch of the source: byte offsets `start..end`, and the line and
/// column (both from 1) of its first character.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Span {
pub start: usize,
pub end: usize,
pub line: u32,
pub col: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TokenKind {
// keywords
Fn, Var, Array, If, Else, While, Return, True, False, Int, Bool,
// names and literals
Ident(String),
Number(i64),
// operators
Plus, Minus, Star, Slash, Percent,
EqEq, NotEq, Lt, Le, Gt, Ge,
AndAnd, OrOr, Bang, Assign,
// punctuation
LParen, RParen, LBrace, RBrace, LBracket, RBracket,
Comma, Semi, Colon, Arrow,
Eof,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Token {
pub kind: TokenKind,
pub span: Span,
}
Definition 1.3 (Scanner, span)
A scanner (or lexer) is the phase that turns the characters of a source file into a sequence of tokens, dropping white space and comments. The span of a token is where its lexeme lies in the source: its first and past-the-end byte offsets, and the line and column of its first character, both counted from 1.
The span is carried through every later phase, so that a type error found in chapter 4 can still point at a column of the source. Byte offsets let a phase cut the lexeme out of the source in constant time; line and column are for people. They are computed once, as the scanner moves, rather than recomputed from an offset, which would mean counting newlines from the start of the file at every error.
1.3 From regular expressions to a scanner
Every token class of Moor is a regular language. Identifiers are [A-Za-z_][A-Za-z0-9_]*, numbers [0-9]+, each keyword and each operator a fixed string. So the scanner could be generated: write one regular expression per class, build one automaton, run it.
Definition 1.4 (Scanner generator)
A scanner generator is a program that reads an ordered list of rules, each a regular expression with the token class it denotes, and writes a scanner for them: a deterministic automaton stored as a table, and the code that runs it.
The first step is to turn each rule into an automaton. Listing 1.3 is Thompson’s construction over a parsed regular expression (the parser is the first ninety lines of the file, a small recursive descent of the kind the next chapter studies). Each case builds a fragment with one entry and one exit.
/// Thompson's construction: a fragment with one entry and one exit.
pub fn fragment(&mut self, re: &Re) -> (usize, usize) {
if let Re::Cat(a, b) = re {
let (a_in, a_out) = self.fragment(a);
let (b_in, b_out) = self.fragment(b);
self.states[a_out].eps.push(b_in); // concatenation adds no state
return (a_in, b_out);
}
let (s, e) = (self.new_state(), self.new_state());
match re {
Re::Eps => self.states[s].eps.push(e),
Re::Set(ranges) => {
for &(lo, hi) in ranges {
self.states[s].moves.push((lo, hi, e));
}
}
Re::Alt(a, b) => {
for r in [a, b] {
let (i, o) = self.fragment(r);
self.states[s].eps.push(i);
self.states[o].eps.push(e);
}
}
Re::Star(a) | Re::Plus(a) | Re::Opt(a) => {
let (i, o) = self.fragment(a);
self.states[s].eps.push(i);
self.states[o].eps.push(e);
if !matches!(re, Re::Plus(_)) {
self.states[s].eps.push(e); // zero times
}
if !matches!(re, Re::Opt(_)) {
self.states[o].eps.push(i); // once more
}
}
Re::Cat(..) => unreachable!(),
}
(s, e)
}
}
Proposition 1.5 (Size of a Thompson automaton)
For a regular expression with character sets and operators among |, *, +, ?, the fragment of Listing 1.3 has exactly states.
Proof. By induction on the expression. A character set (and the empty word) makes two states. An alternation, a star, a plus or an option adds two new states to the states of its operands. A concatenation adds none: it joins the exit of its left fragment to the entry of its right one by a spontaneous move. So each set and each operator other than concatenation contributes exactly two states. ∎
A scanner has many rules, and must say which one matched. The construction joins them under a new start state.
Method 1.6 (The scanner automaton of a list of rules)
Given rules in order: build a fragment for each; add a start state with a spontaneous move into each fragment’s entry; mark the exit of fragment as accepting for rule . Then apply the subset construction, and label each deterministic state with the smallest rule index among the accepting states it contains, if any.
/// The scanner's NFA: a new start state with an epsilon move into each
/// rule's fragment; the exit of rule k accepts k.
pub fn union(rules: &[&str]) -> Result<Nfa, String> {
let mut nfa = Nfa::default();
nfa.start = nfa.new_state();
for (k, rule) in rules.iter().enumerate() {
let (i, o) = nfa.fragment(&parse(rule)?);
nfa.states[nfa.start].eps.push(i);
nfa.states[o].accept = Some(k);
}
Ok(nfa)
}
The figure below is the automaton for two rules, the keyword if (rule 0) and identifiers [a-z][a-z0-9]* (rule 1). After reading if the automaton is in states 4 and 8 at once: both rules have matched. Labelling by the smallest index makes the keyword win.
if and [a-z][a-z0-9]*, joined under a new start state 0; the state numbers are the order in which Listing 1.3 creates them. Eleven states: one for the union, for if, for the identifier rule.Listing 1.5 is the subset construction with that labelling. It is the Year 2 construction with one line added, the one that computes rule.
/// The subset construction. A DFA state accepts the rule of smallest
/// index among the NFA states it contains: the rule written first wins.
pub fn subset(nfa: &Nfa) -> Dfa {
let mut first = BTreeSet::from([nfa.start]);
closure(nfa, &mut first);
let mut index: HashMap<BTreeSet<usize>, usize> = HashMap::from([(first.clone(), 0)]);
let mut sets = vec![first];
let mut dfa = Dfa { next: Vec::new(), accept: Vec::new(), nfa_sets: Vec::new() };
let mut k = 0;
while k < sets.len() {
let mut row = [DEAD; 128];
for (c, cell) in row.iter_mut().enumerate() {
let mut target = BTreeSet::new();
for &s in &sets[k] {
for &(lo, hi, t) in &nfa.states[s].moves {
if lo as usize <= c && c <= hi as usize {
target.insert(t);
}
}
}
if target.is_empty() {
continue;
}
closure(nfa, &mut target);
let n = sets.len();
*cell = *index.entry(target.clone()).or_insert_with(|| {
sets.push(target);
n
});
}
let rule = sets[k].iter().filter_map(|&s| nfa.states[s].accept).min();
dfa.next.push(row);
dfa.accept.push(rule);
dfa.nfa_sets.push(sets[k].iter().copied().collect());
k += 1;
}
dfa
}
Minimisation needs the same care. Moore’s algorithm starts from a partition into accepting and non-accepting states and refines it. For a scanner the first partition must put two states together only if they accept the same rule: a state that accepts if and one that accepts an identifier recognise the same continuations, but merging them would forget which class was found. The function minimise in the same file starts from that partition; the rest is Moore’s algorithm unchanged.
Listing 1.6 builds the scanner for four rules and prints its minimal table, each row with the characters that leave it, grouped into ranges.
const RULES: [(&str, &str); 4] =
[("if", "if"), ("ident", "[a-z][a-z0-9]*"), ("number", "[0-9]+"), ("space", "[ \\n]+")];
$ rustc --edition 2021 -O -o dfa_table dfa_table.rs && ./dfa_table
NFA 19 states, DFA 7 states, minimal 6
state 0 accepts - \n->1 ' '->1 0-9->2 a-h->3 i->4 j-z->3
state 1 accepts space \n->1 ' '->1
state 2 accepts number 0-9->2
state 3 accepts ident 0-9->3 a-z->3
state 4 accepts ident 0-9->3 a-e->3 f->5 g-z->3
state 5 accepts if 0-9->3 a-z->3
Minimisation merged two states: the one reached after a single letter other than i, and the one reached after two or more characters of an identifier. Both accept an identifier and both stay identifiers on any letter or digit. State 4, reached by i, is different: an f from there leads to the keyword. The figure below draws the same table.
0-9, a-e and g-z, and ␣ is a space.History — Thompson, lex and the first compilers
The first Fortran compiler was delivered for the IBM 704 in 1957; its authors wrote every part of it by hand, including the part that cut a statement into words. Ken Thompson published his construction in June 1968, as a regular-expression search that compiled the expression into machine code for an IBM 7094. Lex, written by Mike Lesk and Eric Schmidt at Bell Laboratories for Unix, turned a table of rules into a deterministic scanner and fixed the two rules this chapter uses: the longest match is preferred, and among matches of the same length the rule given first.
1.4 The longest match
A table answers “which class does this string belong to?”. A scanner has a harder question: where does the next token end? In <= the prefix < is already a token; in iffy the prefix if is already a keyword. Both times the right answer is the longer one.
Definition 1.7 (Maximal munch, priority rule)
Maximal munch (or the longest match) is the rule that the next token is the longest prefix of the remaining input that belongs to some token class. The priority rule breaks the remaining ties: when that longest prefix belongs to several classes, the class of the rule written first wins.
So iffy is an identifier (four characters beat two), if is the keyword (a tie of two characters, broken by the rule order), and <= is one operator. The order of rules matters only for ties: a scanner generator that listed the identifier rule before the keywords would never produce a keyword (exercise 1.7 proves the general statement).
Method 1.8 (Maximal munch with a table)
From the current position, run the automaton one character at a time, remembering the last position at which it was in an accepting state, and its label. Stop when the automaton has no move or the input ends. If an accepting state was seen, the token ends at the remembered position and has the remembered class; continue from there. If none was seen, report an error at the current position.
The automaton may read past the end of the token it returns: on 12:3x with a rule for times [0-9][0-9]:[0-9][0-9] it reads five characters hoping for a time, then goes back to 12. Listing 1.7 is the method, with a counter of the characters read, backtracked ones included.
/// The longest match from `from`: the end and class of the longest token,
/// and how many characters the DFA read to find it (the backtracked ones too).
pub fn longest(d: &Dfa, input: &[u8], from: usize) -> (Option<(usize, usize)>, usize) {
let (mut state, mut pos, mut last) = (0, from, None);
while pos < input.len() && input[pos] < 128 {
state = d.next[state][input[pos] as usize];
if state == DEAD {
break;
}
pos += 1;
if let Some(rule) = d.accept[state] {
last = Some((pos, rule));
}
}
(last, pos - from + usize::from(state == DEAD))
}
/// Maximal munch over the whole input: (class, start, end) for each token,
/// and the total number of characters read; Err(position) where no rule matches.
pub fn scan(d: &Dfa, input: &[u8]) -> Result<(Vec<(usize, usize, usize)>, usize), usize> {
let (mut out, mut pos, mut reads) = (Vec::new(), 0, 0);
while pos < input.len() {
let (m, r) = longest(d, input, pos);
reads += r;
let (end, rule) = m.ok_or(pos)?;
out.push((rule, pos, end));
pos = end;
}
Ok((out, reads))
}
Going back is usually cheap: a scanner reads one or two characters too many and backs up. With some token sets it is not.
Proposition 1.9 (Maximal munch can be quadratic)
With the two rules a and a*b, maximal munch reads characters to cut into tokens. With any token set, it reads at most characters on an input of length , so the first example is the worst case.
Proof. From position the automaton can still reach a*b’s accepting state, so it never stops early: it reads the remaining characters, finds no b, and returns the one-character token a it accepted first. The scan then starts again at . In all it reads characters. For the bound: every scan returns a token of at least one character, so the scans start at distinct positions , and a scan from reads at most the remaining characters, the one on which the automaton has no move included. The total is at most . ∎
Listing 1.8 measures it; the figure after the output shows the first scans of .
fn main() {
let nfa = regex_nfa::union(&["a", "a*b"]).unwrap();
let dfa = scanner_dfa::minimise(&scanner_dfa::subset(&nfa));
println!("{:>6} {:>7} {:>10} {:>10}", "n", "tokens", "reads", "n(n+1)/2");
for n in [1, 2, 5, 10, 100, 1000, 10000] {
let input = vec![b'a'; n];
let (tokens, reads) = scanner_dfa::scan(&dfa, &input).unwrap();
println!("{:>6} {:>7} {:>10} {:>10}", n, tokens.len(), reads, n * (n + 1) / 2);
}
let mut ab = vec![b'a'; 10000];
ab.push(b'b');
let (tokens, reads) = scanner_dfa::scan(&dfa, &ab).unwrap();
println!("a^10000 b: {} token, {} reads", tokens.len(), reads);
}
$ rustc --edition 2021 -O -o munch munch.rs && ./munch
n tokens reads n(n+1)/2
1 1 1 1
2 2 3 3
5 5 15 15
10 10 55 55
100 100 5050 5050
1000 1000 500500 500500
10000 10000 50005000 50005000
a^10000 b: 1 token, 10001 reads
b at the end makes it linear.a and a*b. Each scan reads to the end of the input hoping for a b (black arrow), then backs up to the end of the one-character token it had already accepted (red arrow, shaded token).The cure is to remember failure. A scan that ends at position has visited pairs (state, position) beyond from which no accepting state was ever reached; reaching the same pair again can only fail the same way. Thomas Reps showed in 1998 that a table of these pairs makes maximal munch linear for every token set; exercise 1.12 builds it, and the weekend problem measures it.
Real scanners avoid the question differently. A hand-written scanner knows its token set and reads ahead by a fixed amount: Listing 1.9 reads an identifier or a number in one loop, and settles a two-character operator by looking one character ahead.
pub fn next_token(&mut self) -> Result<Token, LexError> {
self.skip_trivia();
let (start, line, col) = (self.pos, self.line, self.col);
let span = |end| Span { start, end, line, col };
let Some(c) = self.peek(0) else {
return Ok(Token { kind: TokenKind::Eof, span: span(start) });
};
let kind = if c.is_ascii_alphabetic() || c == b'_' {
while matches!(self.peek(0), Some(d) if d.is_ascii_alphanumeric() || d == b'_') {
self.bump();
}
let word = std::str::from_utf8(&self.src[start..self.pos]).unwrap();
keyword(word).unwrap_or_else(|| TokenKind::Ident(word.to_string()))
} else if c.is_ascii_digit() {
while matches!(self.peek(0), Some(d) if d.is_ascii_digit()) {
self.bump();
}
let text = std::str::from_utf8(&self.src[start..self.pos]).unwrap();
match text.parse::<i64>() {
Ok(v) if v <= i32::MAX as i64 => TokenKind::Number(v),
_ => Err(LexError { msg: "number too large".into(), span: span(self.pos) })?,
}
} else {
self.symbol(c).map_err(|msg| LexError { msg, span: span(self.pos) })?
};
Ok(Token { kind, span: span(self.pos) })
}
/// Operators and punctuation: two-character ones first (the longest match).
fn symbol(&mut self, c: u8) -> Result<TokenKind, String> {
use TokenKind::*;
let two = match (c, self.peek(1)) {
(b'=', Some(b'=')) => Some(EqEq),
(b'!', Some(b'=')) => Some(NotEq),
(b'<', Some(b'=')) => Some(Le),
(b'>', Some(b'=')) => Some(Ge),
(b'&', Some(b'&')) => Some(AndAnd),
(b'|', Some(b'|')) => Some(OrOr),
(b'-', Some(b'>')) => Some(Arrow),
_ => None,
};
if let Some(k) = two {
self.bump();
self.bump();
return Ok(k);
}
Keywords are not rules of their own in Listing 1.9. The loop reads the longest identifier, and a lookup in the keyword list (keyword in Listing 1.2) turns while into a keyword and leaves whilst an identifier. That is maximal munch and the priority rule again, decided in a different order; it also keeps the automaton small (exercise 1.9 counts how small).
Remark 1.10 (Two scanners, one test)
The chapter’s tests build a generated scanner from Moor’s 40 rules (eleven keywords first, then identifiers, numbers, twenty-five operators, white space and comments) and compare its tokens with the hand-written scanner’s on 2,000 generated lines. They agree. A hand-written scanner is faster to run and easier to give good error messages; the generated one is the specification it is tested against.
Output 1.3 runs the hand-written scanner on Listing 1.1, printing each token’s line, column, class and lexeme.
$ rustc --edition 2021 -O -o lex_demo lex_demo.rs && ./lex_demo hello.moor
2:1 keyword fn
2:4 ident square
2:10 symbol (
2:11 ident x
2:12 symbol :
2:14 keyword int
2:17 symbol )
2:19 symbol ->
2:22 keyword int
2:26 symbol {
3:5 keyword return
3:12 ident x
3:14 symbol *
3:16 ident x
3:17 symbol ;
4:1 symbol }
8:52 symbol ;
8:54 symbol }
9:1 symbol }
10:1 eof
49 tokens
hello.moor: the comment and the spaces are gone, -> is one token. Some lines are left out.1.5 Errors and their positions
A scanner meets three kinds of error in Moor: a character that starts no token (#, é), a character that starts a token only with a partner it lacks (a single &), and a lexeme the class rejects although the pattern matches (a number beyond ). Each is reported at the span of the offending lexeme, and the report shows the line with a caret under the column.
/// The message under the source line, a caret under the column. Tabs before
/// the column are copied, so the caret lines up whatever the tab width.
pub fn show_error(src: &str, file: &str, e: &LexError) -> String {
let text = src.lines().nth(e.span.line as usize - 1).unwrap_or("");
let pad: String = text
.chars()
.take(e.span.col as usize - 1)
.map(|c| if c == '\t' { '\t' } else { ' ' })
.collect();
format!("{}:{}:{}: error: {}\n {}\n {}^\n", file, e.span.line, e.span.col, e.msg, text, pad)
}
A column counts characters, not bytes, and not screen positions: é is two bytes and one column, a tab is one column and four or eight positions on a screen. Copying the tabs into the caret line is the trick that makes the two agree without knowing the tab width. Line 2 of the file below starts with a tab, which is column 1.
Method 1.11 (Recovery by skipping a character)
After an error, skip the offending character (all its bytes) and scan on, collecting errors in a list; report them all at the end. The tokens produced after an error are kept, so that later phases can still look for errors of their own.
Skipping one character is the simplest recovery that always makes progress, and for a scanner it is usually enough: a stray character rarely confuses what follows. The parser will need something stronger (chapter 2).
fn main() {
let file = std::env::args().nth(1).expect("usage: lex_error FILE");
let src = std::fs::read_to_string(&file).expect("cannot read the file");
let (tokens, errors) = lexer::lex_recover(&src);
for e in &errors {
print!("{}", lexer::show_error(&src, &file, e));
}
println!("{} errors, {} tokens kept", errors.len(), tokens.len());
}
$ rustc --edition 2021 -O -o lex_error lex_error.rs && ./lex_error bad.moor
bad.moor:2:12: error: number too large
var big = 4000000000;
^
bad.moor:3:14: error: expected '&&', found a single '&'
if 1 < 2 & true { print(1); }
^
bad.moor:4:12: error: unexpected character 'é'
var café = 3;
^
3 errors, 28 tokens kept
bad.moor, one per kind; the caret of the first sits under the number although the line starts with a tab.In practice — What the scanner leaves to the parser
A scanner checks only what a regular language can check. It accepts ) ) (, var var, and x = = 1: each lexeme is fine, the order is wrong, and the order is the parser’s business. It cannot match brackets, since balanced brackets are not a regular language (Year 2 volume, the pumping lemma). Where a language has comments that nest, the scanner keeps a counter, which is no longer a finite automaton (exercise 1.11).
1.6 Exercises
Exercise 1.1 ★
Write the token stream that the scanner of this chapter produces for the line while i<=n{i=i+1;}//done, as a list of classes with their lexemes. How many tokens are there, the end-of-file token included?
Solution
Solution of Exercise 1.1.
Thirteen tokens: the keyword while, identifier i, <=, identifier n, {, identifier i, =, identifier i, +, the number 1, ;, }, and the end-of-file token. The missing spaces change nothing, since no two neighbouring lexemes could join into a longer one (n{ is not a token), and the comment //done disappears with the rest of its line.
Exercise 1.2 ★
For each input, say which tokens the scanner returns and which rule decides: iffy, if, if2, <=, <==, 1x, ->-, a--b.
Solution
Solution of Exercise 1.2.
iffy: one identifier, by maximal munch (four characters beat the keyword’s two). if: the keyword, by the priority rule in a generated scanner, by the keyword lookup in the hand-written one. if2: one identifier, by maximal munch. <=: one operator, by maximal munch. <==: <= then =; maximal munch takes the longest token first and never looks for a better cut, so < followed by == is never tried. 1x: the number 1, then the identifier x; a digit cannot continue an identifier’s first character, and the scanner does not object, the parser will. ->-: -> then -. a--b: a, -, -, b, since Moor has no -- operator.
Exercise 1.3 ★
Write a regular expression, in the syntax of Listing 1.3’s parser, for Moor’s comments, from // to the end of the line. Should the newline belong to the comment? How many states does Thompson’s construction give your expression?
Solution
Solution of Exercise 1.3.
//[^\n]*. The newline is better left out: it is white space and ends the line in any case, a comment on the last line of a file with no final newline still matches, and the line counter of the scanner sees every newline as an ordinary character. The expression has three character sets (/, /, [^\n]) and one star, so states by Proposition 1.5; the tests of dfa_test.rs check the count.
Exercise 1.4 ★
How many states does Thompson’s construction, as in Listing 1.3, build for (a|b)*abb? For [0-9]+(\.[0-9]+)?? Check the first against the chapter’s tests.
Solution
Solution of Exercise 1.4.
The first expression has five character sets and two operators, the bar and the star: states. The second has three sets (two digit classes and the dot) and three operators (two + and a ?): 12 states. Both counts are asserted in tests/dfa_test.rs. The parentheses add nothing: they only group.
Exercise 1.5 ★★
Listing 1.13 is a first attempt at a scanner for words and numbers, and Output 1.5 what it prints. Find the bug, explain why the first call hides it, and fix it.
fn words(src: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
for c in src.chars() {
if c.is_ascii_alphanumeric() {
current.push(c);
} else if !current.is_empty() {
out.push(current.clone());
current.clear();
}
}
out
}
fn main() {
println!("{:?}", words("var n = 7;\n"));
println!("{:?}", words("var n = 7"));
}
$ rustc --edition 2021 -O -o words_bug words_bug.rs && ./words_bug
["var", "n", "7"]
["var", "n"]
Solution
Solution of Exercise 1.5.
A word is pushed only when a character that cannot continue it is read. The last word of an input that ends inside a word is never followed by such a character, so it is lost. The first call ends with ; and a newline, which flush 7; the second ends on 7. The fix (exercises/ex5_words_fixed.rs, tested in tests/exercises_test.rs) pushes the word under construction after the loop if it is not empty. The hand-written scanner of the chapter avoids the bug by construction: it reads a whole lexeme in an inner loop that stops at the end of the input as well as at a delimiter.
Exercise 1.6 ★★
Add hexadecimal literals to Moor’s numbers: 0xff and 0XFF are 255. Write a function that reads a number literal at the start of a byte slice and returns its value and length, with an error for 0x alone, for a letter glued to the digits (0x1g, 12ab), and for a value that does not fit. Which values should a hexadecimal literal accept that a decimal one does not, on a 32-bit machine, and why?
Solution
Solution of Exercise 1.6.
exercises/ex6_hex.rs reads an optional 0x or 0X, then the longest run of digits in the radix, and refuses an empty run, a letter, digit or underscore glued to the end (so 0x1g and 12ab are errors rather than two tokens), and a value that does not fit. A decimal literal must fit a positive 32-bit integer, at most ; a hexadecimal literal is accepted up to 0xFFFFFFFF, because programmers write hexadecimal for bit patterns, and 0xFFFFFFFF is the pattern of on a 32-bit machine: a mask with all bits set. The tests check 255, 0xff, 0XFFFFFFFF, 0 and the four errors.
Exercise 1.7 ★★
Prove that the labelling of Method 1.6 is right: for every string , the deterministic state reached on is labelled if and only if matches rule and no rule before it. Deduce that a rule whose language is included in that of an earlier rule never labels any state.
Solution
Solution of Exercise 1.7.
Write for rule ’s Thompson fragment, with entry and exit . Thompson’s construction is correct: is reachable from by a path spelling if and only if . The fragments share no state and the only moves into come from the new start state, by a spontaneous move to ; so is reachable from the start on if and only if . The subset construction reaches, on , the set of all NFA states reachable from the start on . Its label is the smallest with , that is, the smallest with : the state is labelled exactly when matches and no earlier rule. If with , every that matches also matches , so the label of its state is at most and never . This is why the identifier rule must come after the keywords: written first, it would make every keyword unreachable, which the test the_first_rule_wins_a_tie shows on if.
Exercise 1.8 ★★
A line of a Moor file is a tab, then var x = 3 # 4;. At which line and column does the scanner report the error? An editor shows tabs as eight spaces: in which screen column does the # appear? What would a caret line made only of spaces look like there, and why does Listing 1.11 not have that problem?
Solution
Solution of Exercise 1.8.
Line and column: the line’s own number, column 12 (the tab is column 1, var columns 2 to 4, and # is the twelfth character). On a screen with tab stops every eight positions, the tab fills positions 1 to 8, and # lands in position 19. A caret line of eleven spaces and a caret would put the caret at screen position 12, under the space after var, seven positions too far left. Listing 1.11 copies the tab into the caret line, so the caret line expands exactly as the source line does, whatever the tab width.
Exercise 1.9 ★★
Build the minimal scanner automaton (with Listing 1.5 and minimise) for Moor’s identifiers alone, then for the eleven keywords as rules before the identifier rule. How many states does each have? What does this say about treating keywords as a lookup after the identifier has been read?
Solution
Solution of Exercise 1.9.
The identifier rule alone gives a minimal automaton of 2 states: the start, and one accepting state that loops on letters, digits and underscores. With the eleven keywords as rules before it, the minimal automaton has 43 states (tests/dfa_test.rs). The keywords spell 43 characters; their prefix tree shares only i (if, int) and f (fn, false), which leaves 41 states inside the keywords, plus the start and the generic identifier state. The lookup keeps the automaton at 2 states and costs one table lookup per identifier, which a hash table or a perfect hash makes constant. The large automaton is not slower to run (one table step per character either way), but its table is twenty times larger, and every keyword added to the language grows it.
Exercise 1.10 ★★★
Show that for every token set maximal munch reads characters on an input of length , and that the bound is reached only by token sets whose automaton can read arbitrarily far past the end of the token it returns. State that condition precisely in terms of the minimal automaton, and decide it for Moor’s token set and for the rules - and -+>.
Solution
Solution of Exercise 1.10.
A scan from position reads at most the remaining characters, the failing one included, and returns a token of length at least 1, so successive scans start at distinct positions; the total is at most . Call the overshoot of a scan the number of characters read after the end of the token it returns. A scan reads the token’s length plus its overshoot, and the token lengths add up to ; if every overshoot is at most , the total is at most for tokens, which is linear. So a quadratic total needs unbounded overshoot. Overshoot is unbounded exactly when, in the minimal automaton (whose states can all reach an accepting state), some cycle of non-accepting states can be reached from an accepting state through non-accepting states only: following the cycle reads as many characters past the last acceptance as wanted, and without such a cycle the walk past an accepting state is a path without repeated states, of length less than . In Moor’s automaton the only non-accepting states other than the start are those after a single & or |, which only the start leads to; every move out of an accepting state leads to an accepting state (< to <=, / to a comment, a letter to a longer identifier), so the overshoot is exactly the one failing character. For the rules - and -+>, the state after two or more dashes is non-accepting, loops on -, and is reached from the accepting state after one dash; the overshoot is unbounded, and dashes cost reads.
Exercise 1.11 ★★★
Some languages have comments that nest: /* a /* b */ c */ is one comment. Use the Myhill–Nerode theorem (Year 2 volume) to show that the set of nested comments is not regular, so no rule of a scanner generator can describe it. Then write a function that skips a nested comment with a depth counter and returns its length, and test it.
Solution
Solution of Exercise 1.11.
For let and . The word is one nested comment: it opens times, then closes times, and the as keep a * from touching a / in the wrong order. For , the word is not one comment: the depth returns to zero after closings, which ends the comment, and the rest of the word follows it. So the prefixes are pairwise distinguishable (the suffix separates from ), the language has infinitely many Myhill–Nerode classes, and it is not regular. exercises/ex11_nested.rs keeps a depth counter: it adds one at /*, subtracts one at */, returns the length when the depth comes back to zero, and reports an unterminated comment if the input ends first; the counter is the unbounded memory that no finite automaton has. The tests check a flat comment, a nested one, an unterminated one, and an input that does not start with a comment.
Exercise 1.12 ★★★
Implement maximal munch with a table of failed pairs (state, position): after a scan that returns a token ending at , mark every pair visited at a position beyond ; stop a later scan as soon as it reaches a marked pair. Prove that it returns the same tokens as Listing 1.7, that it reads at most characters for an automaton with states, and that on with the rules a and a*b it reads exactly for .
Solution
Solution of Exercise 1.12.
exercises/memo_munch.rs implements it. Same tokens: a pair is marked only after a scan visited it at a position beyond the end of the token that scan returned; since that scan returned , no accepting state was reached after from , and the automaton is deterministic, so any later run from would also reach none. Stopping there loses no acceptance, and the last accepting position found is the one the plain scanner finds. Bound: a scan from that returns a token ending at reads characters up to the token’s end, plus the characters after , each of which either enters a pair that is then marked (it was not marked, or the scan would have stopped), or is the one read that stops the scan. Token lengths add up to ; a pair is marked once, so the marked pairs number at most ; there is one stopping read per token, at most . In all at most . On : the first scan reads all characters and marks the non-accepting state at positions ; every later scan from position reads two characters, the accepting a and one that enters a marked pair; the last scan reads one. That is . The test naive_munch_is_quadratic_and_memo_munch_linear checks it for = 2, 10, 100 and 1,000.
1.7 Weekend problem
Problem 1.1
Weekend problem — The town hall’s timetable reader
Brenmoor’s town hall publishes its opening hours as plain text files. A line looks like Library 09:45-12:30 room 3, a row of dashes separates the days, and an arrow --> points from a place to a time. The town’s programmer writes a scanner for these files with seven rules, in this order: time [0-9][0-9]:[0-9][0-9], number [0-9]+, name [A-Z][a-z]*, word [a-z]+, arrow -+>, dash -, space [␣\n]+. The file exercises/pb_timetable.rs builds this scanner with the chapter’s modules; reason each answer out before checking it.
Part I — Rules and conflicts.
- Write the tokens of
Library 09:45-12:30 room 3, with their classes. - Which rules match a prefix of
09:45? Which token does maximal munch return, and which for0945? - Show that no lexeme matches two rules of this list. What follows for the order of the rules?
- The programmer moves
numberbeforetime. Does any token change? And ifdashmoves beforearrow? - On
12:3x, how many characters does the automaton read before it returns its first token, which token is it, and where is the error reported? - A clerk writes
9:45. What does the scanner do? Propose a change to one rule that accepts it, and say what it costs fornumber.
Part II — The automaton, by hand and by program.
- Count the states of each rule’s Thompson fragment, and of the whole automaton, with Proposition 1.5.
- Follow the subset construction from the start state on the digits: which deterministic states does
09:45visit, and which of them accept? - The construction gives 14 deterministic states and minimisation 13. Which two states merge, and why could no other pair?
- How many of the 13 states accept? Which states accept
number, and why are there more than one? - Why must minimisation start from a partition by class? Give two states of this automaton that a partition into “accepting” and “not accepting” would merge wrongly.
- Two characters are equivalent when every state moves on them to the same place. How many classes of characters does the minimal table have? List them.
- The table stores one 4-byte entry per state and character. How many bytes does it take with 128 columns, and with one column per class plus a 128-byte map from characters to classes?
Part III — What maximal munch costs.
- How many characters does the scanner read on
--->, and how many tokens does it return? - Each day ends with a rule line of dashes. Show that the scanner returns
dashtokens and reads characters. - How many characters does it read on a rule line of 80 dashes? The file has 365 such lines and 2,000 other lines of 30 characters: what share of all reads do the rule lines cause?
- Show that, whatever the input, the
timerule can make the scanner read at most 3 characters past the end of the token it returns, the character that fails included. - Deduce a bound on the reads of a scanner with only the rules
time,number,name,wordandspace, on any input of length . - Rewrite the token set so that no rule line costs more than linear time without a memo table, and say what the parser must then do to recognise an arrow.
Part IV — The memoised scanner.
- Run the memoised scanner of exercise 1.12 by hand on five dashes: list the pairs it marks and the characters each scan reads.
- Prove that on dashes it reads exactly characters.
- How many pairs does it mark on dashes? Compare with the entries its table can hold.
- Check with the program that the two scanners return the same tokens on 500 random lines built from dashes, arrows, times, numbers and names, and that the memoised one never reads more than characters.
- State the result for the 80-dash rule line: characters read by each scanner, and the factor between them.
Solution
Solution of Problem 1.1.
The numbers below are asserted in tests/pb_test.rs.
1. Nine tokens: name Library, space, time 09:45, dash, time 12:30, space, word room, space, number 3.
2. number matches 0 and 09; time matches 09:45. Maximal munch returns the longest, the time. On 0945 the time rule fails at the third character, and the number 0945 (four characters) is returned.
3. Every lexeme of time contains a colon and no other rule’s does; number has only digits; name starts with a capital and word has none; arrow ends with >, which dash and space never contain; dash is the single -, space only blanks. The seven languages are pairwise disjoint, so no two rules ever tie, and the priority rule never decides anything: the order of the rules does not matter.
4. No token changes, for either move, by the answer to question 3.
5. It reads 1, 2, :, 3, and then x, on which it has no move: five characters. The last accepting position was after 12, so it returns the number 12. The next scan starts at the colon, which starts no token: the error is at offset 2, column 3.
6. It returns the number 9, then reports the colon as an error. Making the first digit of time optional,
[0-9][0-9]?:[0-9][0-9]
accepts 9:45. A number is not affected in its tokens, but a one-digit number followed by a colon now makes the scanner read ahead for a time, as two digits already did.
7. time 10 states (five sets), number 4, name 6, word 4, arrow 6 (two sets and a plus), dash 2, space 4: 36, plus the start of the union, 37.
8. From the start, a digit leads to a state accepting number in which time is still possible; a second digit to another such state; the colon to a state where only time is alive, which does not accept; a digit to a second non-accepting state; the last digit to the state accepting time. Five states after the start, three of them accepting: two for number, the last for time.
9. The two name states merge: the one after the capital letter and the one after one or more lower-case letters stand for different NFA states, but both accept name and loop on [a-z]. No other pair can merge: the states of different classes start in different blocks, the three number states differ on what a colon or a digit leads to, and the non-accepting ones differ in how many characters remain before an acceptance.
10. Nine of the 13 states accept: one each for space, dash, name, word, arrow and time, and three for number. The three number states are a number of one digit, of two digits, and of three or more: after two digits a colon can still start a time, after one or three it cannot (and with the rule of question 6, after one it can).
11. Minimisation must never merge two states of different classes, or the scanner would no longer know which class it found. With a first partition into accepting and non-accepting states, the name state and the word state would merge: both accept and both loop on [a-z] and on nothing else, so every word would be returned with one class for both.
12. Eight classes (tests/pb_test.rs): the digits, the colon, the capitals, the lower-case letters, -, >, the space and newline together, and every other character, on which all states have no move.
13. bytes with 128 columns; bytes with eight columns and the map, twelve times less.
14. Four characters, one arrow token: the dashes keep arrow alive, and the > accepts.
15. From position , every dash keeps arrow possible, so the automaton reads to the end of the line; it never sees >, and the last acceptance was dash after one character. It returns one dash and starts again at . Each of the scans returns one dash, and they read characters in all, with no failing read since the line ends.
16. reads for one rule line. The 365 lines cost reads. The other lines hold 60,000 characters and their tokens overshoot by at most a few characters (questions 17 and 18), so they cost at most reads by question 18, and about 60,000 in practice. The rule lines cause about 95 % of the reads ( out of about ), and at least 83 % with the bound, for a third of the characters ( out of ).
17. Past the end of a returned token, only the time rule can still be alive, and only after a token of one or two digits (a number). From two digits it can read a colon and one digit without accepting, then fail on the next character: three characters past the token, as on 12:3x. From one digit, the colon is already a failure: one character. No other path through the time pattern reads further without accepting.
18. With these five rules the overshoot of a scan is at most 3 (question 17; every other rule’s overshoot is the one failing character). A scan reads its token plus at most 3, the tokens add up to characters, and there are at most tokens: at most reads.
19. Replace arrow and dash by dashes -+ and gt >. A rule line becomes one dashes token, read once; the overshoot of every rule is now bounded and the scanner is linear. The parser recognises an arrow as a dashes token followed by a gt token whose span starts where the dashes end, and a separator as a dashes token alone on its line.
20. Write for the state after one dash (accepting) and for the state after two or more (not accepting). The first scan visits , , , , , reads 5, returns the dash ending at 1, and marks to . The scans from 1, 2 and 3 each read 2: they reach , accept, and stop on the marked . The scan from 4 reads 1 and meets the end. Total .
21. The first scan reads ; each scan from positions 1 to reads 2, as in question 20; the scan from reads 1. So .
22. pairs: to , all marked by the first scan, since every later scan’s visited pairs lie at or before the end of its token. The table could hold pairs; the memo is a small fraction of it, and a hash set stores only the marked ones.
23. The test memo_bound_holds_on_mixed_lines builds 500 lines of 40 random pieces (dashes, double dashes, >, times, numbers, a name, a word, spaces, newlines), and checks on every line both scanners accept that they return the same tokens and that the memoised one reads at most characters ().
24. On the 80-dash rule line the plain maximal-munch scanner reads characters and the memoised scanner , a factor of about 13.7; on dashes the factor is , about , and it grows without bound with the length of the line.