Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Specifying and recognising tokens

How to specify tokens with regular expressions and recognise them with finite automata (lexical analysis for compilers).

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 front end: it converts raw source text into a stream of tokens for the parser. Engineers use token specifications and fast recognisers (DFAs) when building compilers, interpreters, source-formatting tools, syntax highlighters and any software that must split programming language text into meaningful pieces.

Key ideas

  • String (or word): a finite sequence of symbols from an alphabet.
  • Language: a set of strings over an alphabet.
  • Token: a pair (token-name, lexeme) where lexeme is the actual substring from the source and token-name is the category (for example, IDENTIFIER, NUMBER, PLUS). Compilers work with a stream of tokens, not raw characters.
  • Pattern: a description of the set of lexemes that belong to a token, usually given by a regular expression.
  • Regular expression (RE): a formal notation to describe regular languages. Basic operators: union (A|B), concatenation (AB), Kleene star (A*). We also commonly use + (one or more), ? (zero or one), character classes like [a-z], and escape sequences.
  • Regular language: a set of strings described by some regular expression (equivalently recognised by a finite automaton). State Kleene's theorem: A language is regular iff it can be represented by a regular expression iff it can be recognised by a finite automaton (NFA/DFA). Assumption: finite alphabet, finite expressions.
  • Nondeterministic finite automaton (NFA): a 5-tuple (Q, Σ, δ, q0, F) where Q is finite set of states, Σ alphabet, δ transition relation Q × (Σ ∪ {ε}) → P(Q), q0 start state, F set of accepting states. In an NFA a current state can branch into several next states for the same input symbol, and ε-transitions allow moves without consuming input. Here P(Q) denotes the power set of Q.
  • Deterministic finite automaton (DFA): a special NFA where δ is a function Q × Σ → Q (no ε, single next state). A DFA is easier and faster to implement because there is one next state for each input character.
  • ε-closure: for a set of NFA states S, ε-closure(S) is the set of states reachable from S by following only ε-transitions (including S itself).
  • Subset construction (powerset construction): algorithm to convert an NFA to an equivalent DFA. Exact statement: Given an NFA with n states, construct a DFA whose states are subsets of the NFA states; the DFA accepts the same language. Worst-case number of DFA states is 2^n. Step-by-step (the standard derivation universities want):
    1. Let Q_N be the NFA states. Start state of the DFA is ε-closure({q0}).
    2. For any DFA state S (a subset of Q_N) and input symbol a∈Σ, compute T = ε-closure(⋃_{p∈S} move(p,a)), where move(p,a) is the set of NFA states reachable from p on character a.
    3. Make T a DFA state and add a DFA transition S --a--> T. Repeat until no new DFA states.
    4. Any DFA state containing at least one NFA accepting state is an accepting DFA state.
  • Maximal-munch (longest-match) rule: when multiple token patterns match a prefix of the remaining input, choose the longest lexeme; if a tie remains, use token priority (order of rules) to decide.
  • Token precedence and handling overlaps: lexical specifications often list patterns in order; when patterns overlap (e.g., if "if" could be an IDENTIFIER), languages choose rule ordering or separate keyword tables to resolve. Practical lexer generators (lex/flex) use rule order as tie-break.
  • Lex/Flex pipeline: write token rules as regular expressions with associated actions. The tool converts REs to NFAs (Thompson construction), combines them, runs subset construction to DFA, optionally minimises and emits a fast table-driven or code-based DFA.
  • DFA minimisation: reduces number of DFA states to the minimal equivalent automaton. Common algorithm: partition refinement (Hopcroft's algorithm). Exact statement: Hopcroft runs in O(|Σ| n log n) time; naive partition refinement is O(n^2). The minimal DFA is unique up to isomorphism.

Diagram to draw for an exam (describe exactly):

  • Draw a small NFA for regexp (a|b)*abb: three part structure. Label states q0 (start), intermediate states for a/b loops, arrows for ε if using Thompson construction, and final accepting state qF. Then draw the equivalent DFA produced by subset construction: each DFA state is a set of NFA states—draw them as labelled circles, arrows labelled a or b, initial DFA state boxed or marked, accepting DFA states double-circled.

Formulas

RE operators: | (union), concatenation (implicit), * (Kleene star), + (one or more), ? (zero or one), [a-z] (character class) — Syntax to remember for regular expressions used in token rules. Operator precedence: unary (*, +, ?) highest, concatenation next, | lowest; parentheses override. Thompson construction: build NFA fragments for atoms; combine with ε transitions for union, concatenation, and star — Summary algorithm to convert RE → NFA. ε-closure(S) = S ∪ { q | exists p ∈ S and path of only ε-transitions from p to q } — Definition and use in subset construction. DFA transition: δ_DFA(S, a) = ε-closure(⋃_{p∈S} δ_NFA(p, a)) — δ_NFA may return multiple states; δ_DFA is deterministic function on subset state S. Accepting DFA states: { S | S ∩ F_NFA ≠ ∅ } — A DFA state is accepting if it contains any NFA accepting state. Complexity: subset construction worst-case number of DFA states ≤ 2^{|Q_N|} — When it applies: theoretical worst case; practical automata are smaller. Hopcroft minimisation complexity: O(|Σ| n log n) — where n is the number of DFA states and Σ is the input alphabet.

Worked examples

Example 1 — Convert regexp (a|b)*abb to a DFA (sketch and subset-construction trace):

  1. Build an NFA (Thompson):
    • Fragment for (a|b)*: a start state q0 with loop via an intermediate that accepts a or b and loops with ε back. For exam, draw: q0 --ε--> q1; q1 --a--> q2; q1 --b--> q3; q2 --ε--> q1; q3 --ε--> q1; q1 --ε--> q4 (continue to concatenation). Then fragments for 'a' then 'b' then 'b' concatenated, finishing at accepting state qF. (You must draw states and label all ε and symbol transitions.)
  2. Compute ε-closure of start {q0} to get initial DFA state S0.
  3. For S0 compute δ_DFA(S0,a) and δ_DFA(S0,b) by computing moves from all NFA states in S0 then taking ε-closures. Continue until no new subsets.
  4. Mark any subset containing qF as accepting. (Exam expectations: show the key subset calculations explicitly for the first few steps and then draw the DFA transition graph with states named as sets of NFA states. If time limited, show clear state-labels and transitions that prove correctness.)

Example 2 — Tokenising a small input with rules and maximal-munch: Rules (order = priority): NUMBER: [0-9]+(\.[0-9]+)? IDENT: [A-Za-z_][A-Za-z0-9_]* ASSIGN: = PLUS: \+ WS: [ \t\n]+ (action: skip) Input: sum = a + 42; Step-by-step:

  1. Read from start: "sum" matches IDENT (lexeme "sum"). Emit IDENT(sum).
  2. Next char is space; WS matches and is skipped.
  3. Next char '=' matches ASSIGN. Emit ASSIGN.
  4. Space skipped.
  5. 'a' matches IDENT (single letter). Emit IDENT(a).
  6. Space skipped.
  7. '+' matches PLUS. Emit PLUS.
  8. Space skipped.
  9. '42' matches NUMBER (digits). Emit NUMBER(42).
  10. ';' unknown if no rule: lexer should report an error or have a token for semicolon. If token rule missing, report lexical error at that character. (Exam answer must mention longest-match and skipping WS, and show emitted token sequence.)

Common mistakes

  • Mixing up NFA transitions and DFA transitions: writing multiple target states in a DFA transition or forgetting ε-closures during subset construction.
  • Not applying the maximal-munch rule: choosing the first matching rule instead of the longest matched lexeme when several rules match.
  • Forgetting to mark DFA states that contain any NFA accepting state as accepting.
  • Omitting whitespace and comment handling in token rules; then lexing examples fail at spaces or comments.
  • Claiming subset construction always creates 2^n states in practice — this is worst-case only.
  • In minimisation, trying to merge states that have different acceptance labels (e.g., merging states accepting different token types) — acceptance labels matter.

For your exam

Possible question types:

  • Definitions: define token, lexeme, regular expression, NFA, DFA, ε-closure.
  • Short note: explain the role of the lexical analyser, maximal-munch rule, or lex/flex pipeline.
  • Derivation/algorithm: give Thompson construction for a small RE or the subset-construction algorithm and prove correctness sketch.
  • Convert: RE → NFA → DFA (show all intermediate steps), or show DFA minimisation by partition refinement.
  • Trace: given token rules and input, show the token stream produced and explain handling of whitespace/comments.
  • Diagram: draw an NFA and its equivalent DFA; label states and transitions. What full-marks answers include:
  • Precise definitions (bold or underlined in your answer if allowed) and an explicit alphabet assumption.
  • For algorithms: clear input/output specification, step-by-step actions, and a small worked example trace showing correctness.
  • For conversions: show the full NFA fragment (Thompson), list ε-closures computed, list DFA states as sets, and provide the final DFA graph with initial and accepting states.
  • For tokenisation: show longest-match decisions and how ties are broken by rule ordering or priority.

Quick check

  1. What is the difference between a token and a lexeme?
  2. State the subset-construction formula for a DFA transition from NFA sets.
  3. In maximal-munch, given rules IDENT = [A-Za-z]+ and KEY = "if", how should the lexer return the text "if"? (Assume KEY has higher priority.)

Answers: 1) A token is the category/name (e.g. IDENT), a lexeme is the actual substring from the source that matched; 2) δ_DFA(S, a) = ε-closure(⋃_{p∈S} δ_NFA(p, a)); 3) Return KEY("if") because it matches both but KEY has higher priority (or treat keywords specially after recognising IDENT).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?