Lexical analysis
Lexical analysis: how source text is split into tokens using regular expressions, finite automata (NFA/DFA), input buffering and scanner rules, with constructions and examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Lexical analysis is the first phase of a compiler or any language processor: it reads raw source text and converts it into a stream of tokens the next phases (parser, semantic analyser) can use. Engineers implement fast, correct scanners (lexers) in assemblers, compilers, interpreters, linkers, device drivers that embed small languages, and in tools that must recognise patterns in text.
Key ideas
Explain terms before using them.
- Source character: one character from the input file (for example a Unicode code point; in ASCII-encoded sources this is one byte).
- Lexeme: the contiguous sequence of source characters that matches a token pattern. Example: the characters
c,o,u,n,tform the lexemecount. - Token: a pair (token-name, attribute) representing the lexeme's type and any extra value (e.g. token-name
NUMBER, attribute27). - Pattern: a rule (usually a regular expression) that describes the lexemes for one token type.
- Scanner (lexer): the program that implements lexical analysis, applies patterns to the input, and produces tokens.
- Regular expression (RE): a formula using concatenation, alternation (|), and Kleene star (*) over an alphabet Σ that describes a set of strings. (We assume the usual precedence: * highest, concatenation next, | lowest.)
- Regular language: a set of strings that can be described by some RE.
- NFA (nondeterministic finite automaton): a 5-tuple (Q, Σ, δ, q0, F) where Q is a finite set of states, Σ is the input alphabet, δ: Q × (Σ ∪ {ε}) → P(Q) is the transition function (P(Q) is the power set of Q), q0 ∈ Q is the start state, and F ⊆ Q is the set of accepting states. Transitions may be on ε (empty string).
- DFA (deterministic finite automaton): a 5-tuple (Q, Σ, δ, q0, F) where δ: Q × Σ → Q (exactly one next state per input) and no ε-transitions.
Exact statements students must remember:
- Kleene's theorem: A language is regular iff some finite automaton (NFA or DFA) recognises it iff some regular expression denotes it. (Assumptions: alphabet Σ finite, automata finite-state.)
- Thompson construction: every regular expression can be converted mechanically into an NFA; construct small NFA fragments for base cases and combine using ε-transitions for union, concatenation and star. (This is constructive and used in practice.)
- Subset construction (powerset construction): every NFA can be converted into an equivalent DFA by creating DFA states that are sets of NFA states. Start state is ε-closure of NFA start; DFA transition on symbol a from set S goes to ε-closure of union of δ(q,a) for q∈S. Optionally, minimize the resulting DFA (e.g., Hopcroft’s algorithm) to reduce the number of states without changing the language recognized.
- Longest-match (maximal munch) rule: when multiple patterns match a prefix of the remaining input, choose the longest lexeme; if there is a tie, use the pattern priority (order of rules) to pick which token. This rule is essential to disambiguate keywords vs identifiers and multi-character operators.
- Two-buffer input technique: use two fixed-size buffers and sentinel (EOF marker) to implement efficient streaming input allowing unread and refill without shifting the whole file. Typical implementation uses two pointers lexemeBegin and forward; when forward meets the sentinel, refill the other buffer and reset forward; if the sentinel is encountered again without data, report EOF.
- Complexity claim used in practice: scanning with a DFA is O(n) time in the length n of the input (constant work per character) and O(m|Σ|) memory for a full transition table (or less with sparse encoding), where m is the number of DFA states. (Assumes DFA fits in memory and table lookup is O(1).)
Diagrams to draw in exams (describe exactly):
- For Thompson NFA for a|b: draw two small circles labelled start and accept, with an ε edge from start to two sub-NFAs; each sub-NFA is a single labelled edge
aorbto its own state, then ε edges from those to accept. Label every state uniquely. - For subset construction: draw the NFA states as circles, list the ε-closure(s) as a boxed set, then draw DFA states as labelled boxes containing sets of NFA states; draw transitions with input symbols.
Formulas
DFA = (Q, Σ, δ, q0, F) — Q states, Σ alphabet, δ: Q×Σ→Q, q0∈Q start, F⊆Q accepting; applies to deterministic recognisers.
NFA = (Q, Σ, δ, q0, F) — same but δ: Q×(Σ∪{ε})→P(Q); applies to nondeterministic recognisers with ε-moves.
ε-closure(S) = S ∪ { q | there exists path of ε-transitions from some p∈S to q } — set of states reachable by only ε.
DFA-transition(T, a) = ε-closure( ⋃_{q∈T} δ(q,a) ) — used in subset construction; T a set of NFA states.
Time(scanning with DFA) = O(n) — n = number of input characters; applies when DFA table lookup is O(1).
Syntax to remember (regular expressions):
R1 | R2— union (alternation)R1 R2orR1R2— concatenationR*— Kleene star (zero or more repetitions)R+— one or more; equivalent toR R*( )— grouping
Worked examples
Example 1 — Thompson NFA for a(b|c)*d (constructive steps).
- Base:
a→ NFA: start s0 --a--> s1 (s1 accept). - Base:
bandc(andd) similar. b|c: make new start s2, new accept s3; s2 --ε--> b-start and s2 --ε--> c-start; b-accept --ε--> s3 and c-accept --ε--> s3.(b|c)*: takeb|cfragment, add new start s4 and new accept s5; s4 --ε--> s2 (the union start) and s4 --ε--> s5 (to allow zero repeats); s3 --ε--> s2 (to repeat) and s3 --ε--> s5.- Concatenate
a(from step 1),(b|c)*(step 4), andd: connecta's accept to(b|c)*start by ε, and(b|c)*accept tod's start by ε. Number states and label all transitions.
What to draw: include all states from the base fragments for a, b, c, the union, the star, and d; label ε and character transitions; final accepting state marked double circle.
Example 2 — Scanner trace (tokenisation) with rules:
- IDENTIFIER: letter (letter | digit)* (assume letter = [A-Za-z], digit = [0-9])
- NUMBER: digit+
- ASSIGN:
= - PLUS:
+ - SEMI:
; - WHITESPACE: space, tab, newline (ignored)
Input:
count123=45+6;Step-by-step:
- Read
c(letter) → follow IDENTIFIER DFA: reado u n t 1 2 3(letters/digits allowed). Next char is=which is not allowed; stop. Longest match lexemecount123→ emit token (IDENTIFIER,count123). - Read
=→ matches ASSIGN (single char) → emit (ASSIGN,=). - Read
4→ NUMBER: read4 5, next char+stops → emit (NUMBER,45). - Read
+→ emit (PLUS,+). - Read
6→ NUMBER: read6, next char;stops → emit (NUMBER,6). - Read
;→ emit (SEMI,;). Show that longest-match prevented splittingcount123intocountand123(correct behaviour for identifiers).
Example 3 — Subset construction small example for RE a|ab.
- Build NFA: states q0 start; q1 for
asingle; q2 chain forab. From q0 ε→q1 (which onagoes to accept qf) and ε→q2 (q2 onato q3 onbto qf). Accept is qf. - ε-closure({q0}) = {q0, q1, q2} if q1, q2 reachable by ε — list them.
- On input
a: compute union δ of these states ona, take ε-closure → produces DFA state containing qf (accepting) and possibly other states. Continue until no new DFA states. (In exams draw the set boxes and transitions; final DFA will acceptaandab.)
Common mistakes
- Using NFA transitions as if deterministic (forgetting ε-closure when doing subset construction).
- Not handling end-of-file properly in two-buffer scheme (missing sentinel leading to infinite loops).
- Claiming DFA size is always small — in worst case DFA can have up to 2^{|NFA-states|} states; ignoring this exponential blow-up is dangerous.
- Assuming regex with backreferences are regular (backreferences make the language non-regular).
For your exam
Kinds of questions you will see:
- Definitions: define token, lexeme, regular expression, NFA, DFA, ε-closure; give precise 1–2 sentence definitions.
- Short notes: Thompson construction, subset construction, longest-match rule, input buffering.
- Derivations / algorithms: show step-by-step Thompson construction for a given RE; convert a small NFA to DFA using subset construction; show two-buffer refill algorithm pseudocode.
- Numericals / traces: scan a supplied input and show the produced token stream; simulate a DFA on an input string showing state sequence.
- Diagrams: draw NFA fragments and the resulting DFA; label states, transitions, start and final states.
What full-marks answers include:
- Exact definitions (bold terms), correct diagrams with labelled states and transitions, and a correct final set of tokens or DFA states.
- For construction problems: show intermediate steps (building blocks for Thompson, each ε-closure step in subset construction).
- For scanner traces: show each character read, lexeme boundaries, and final emitted tokens with attributes.
Quick check
- What does the longest-match rule decide when two patterns match the same prefix?
- Write the formal type of δ in a DFA and in an NFA (include ε).
- Give one reason why we convert an NFA to a DFA before implementing a scanner.
Answers: 1) Choose the match with the greatest number of characters; if tie, use rule priority. 2) DFA: δ: Q × Σ → Q. NFA: δ: Q × (Σ ∪ {ε}) → P(Q). 3) A DFA is deterministic so scanning is O(n) with a single transition per input character (no backtracking or nondeterministic choices), making the scanner fast and simple to implement.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?