Token Kinds and Their Source Spellings

A lexer can classify spans into token kinds while keeping their original spellings or parsed values for later stages.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a short expression
  2. Check how tokens compete
  3. Keep semantic type and source text together
  4. Test where token spelling can change meaning

Trace a short expression

Text 12 + 5 can produce numeric token, plus token, and numeric token. The two numeric tokens share a kind and carry different values. See tokenizing text for why a boundary rule matters.

Check how tokens compete

When a language permits several token matches from the same position, its specification needs a selection rule. Longest matching prefixes explain one common convention.[1]

Keep semantic type and source text together

Source count = 007 can contain an identifier token spelling count and an integer token spelling 007, where the numeric value may become seven under the language's rules. Retaining the original spelling and offsets supports diagnostics and faithful rewriting. See byte and line locations.

IDENTIFIER: lexeme "count"
ASSIGN: lexeme "="
INTEGER: lexeme "007", parsed value 7 under the example language

Test where token spelling can change meaning

A language might interpret leading zeros differently or disallow them. Specify the lexical rule before converting. Include an unknown character with an exact expected position.

References

  1. Michael Sipser, Introduction to the Theory of Computation ↩