Lexical Analysis and Maximal Munch

Tokenize by tracking the longest accepted prefix and resolve ties without breaking identifier boundaries.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Remember the last accepting state
  2. Priority only resolves equal lengths

Remember the last accepting state

A lexer can combine regular token recognizers into one automaton. From the current input position, advance until no transition remains, remembering the most recent accepting position and token kind. Emit the token ending there and resume from the first unconsumed symbol. Leaving the stream at the failing transition can lose text when the automaton advanced beyond its last accepted prefix. If there was no accepting position, report an invalid token and ensure recovery consumes input.

Priority only resolves equal lengths

An identifier rule accepts both “if” and “iffy”. A keyword rule accepts only “if”. On the longer word, maximal munch chooses the identifier. For exactly “if”, equivalent-length acceptance can prefer the keyword. This keeps prefix keywords from cutting longer identifiers into fragments. Automata-based matching explains possible states. Parser recovery works with the token stream once this boundary is determined.[1][2]

References

  1. Andrew C. Myers, Cornell CS 4120: Compiler Course Notes ↩
  2. LLVM Project, LLVM Language Reference Manual ↩