Lexical Analysis
Turning characters into tokens — token types, lexemes, regular expressions, finite automata (NFA to DFA), maximal munch, handling whitespace, comments and keywords, and writing a hand-coded lexer.
The lexer (scanner, tokenizer) is the first phase of a compiler. It reads raw characters and groups them into tokens — the "words" of the language — discarding whitespace and comments. The parser then works on tokens instead of characters, which is far simpler.
Source: if (count >= 10) return "big"; // check
Tokens: KW_IF LPAREN IDENT("count") GE INT(10) RPAREN
KW_RETURN STRING("big") SEMI EOF| Term | Meaning | Example |
|---|---|---|
| Token type | Category | IDENT, INT, GE, KW_IF |
| Lexeme | The actual characters | count, 10, >= |
| Pattern | Rule describing the lexemes of a type | [a-zA-Z_][a-zA-Z0-9_]* |
| Token | Type + lexeme/value + source position | IDENT("count") @ 1:5 |
Tokens carry line and column information so later phases can report errors precisely.
Specifying tokens with regular expressions
Each token type is described by a regular expression:
| Token | Regular expression |
|---|---|
| Identifier | [A-Za-z_][A-Za-z0-9_]* |
| Integer | [0-9]+ |
| Float | [0-9]+\.[0-9]+([eE][+-]?[0-9]+)? |
| String | "([^"\\]|\\.)*" |
| Whitespace (skipped) | [ \t\n\r]+ |
| Line comment (skipped) | //[^\n]* |
Regular languages are exactly what finite automata recognise (Automata), which is why lexing is fast: linear time in the input length.
From regex to DFA
Lexer generators (lex, flex, re2c, ANTLR's lexer) compile the token regexes into a single deterministic finite automaton (DFA):
- Thompson's construction: each regex → an NFA (with ε-transitions).
- Combine all NFAs with a new start state.
- Subset construction: NFA → DFA (each DFA state is a set of NFA states).
- Minimise the DFA (Hopcroft's algorithm).
- Emit a transition table or a
switch-based state machine.
A DFA for identifiers and integers. The accepting states (highlighted) emit a token when no transition matches the next character:
Rules that resolve ambiguity
- Maximal munch (longest match): keep consuming while the input still matches some token;
>=is one token, not>then=;iffyis an identifier, notif+fy. - Priority: if two patterns match the same longest lexeme, the earlier rule wins. Keywords are listed before identifiers — or, more commonly, every identifier is looked up in a keyword table.
Maximal munch has famous edge cases: in C++ before 2011, vector<vector<int>> lexed >> as a shift operator, so you had to write > >.
A hand-written lexer
Most production compilers (GCC, Clang, Go, rustc, V8) use hand-written lexers: faster, better error messages, and easy handling of context-sensitive quirks.
from dataclasses import dataclass
KEYWORDS = {"if", "else", "while", "return", "let", "fn"}
SINGLE = {"(": "LPAREN", ")": "RPAREN", "{": "LBRACE", "}": "RBRACE",
"+": "PLUS", "-": "MINUS", "*": "STAR", "/": "SLASH", ";": "SEMI", ",": "COMMA"}
DOUBLE = {"==": "EQ", "!=": "NE", "<=": "LE", ">=": "GE"}
@dataclass
class Token:
type: str
text: str
line: int
col: int
def lex(src: str) -> list[Token]:
tokens, i, line, col = [], 0, 1, 1
def emit(type_, text):
tokens.append(Token(type_, text, line, col))
while i < len(src):
c = src[i]
if c == "\n":
i += 1; line += 1; col = 1; continue
if c.isspace():
i += 1; col += 1; continue
if src.startswith("//", i): # comment: skip to end of line
while i < len(src) and src[i] != "\n": i += 1
continue
start = i
if c.isalpha() or c == "_": # identifier or keyword
while i < len(src) and (src[i].isalnum() or src[i] == "_"): i += 1
word = src[start:i]
emit("KW_" + word.upper() if word in KEYWORDS else "IDENT", word)
elif c.isdigit(): # integer
while i < len(src) and src[i].isdigit(): i += 1
emit("INT", src[start:i])
elif c == '"': # string literal
i += 1
while i < len(src) and src[i] != '"':
i += 2 if src[i] == "\\" else 1
if i >= len(src): raise SyntaxError(f"unterminated string at {line}:{col}")
i += 1
emit("STRING", src[start + 1:i - 1])
elif src[i:i + 2] in DOUBLE: # maximal munch: try 2 chars first
i += 2; emit(DOUBLE[src[start:i]], src[start:i])
elif c in SINGLE or c in "<>=!":
i += 1; emit(SINGLE.get(c, {"<": "LT", ">": "GT", "=": "ASSIGN", "!": "NOT"}[c]), c)
else:
raise SyntaxError(f"unexpected character {c!r} at {line}:{col}")
col += i - start
emit("EOF", "")
return tokensPractical details
- Lookahead: usually one or two characters (peek) is enough.
- Error recovery: report an illegal character, skip it, keep lexing to find more errors.
- Context-sensitive lexing: in JavaScript,
/may begin a regex literal or be division depending on the previous token; Python's lexer emitsINDENT/DEDENTtokens by tracking an indentation stack; template strings and string interpolation require lexer modes. - Unicode: identifiers may include non-ASCII letters; source is usually UTF-8.
- Performance: lexing touches every byte, so production lexers avoid allocation (tokens reference slices of the source) and use tight loops or SIMD.
- The lexer turns characters into tokens (type + lexeme + position), dropping whitespace and comments.
- Token patterns are regular expressions; generators compile them to a DFA via Thompson's construction and subset construction.
- Maximal munch and rule priority resolve ambiguities; keywords are usually found via a lookup table.
- Production lexers are often hand-written for speed, error messages and context-sensitive features.