---
title: "Lexical Analysis"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 1
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 1 — Lexical 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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token) set on which that rule makes the [scanner](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token), 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: $m$ [front ends](#def-b3-lexical-analysis-phases) and $n$ [back ends](#def-b3-lexical-analysis-phases) that share one intermediate form make $m n$ compilers from $m + n$ parts. The figure below follows one Moor statement through the phases this book writes, with the chapter that writes each.

![The phases of the Moor compiler, with what the statement looks like between two of them (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.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lexical-analysis/fig-7ab1127fe3e8.svg)

*The phases of the Moor compiler, with what the statement looks like between two of them (`ID` and `NUM` stand for an identifier and a number [token](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-phases) 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.

```text
// 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)); }
}
```

***Listing 1.1.** The running example: a function, a variable, an `if`, operators of one and two characters. code/bachelor-3/01-lexical-analysis/listings/hello.moor*

## 1.2 Tokens, lexemes and spans

The [scanner](#def-b3-lexical-analysis-scanner)’s output is a sequence of [tokens](#def-b3-lexical-analysis-token). The words need care, because three different things are often all called a “[token](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token) are `var`, `n`, `=`, `7` and `;`; the [tokens](#def-b3-lexical-analysis-token) 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](#def-b3-lexical-analysis-token) 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](#def-b3-lexical-analysis-token).

[Listing 1.2](#lst-b3-lexical-analysis-token) is Moor’s [token](#def-b3-lexical-analysis-token) type. Each variant of `TokenKind` is one [token class](#def-b3-lexical-analysis-token); two of them carry data. A [token](#def-b3-lexical-analysis-token) also carries where it came from.

```rust
/// 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,
}

```

***Listing 1.2.** The [tokens](#def-b3-lexical-analysis-token) of Moor. Frozen: every later chapter includes this file. code/bachelor-3/01-lexical-analysis/listings/token.rs*

**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](#def-b3-lexical-analysis-token), dropping white space and comments. The *span* of a [token](#def-b3-lexical-analysis-token) is where its [lexeme](#def-b3-lexical-analysis-token) 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](#def-b3-lexical-analysis-scanner) 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](#def-b3-lexical-analysis-token) out of the source in constant time; line and column are for people. They are computed once, as the [scanner](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token) 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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token) it denotes, and writes a [scanner](#def-b3-lexical-analysis-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](#lst-b3-lexical-analysis-thompson) 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.

```rust

    /// 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)
    }
}
```

***Listing 1.3.** Thompson’s construction. Concatenation links two fragments with a spontaneous move; every other case adds two states. code/bachelor-3/01-lexical-analysis/listings/regex_nfa.rs*

**Proposition 1.5 (Size of a Thompson automaton).**

For a regular expression with $s$ character sets and $o$ operators among `|`, `*`, `+`, `?`, the fragment of [Listing 1.3](#lst-b3-lexical-analysis-thompson) has exactly $2(s + o)$ 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](#def-b3-lexical-analysis-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 $r_0, r_1, \dots, r_{k-1}$ 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 $i$ as accepting for rule $i$. Then apply the subset construction, and label each deterministic state with the *smallest* rule index among the accepting states it contains, if any.

```rust
/// 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)
}
```

***Listing 1.4.** The union of the rules, with a label on each exit. code/bachelor-3/01-lexical-analysis/listings/regex_nfa.rs*

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.

![Thompson’s automaton for the rules if and (a-z)(a-z0-9)*, joined under a new start state 0; the state numbers are the order in which creates them. Eleven states: one for the union, 2 × 2 for if, 2 × 3 for the identifier rule.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lexical-analysis/fig-1880fba058a3.svg)

*Thompson’s automaton for the rules `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](#lst-b3-lexical-analysis-thompson) creates them. Eleven states: one for the union, $2 \times 2$ for `if`, $2 \times 3$ for the identifier rule.*

[Listing 1.5](#lst-b3-lexical-analysis-subset) is the subset construction with that labelling. It is the Year 2 construction with one line added, the one that computes `rule`.

```rust
/// 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
}
```

***Listing 1.5.** The subset construction over the 128 ASCII characters; a state’s label is the first rule it accepts. code/bachelor-3/01-lexical-analysis/listings/scanner_dfa.rs*

Minimisation needs the same care. Moore’s algorithm starts from a partition into accepting and non-accepting states and refines it. For a [scanner](#def-b3-lexical-analysis-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](#lst-b3-lexical-analysis-table) builds the [scanner](#def-b3-lexical-analysis-scanner) for four rules and prints its minimal table, each row with the characters that leave it, grouped into ranges.

```rust
const RULES: [(&str, &str); 4] =
    [("if", "if"), ("ident", "[a-z][a-z0-9]*"), ("number", "[0-9]+"), ("space", "[ \\n]+")];
```

***Listing 1.6.** The four rules of the table (the rest of the file prints it). code/bachelor-3/01-lexical-analysis/listings/dfa_table.rs*

```
$ 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
```

***Output 1.1.** The [scanner](#def-b3-lexical-analysis-scanner) DFA of the four rules: 19 NFA states, 7 subset states, 6 after minimisation.*

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.

![The minimal scanner automaton of . Every accepting state is labelled with its token class; “other” on the edge from 4 is 0-9, a-e and g-z, and ␣ is a space.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lexical-analysis/fig-251b6c9aed15.svg)

*The minimal [scanner](#def-b3-lexical-analysis-scanner) automaton of [Output 1.1](#out-b3-lexical-analysis-table). Every accepting state is labelled with its [token class](#def-b3-lexical-analysis-token); “other” on the edge from 4 is `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](#def-b3-lexical-analysis-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.

![An IBM 704 at a research laboratory, March 1957: the console in the middle, the open wiring cabinet on the left, a card reader in front.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lexical-analysis/img-ee34e3f27002.jpg)

*An IBM 704 at a research laboratory, March 1957: the console in the middle, the open wiring cabinet on the left, a card reader in front.*

## 1.4 The longest match

A table answers “which class does this string belong to?”. A [scanner](#def-b3-lexical-analysis-scanner) has a harder question: where does the next [token](#def-b3-lexical-analysis-token) *end*? In `<=` the prefix `<` is already a [token](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token) is the longest prefix of the remaining input that belongs to some [token class](#def-b3-lexical-analysis-token). 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](#def-b3-lexical-analysis-generator) that listed the identifier rule before the keywords would never produce a keyword (exercise [1.7](#exo-b3-lexical-analysis-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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-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](#lst-b3-lexical-analysis-longest) is the method, with a counter of the characters read, backtracked ones included.

```rust
/// 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))
}
```

***Listing 1.7.** [Maximal munch](#def-b3-lexical-analysis-munch): the longest match from one position, and the scan of a whole input. code/bachelor-3/01-lexical-analysis/listings/scanner_dfa.rs*

Going back is usually cheap: a [scanner](#def-b3-lexical-analysis-scanner) reads one or two characters too many and backs up. With some [token](#def-b3-lexical-analysis-token) sets it is not.

**Proposition 1.9 (Maximal munch can be quadratic).**

With the two rules `a` and `a*b`, [maximal munch](#def-b3-lexical-analysis-munch) reads $n(n+1)/2$ characters to cut $a^n$ into $n$ [tokens](#def-b3-lexical-analysis-token). With any [token](#def-b3-lexical-analysis-token) set, it reads at most $n(n+1)/2$ characters on an input of length $n$, so the first example is the worst case.

**Proof.** From position $i$ the automaton can still reach `a*b`’s accepting state, so it never stops early: it reads the $n - i$ remaining characters, finds no `b`, and returns the one-character [token](#def-b3-lexical-analysis-token) `a` it accepted first. The scan then starts again at $i + 1$. In all it reads $n + (n-1) + \dots + 1 = n(n+1)/2$ characters. For the bound: every scan returns a [token](#def-b3-lexical-analysis-token) of at least one character, so the scans start at distinct positions $i$, and a scan from $i$ reads at most the $n - i$ remaining characters, the one on which the automaton has no move included. The total is at most $\sum_{i=0}^{n-1}(n - i) = n(n+1)/2$. ∎

[Listing 1.8](#lst-b3-lexical-analysis-munch) measures it; the figure after the output shows the first scans of $a^4$.

```rust
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);
}
```

***Listing 1.8.** Counting the characters [maximal munch](#def-b3-lexical-analysis-munch) reads on $a^n$. code/bachelor-3/01-lexical-analysis/listings/munch.rs*

```
$ 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
```

***Output 1.2.** Exactly $n(n+1)/2$ characters read for $a^n$; one `b` at the end makes it linear.*

![Maximal munch on a4 with the rules 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).](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-lexical-analysis/fig-e67c2b15e622.svg)

*[Maximal munch](#def-b3-lexical-analysis-munch) on $a^4$ with the rules `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](#def-b3-lexical-analysis-token) it had already accepted (red arrow, shaded [token](#def-b3-lexical-analysis-token)).*

The cure is to remember failure. A scan that ends at position $e$ has visited pairs (state, position) beyond $e$ 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](#def-b3-lexical-analysis-munch) linear for every [token](#def-b3-lexical-analysis-token) set; exercise [1.12](#exo-b3-lexical-analysis-12) builds it, and the weekend problem measures it.

Real [scanners](#def-b3-lexical-analysis-scanner) avoid the question differently. A hand-written [scanner](#def-b3-lexical-analysis-scanner) knows its [token](#def-b3-lexical-analysis-token) set and reads ahead by a fixed amount: [Listing 1.9](#lst-b3-lexical-analysis-next) reads an identifier or a number in one loop, and settles a two-character operator by looking one character ahead.

```rust
    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) })
    }
```

***Listing 1.9.** The hand-written [scanner](#def-b3-lexical-analysis-scanner)’s main function: an identifier or keyword, a number, or a symbol. code/bachelor-3/01-lexical-analysis/listings/lexer.rs*

```rust
    /// 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);
        }
```

***Listing 1.10.** Symbols: the two-character operators are tried first, which is the longest match for this [token](#def-b3-lexical-analysis-token) set. code/bachelor-3/01-lexical-analysis/listings/lexer.rs*

Keywords are not rules of their own in [Listing 1.9](#lst-b3-lexical-analysis-next). The loop reads the longest identifier, and a lookup in the keyword list (`keyword` in [Listing 1.2](#lst-b3-lexical-analysis-token)) turns `while` into a keyword and leaves `whilst` an identifier. That is [maximal munch](#def-b3-lexical-analysis-munch) and the [priority rule](#def-b3-lexical-analysis-munch) again, decided in a different order; it also keeps the automaton small (exercise [1.9](#exo-b3-lexical-analysis-9) counts how small).

**Remark 1.10 (Two scanners, one test).**

The chapter’s tests build a generated [scanner](#def-b3-lexical-analysis-scanner) from Moor’s 40 rules (eleven keywords first, then identifiers, numbers, twenty-five operators, white space and comments) and compare its [tokens](#def-b3-lexical-analysis-token) with the hand-written [scanner](#def-b3-lexical-analysis-scanner)’s on 2,000 generated lines. They agree. A hand-written [scanner](#def-b3-lexical-analysis-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](#out-b3-lexical-analysis-demo) runs the hand-written [scanner](#def-b3-lexical-analysis-scanner) on [Listing 1.1](#lst-b3-lexical-analysis-hello), printing each [token](#def-b3-lexical-analysis-token)’s line, column, class and [lexeme](#def-b3-lexical-analysis-token).

```
$ 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
```

***Output 1.3.** The [token](#def-b3-lexical-analysis-token) stream of `hello.moor`: the comment and the spaces are gone, `->` is one [token](#def-b3-lexical-analysis-token). Some lines are left out.*

## 1.5 Errors and their positions

A [scanner](#def-b3-lexical-analysis-scanner) meets three kinds of error in Moor: a character that starts no [token](#def-b3-lexical-analysis-token) (`#`, `é`), a character that starts a [token](#def-b3-lexical-analysis-token) only with a partner it lacks (a single `&`), and a [lexeme](#def-b3-lexical-analysis-token) the class rejects although the pattern matches (a number beyond $2^{31} - 1$). Each is reported at the [span](#def-b3-lexical-analysis-scanner) of the offending [lexeme](#def-b3-lexical-analysis-token), and the report shows the line with a caret under the column.

```rust
/// 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)
}
```

***Listing 1.11.** The message, the line, and a caret. Tabs before the column are copied, so the caret lines up whatever width the reader’s terminal gives a tab. code/bachelor-3/01-lexical-analysis/listings/lexer.rs*

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](#def-b3-lexical-analysis-token) 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](#def-b3-lexical-analysis-scanner) it is usually enough: a stray character rarely confuses what follows. The parser will need something stronger (chapter 2).

```rust
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());
}
```

***Listing 1.12.** Scanning with recovery, then showing every error. code/bachelor-3/01-lexical-analysis/listings/lex_error.rs*

```
$ 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
```

***Output 1.4.** Three errors in `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](#def-b3-lexical-analysis-scanner) checks only what a regular language can check. It accepts `) ) (`, `var var`, and `x = = 1`: each [lexeme](#def-b3-lexical-analysis-token) 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](#def-b3-lexical-analysis-scanner) keeps a counter, which is no longer a finite automaton (exercise [1.11](#exo-b3-lexical-analysis-11)).

## 1.6 Exercises

**Exercise 1.1 ★.**

Write the [token](#def-b3-lexical-analysis-token) stream that the [scanner](#def-b3-lexical-analysis-scanner) of this chapter produces for the line `while i<=n{i=i+1;}//done`, as a list of classes with their [lexemes](#def-b3-lexical-analysis-token). How many [tokens](#def-b3-lexical-analysis-token) are there, the end-of-file [token](#def-b3-lexical-analysis-token) included?

**Solution of Exercise 1.1.**

Thirteen [tokens](#def-b3-lexical-analysis-token): the keyword `while`, identifier `i`, `<=`, identifier `n`, `{`, identifier `i`, `=`, identifier `i`, `+`, the number 1, `;`, `}`, and the end-of-file [token](#def-b3-lexical-analysis-token). The missing spaces change nothing, since no two neighbouring [lexemes](#def-b3-lexical-analysis-token) could join into a longer one (`n{` is not a [token](#def-b3-lexical-analysis-token)), and the comment `//done` disappears with the rest of its line.

**Exercise 1.2 ★.**

For each input, say which [tokens](#def-b3-lexical-analysis-token) the [scanner](#def-b3-lexical-analysis-scanner) returns and which rule decides: `iffy`, `if`, `if2`, `<=`, `<==`, `1x`, `->-`, `a--b`.

**Solution of Exercise 1.2.**

`iffy`: one identifier, by [maximal munch](#def-b3-lexical-analysis-munch) (four characters beat the keyword’s two). `if`: the keyword, by the [priority rule](#def-b3-lexical-analysis-munch) in a generated [scanner](#def-b3-lexical-analysis-scanner), by the keyword lookup in the hand-written one. `if2`: one identifier, by [maximal munch](#def-b3-lexical-analysis-munch). `<=`: one operator, by [maximal munch](#def-b3-lexical-analysis-munch). `<==`: `<=` then `=`; [maximal munch](#def-b3-lexical-analysis-munch) takes the longest [token](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-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](#lst-b3-lexical-analysis-thompson)’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 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](#def-b3-lexical-analysis-scanner) sees every newline as an ordinary character. The expression has three character sets (`/`, `/`, `[^\n]`) and one star, so $2(3 + 1) = 8$ states by [Proposition 1.5](#prop-b3-lexical-analysis-thompson-size); the tests of `dfa_test.rs` check the count.

**Exercise 1.4 ★.**

How many states does Thompson’s construction, as in [Listing 1.3](#lst-b3-lexical-analysis-thompson), build for `(a|b)*abb`? For `[0-9]+(\.[0-9]+)?`? Check the first against the chapter’s tests.

**Solution of Exercise 1.4.**

The first expression has five character sets and two operators, the bar and the star: $2 \times 7 = 14$ 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](#lst-b3-lexical-analysis-wordsbug) is a first attempt at a [scanner](#def-b3-lexical-analysis-scanner) for words and numbers, and [Output 1.5](#out-b3-lexical-analysis-wordsbug) what it prints. Find the bug, explain why the first call hides it, and fix it.

```rust
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"));
}
```

***Listing 1.13.** A [scanner](#def-b3-lexical-analysis-scanner) with a bug. code/bachelor-3/01-lexical-analysis/listings/words_bug.rs*

```
$ rustc --edition 2021 -O -o words_bug words_bug.rs && ./words_bug
["var", "n", "7"]
["var", "n"]
```

***Output 1.5.** The same line, with and without its last two characters.*

**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](#def-b3-lexical-analysis-scanner) of the chapter avoids the bug by construction: it reads a whole [lexeme](#def-b3-lexical-analysis-token) 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 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](#def-b3-lexical-analysis-token)), and a value that does not fit. A decimal literal must fit a positive 32-bit integer, at most $2^{31} - 1$; a hexadecimal literal is accepted up to `0xFFFFFFFF`, because programmers write hexadecimal for bit patterns, and `0xFFFFFFFF` is the pattern of $-1$ 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](#met-b3-lexical-analysis-union) is right: for every string $w$, the deterministic state reached on $w$ is labelled $i$ if and only if $w$ matches rule $i$ and no rule before it. Deduce that a rule $r_j$ whose language is included in that of an earlier rule never labels any state.

**Solution of Exercise 1.7.**

Write $N_i$ for rule $i$’s Thompson fragment, with entry $s_i$ and exit $e_i$. Thompson’s construction is correct: $e_i$ is reachable from $s_i$ by a path spelling $w$ if and only if $w \in L(r_i)$. The fragments share no state and the only moves into $N_i$ come from the new start state, by a spontaneous move to $s_i$; so $e_i$ is reachable from the start on $w$ if and only if $w \in L(r_i)$. The subset construction reaches, on $w$, the set $S(w)$ of all NFA states reachable from the start on $w$. Its label is the smallest $i$ with $e_i \in S(w)$, that is, the smallest $i$ with $w \in L(r_i)$: the state is labelled $i$ exactly when $w$ matches $r_i$ and no earlier rule. If $L(r_j) \subseteq L(r_i)$ with $i < j$, every $w$ that matches $r_j$ also matches $r_i$, so the label of its state is at most $i$ and never $j$. 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](#def-b3-lexical-analysis-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](#lst-b3-lexical-analysis-show) not have that problem?

**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](#lst-b3-lexical-analysis-show) 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](#def-b3-lexical-analysis-scanner) automaton (with [Listing 1.5](#lst-b3-lexical-analysis-subset) 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 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](#def-b3-lexical-analysis-token) set [maximal munch](#def-b3-lexical-analysis-munch) reads $O(n^2)$ characters on an input of length $n$, and that the bound is reached only by [token](#def-b3-lexical-analysis-token) sets whose automaton can read arbitrarily far past the end of the [token](#def-b3-lexical-analysis-token) it returns. State that condition precisely in terms of the minimal automaton, and decide it for Moor’s [token](#def-b3-lexical-analysis-token) set and for the rules `-` and `-+>`.

**Solution of Exercise 1.10.**

A scan from position $i$ reads at most the $n - i$ remaining characters, the failing one included, and returns a [token](#def-b3-lexical-analysis-token) of length at least 1, so successive scans start at distinct positions; the total is at most $\sum_{i}(n - i) = n(n+1)/2 = O(n^2)$. Call the *overshoot* of a scan the number of characters read after the end of the [token](#def-b3-lexical-analysis-token) it returns. A scan reads the [token](#def-b3-lexical-analysis-token)’s length plus its overshoot, and the [token](#def-b3-lexical-analysis-token) lengths add up to $n$; if every overshoot is at most $k$, the total is at most $n + k t \le (k + 1)n$ for $t \le n$ [tokens](#def-b3-lexical-analysis-token), 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 $|Q|$. 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 $n$ dashes cost $n(n+1)/2$ 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](#def-b3-lexical-analysis-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 of Exercise 1.11.**

For $k \ge 1$ let $u_k = (\texttt{/*a})^k$ and $v_k = (\texttt{a*/})^k$. The word $u_k v_k$ is one nested comment: it opens $k$ times, then closes $k$ times, and the `a`s keep a `*` from touching a `/` in the wrong order. For $j < k$, the word $u_j v_k$ is not one comment: the depth returns to zero after $j$ closings, which ends the comment, and the rest of the word follows it. So the prefixes $u_1, u_2, \dots$ are pairwise distinguishable (the suffix $v_k$ separates $u_k$ from $u_j$), 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](#def-b3-lexical-analysis-munch) with a table of failed pairs (state, position): after a scan that returns a [token](#def-b3-lexical-analysis-token) ending at $e$, mark every pair visited at a position beyond $e$; stop a later scan as soon as it reaches a marked pair. Prove that it returns the same [tokens](#def-b3-lexical-analysis-token) as [Listing 1.7](#lst-b3-lexical-analysis-longest), that it reads at most $(|Q| + 2)\,n$ characters for an automaton with $|Q|$ states, and that on $a^n$ with the rules `a` and `a*b` it reads exactly $3n - 3$ for $n \ge 2$.

**Solution of Exercise 1.12.**

`exercises/memo_munch.rs` implements it. *Same [tokens](#def-b3-lexical-analysis-token)*: a pair $(q, p)$ is marked only after a scan visited it at a position $p$ beyond the end $e$ of the [token](#def-b3-lexical-analysis-token) that scan returned; since that scan returned $e$, no accepting state was reached after $p$ from $(q, p)$, and the automaton is deterministic, so any later run from $(q, p)$ would also reach none. Stopping there loses no acceptance, and the last accepting position found is the one the plain [scanner](#def-b3-lexical-analysis-scanner) finds. *Bound*: a scan from $s$ that returns a [token](#def-b3-lexical-analysis-token) ending at $e$ reads $e - s$ characters up to the [token](#def-b3-lexical-analysis-token)’s end, plus the characters after $e$, 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](#def-b3-lexical-analysis-token) lengths add up to $n$; a pair is marked once, so the marked pairs number at most $|Q|n$; there is one stopping read per [token](#def-b3-lexical-analysis-token), at most $n$. In all at most $(|Q| + 2)n$. *On $a^n$*: the first scan reads all $n$ characters and marks the non-accepting state at positions $2, \dots, n$; every later scan from position $i \le n - 2$ reads two characters, the accepting `a` and one that enters a marked pair; the last scan reads one. That is $n + 2(n - 2) + 1 = 3n - 3$. The test `naive_munch_is_quadratic_and_memo_munch_linear` checks it for $n$ = 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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-scanner) with the chapter’s modules; reason each answer out before checking it.

**Part I — Rules and conflicts.**

1. Write the [tokens](#def-b3-lexical-analysis-token) of `Library 09:45-12:30 room 3` , with their classes.
2. Which rules match a prefix of `09:45` ? Which [token](#def-b3-lexical-analysis-token) does [maximal munch](#def-b3-lexical-analysis-munch) return, and which for `0945` ?
3. Show that no [lexeme](#def-b3-lexical-analysis-token) matches two rules of this list. What follows for the order of the rules?
4. The programmer moves `number` before `time` . Does any [token](#def-b3-lexical-analysis-token) change? And if `dash` moves before `arrow` ?
5. On `12:3x` , how many characters does the automaton read before it returns its first [token](#def-b3-lexical-analysis-token) , which [token](#def-b3-lexical-analysis-token) is it, and where is the error reported?
6. A clerk writes `9:45` . What does the [scanner](#def-b3-lexical-analysis-scanner) do? Propose a change to one rule that accepts it, and say what it costs for `number` .

**Part II — The automaton, by hand and by program.**

7. Count the states of each rule’s Thompson fragment, and of the whole automaton, with [Proposition 1.5](#prop-b3-lexical-analysis-thompson-size) .
8. Follow the subset construction from the start state on the digits: which deterministic states does `09:45` visit, and which of them accept?
9. The construction gives 14 deterministic states and minimisation 13. Which two states merge, and why could no other pair?
10. How many of the 13 states accept? Which states accept `number` , and why are there more than one?
11. 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.
12. 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.
13. 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.**

14. How many characters does the [scanner](#def-b3-lexical-analysis-scanner) read on `--->` , and how many [tokens](#def-b3-lexical-analysis-token) does it return?
15. Each day ends with a rule line of $n$ dashes. Show that the [scanner](#def-b3-lexical-analysis-scanner) returns $n$ `dash` [tokens](#def-b3-lexical-analysis-token) and reads $n(n+1)/2$ characters.
16. 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?
17. Show that, whatever the input, the `time` rule can make the [scanner](#def-b3-lexical-analysis-scanner) read at most 3 characters past the end of the [token](#def-b3-lexical-analysis-token) it returns, the character that fails included.
18. Deduce a bound on the reads of a [scanner](#def-b3-lexical-analysis-scanner) with only the rules `time` , `number` , `name` , `word` and `space` , on any input of length $n$ .
19. Rewrite the [token](#def-b3-lexical-analysis-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.**

20. Run the memoised [scanner](#def-b3-lexical-analysis-scanner) of exercise [1.12](#exo-b3-lexical-analysis-12) by hand on five dashes: list the pairs it marks and the characters each scan reads.
21. Prove that on $n \ge 2$ dashes it reads exactly $3n - 3$ characters.
22. How many pairs does it mark on $n$ dashes? Compare with the $13n$ entries its table can hold.
23. Check with the program that the two [scanners](#def-b3-lexical-analysis-scanner) return the same [tokens](#def-b3-lexical-analysis-token) on 500 random lines built from dashes, arrows, times, numbers and names, and that the memoised one never reads more than $(|Q| + 2)n$ characters.
24. State the result for the 80-dash rule line: characters read by each [scanner](#def-b3-lexical-analysis-scanner) , and the factor between them.

**Solution of Problem 1.1.**

The numbers below are asserted in `tests/pb_test.rs`.

**1.** Nine [tokens](#def-b3-lexical-analysis-token): 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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token) 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](#def-b3-lexical-analysis-munch) never decides anything: the order of the rules does not matter.

**4.** No [token](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token), but a one-digit number followed by a colon now makes the [scanner](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-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.** $13 \times 128 \times 4 = 6{,}656$ bytes with 128 columns; $13 \times 8 \times 4 + 128 = 544$ bytes with eight columns and the map, twelve times less.

**14.** Four characters, one `arrow` [token](#def-b3-lexical-analysis-token): the dashes keep `arrow` alive, and the `>` accepts.

**15.** From position $i$, 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 $i + 1$. Each of the $n$ scans returns one dash, and they read $n + (n-1) + \dots + 1 = n(n+1)/2$ characters in all, with no failing read since the line ends.

**16.** $80 \times 81 / 2 = 3{,}240$ reads for one rule line. The 365 lines cost $1{,}182{,}600$ reads. The other lines hold 60,000 characters and their [tokens](#def-b3-lexical-analysis-token) overshoot by at most a few characters (questions 17 and 18), so they cost at most $4 \times 60{,}000 = 240{,}000$ reads by question 18, and about 60,000 in practice. The rule lines cause about 95 % of the reads ($1{,}182{,}600$ out of about $1{,}242{,}600$), and at least 83 % with the bound, for a third of the characters ($29{,}200$ out of $89{,}200$).

**17.** Past the end of a returned [token](#def-b3-lexical-analysis-token), only the `time` rule can still be alive, and only after a [token](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-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](#def-b3-lexical-analysis-token) plus at most 3, the [tokens](#def-b3-lexical-analysis-token) add up to $n$ characters, and there are at most $n$ [tokens](#def-b3-lexical-analysis-token): at most $n + 3n = 4n$ reads.

**19.** Replace `arrow` and `dash` by `dashes` `-+` and `gt` `>`. A rule line becomes one `dashes` [token](#def-b3-lexical-analysis-token), read once; the overshoot of every rule is now bounded and the [scanner](#def-b3-lexical-analysis-scanner) is linear. The parser recognises an arrow as a `dashes` [token](#def-b3-lexical-analysis-token) followed by a `gt` [token](#def-b3-lexical-analysis-token) whose [span](#def-b3-lexical-analysis-scanner) starts where the dashes end, and a separator as a `dashes` [token](#def-b3-lexical-analysis-token) alone on its line.

**20.** Write $D$ for the state after one dash (accepting) and $A$ for the state after two or more (not accepting). The first scan visits $(D,1)$, $(A,2)$, $(A,3)$, $(A,4)$, $(A,5)$, reads 5, returns the dash ending at 1, and marks $(A,2)$ to $(A,5)$. The scans from 1, 2 and 3 each read 2: they reach $(D, i+1)$, accept, and stop on the marked $(A, i+2)$. The scan from 4 reads 1 and meets the end. Total $5 + 2 + 2 + 2 + 1 = 12$.

**21.** The first scan reads $n$; each scan from positions 1 to $n - 2$ reads 2, as in question 20; the scan from $n - 1$ reads 1. So $n + 2(n - 2) + 1 = 3n - 3$.

**22.** $n - 1$ pairs: $(A, 2)$ to $(A, n)$, all marked by the first scan, since every later scan’s visited pairs lie at or before the end of its [token](#def-b3-lexical-analysis-token). The table could hold $13n$ 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](#def-b3-lexical-analysis-scanner) accept that they return the same [tokens](#def-b3-lexical-analysis-token) and that the memoised one reads at most $15n$ characters ($|Q| + 2 = 15$).

**24.** On the 80-dash rule line the plain maximal-munch [scanner](#def-b3-lexical-analysis-scanner) reads $n(n+1)/2 = 3{,}240$ characters and the memoised [scanner](#def-b3-lexical-analysis-scanner) $3n - 3 = 237$, a factor of about 13.7; on $n$ dashes the factor is $n(n+1)/(6(n-1))$, about $(n+1)/6$, and it grows without bound with the length of the line.
