Sub topic 4
NFAs and DFAs as token recognizers
This chapter assumes you know basic set notation, can read a state-transition diagram, and have met regular expressions. The previous chapters defined tokens and wrote patterns for them. Here we turn those patterns into machines that decide whether a string of characters is a lexeme of a given token class.
The working model
A deterministic finite automaton (DFA) is a 5-tuple (Q, Σ, δ, q0, F):
- Q is a finite set of states.
- Σ is the input alphabet.
- δ: Q × Σ → Q is the transition function.
- q0 is the start state.
- F ⊆ Q is the set of accepting states.
The machine starts in q0 and reads one character at a time. For each character it applies δ. It accepts if the whole input is consumed and the final state is in F. A DFA has exactly one next state for each (state, character) pair, so it needs no guessing.
A nondeterministic finite automaton (NFA) changes δ to Q × (Σ ∪ {ε}) → 2^Q. A pair can lead to several states, or to none, and an ε-transition moves without reading input. An NFA accepts if at least one path reads the whole input and ends in an accepting state.
Both models recognize exactly the regular languages. Nondeterminism adds convenience, not power.
A DFA that recognizes identifiers and numbers
The diagram shows a DFA that recognizes two token classes, identifiers [A-Za-z_][A-Za-z0-9_]* and integers [0-9]+. Its accepting states are Ident and Num.
The diagram leaves out a dead (trap) state. Any missing transition, such as Num on a letter, goes to the dead state. The dead state has no way out and is not accepting. In a complete DFA every state has a transition for every symbol. Diagrams usually omit the dead state, but table-based implementations store it explicitly. Count it when a GATE question asks for the number of states in a complete DFA.
Here is the same DFA as a table-driven function. It returns the end of the longest accepted prefix, which is the behavior a lexer needs.
def char_class(c):
if c.isascii() and (c.isalpha() or c == "_"):
return "letter"
if c.isascii() and c.isdigit():
return "digit"
return "other"
DELTA = {
("Start", "letter"): "Ident",
("Start", "digit"): "Num",
("Ident", "letter"): "Ident",
("Ident", "digit"): "Ident",
("Num", "digit"): "Num",
}
ACCEPTING = {"Ident": "ID", "Num": "NUM"}
def longest_match(text, start=0):
state, i, best = "Start", start, None
while i < len(text):
state = DELTA.get((state, char_class(text[i])))
if state is None: # fell into the dead state
break
i += 1
if state in ACCEPTING:
best = (ACCEPTING[state], text[start:i])
return best
print(longest_match("count1 = 5")) # ('ID', 'count1')
print(longest_match("42abc")) # ('NUM', '42')
print(longest_match("+")) # NoneThe loop records the last accepting position instead of stopping at the first. That is the machine-level form of maximal munch, covered in a later chapter.
Simulating an NFA
An NFA cannot follow one path, so a simulator tracks the set of all states the machine could be in. The NFA below recognizes (a|b)*abb. State 0 loops on a and b, and also guesses that the final abb has begun.
NFA = {
(0, "a"): {0, 1},
(0, "b"): {0},
(1, "b"): {2},
(2, "b"): {3},
}
START, ACCEPT = {0}, {3}
def accepts(s):
current = set(START)
for ch in s:
current = set().union(*(NFA.get((q, ch), set()) for q in current))
return bool(current & ACCEPT)
print(accepts("aabb")) # True
print(accepts("abb")) # True
print(accepts("abab")) # FalseEach set the simulator holds corresponds to one DFA state. Collecting those sets in advance gives the subset construction, which the next chapter develops.
NFA versus DFA
| Property | NFA | DFA | Column | Column |
|---|---|---|---|---|
| Next states per (state, symbol) | Zero, one, or many | Exactly one | ||
| ε-transitions | Allowed | Not allowed | ||
| Time to scan n characters | O(n·\ | Q\ | ²) by set simulation | O(n) |
| Size from a regex of length m | O(m) states | Up to 2^m states in the worst case |
Lexer generators exploit this trade-off. The regex-to-NFA step is cheap and mechanical. Converting to a DFA gives the fast scanning loop, at a possible cost in table size.
Common errors
- Forgetting the dead state. A complete DFA on Σ = {a, b} needs a transition on both symbols from every state.
- Misusing ε-closure. Before reading each symbol, and at the very start, an ε-NFA's current set must be extended with every state reachable by ε-moves.
- Treating "stuck" as "reject" too early. For a lexer, getting stuck after passing an accepting state is normal. Back up to the last accepting position.
- Assuming the DFA is always larger. The bound is 2^n states for an n-state NFA, but many subsets are unreachable. Some NFAs have a smaller DFA than NFA.
- Mixing up accepting states. The accepting state for
[0-9]+is not the start state. The start state accepts only if the empty string is in the language.
Exercise
An NFA without ε-transitions has 4 states. What is the maximum number of states in the DFA produced by subset construction, counting the empty set? Is that bound always reached?
Show answer
The maximum is 2^4 = 16, since each DFA state is a subset of the 4 NFA states and the empty set is the dead state. The bound is not always reached. Only subsets reachable from the start subset become DFA states, and many NFAs produce far fewer. The NFA above for (a|b)*abb has 4 states and its DFA has only 4 states.
Exercise
Using the NFA simulator above, give the set of states after reading each prefix of abb, starting from {0}.
Show answer
After a: {0, 1}. After ab: {0, 2}. After abb: {0, 3}. State 3 is accepting, so abb is accepted.