Programming Search⌘K

Conceptcore

Finite-state machines

Also called finite-state machine, state machine, finite automaton, DFA, NFA, deterministic finite automaton, transition table, Mealy machine, Moore machine, statechart.

A finite-state machine is always in one of a fixed set of states and moves between them on each input symbol. Regular expressions, lexers and network protocols are such machines.

Applies to
core-languages

Idea

A finite-state machine is a model of computation with a fixed, finite set of states. The machine is always in one of them. It reads its input one symbol at a time, and a transition table gives the next state for each pair of current state and symbol. Some states are final: the machine accepts the input if it stops in one of them. The machine has no other memory, so it can recognize patterns such as numbers, keywords and well-formed dates, but it cannot count without limit or match nested brackets. Regular expressions, lexers, network protocols, user interfaces and game logic are finite-state machines in practice.

# a machine that accepts decimal numbers such as 42, -3.5 and 007
TABLE = {
    ("start", "sign"): "sign",
    ("start", "digit"): "int",
    ("sign", "digit"): "int",
    ("int", "digit"): "int",
    ("int", "dot"): "dot",
    ("dot", "digit"): "frac",
    ("frac", "digit"): "frac",
}
ACCEPT = {"int", "frac"}


def kind(ch):
    if ch.isdigit():
        return "digit"
    return {"+": "sign", "-": "sign", ".": "dot"}.get(ch, "other")


def run(text, trace=False):
    state = "start"
    for ch in text:
        state = TABLE.get((state, kind(ch)), "dead")  # no entry: reject
        if trace:
            print(f"  {ch!r} -> {state}")
        if state == "dead":
            return False
    return state in ACCEPT


print("-3.5")
run("-3.5", trace=True)
for text in ["42", "-3.5", "1.", "+", "007", ".5", "4.2.1"]:
    print(f"{text:6} {run(text)}")
Output
-3.5
  '-' -> sign
  '3' -> int
  '.' -> dot
  '5' -> frac
42     True
-3.5   True
1.     False
+      False
007    True
.5     False
4.2.1  False

The machine has five states and a dead state. kind reduces each character to one of four classes, and TABLE gives the next state for each pair of state and class; a pair with no entry goes to the dead state, from which no input escapes. The trace shows the machine reading -3.5, and it stops in frac, a final state. 1. stops in dot and + in sign, which are not final, so the machine rejects them, and .5 dies at once because a number must start with a sign or a digit.

How it works

States, input and transitions. Russ Cox describes the model in an article on regular expressions: "A finite automaton is always in one of its states".1 A machine is defined by five things: the set of states, the alphabet of input symbols, the transition function, the start state and the set of final states. The state is the only memory of the machine, so each state must stand for everything that matters about the input read so far. In the example, int means "a sign or nothing, then at least one digit, and no dot yet".

Deterministic and nondeterministic machines. In a deterministic machine (DFA), "in any state, each possible input letter leads to at most one new state."1 A nondeterministic machine (NFA) can have several choices, and it accepts if any sequence of choices ends in a final state. An NFA is often smaller and easier to build from a pattern, and the subset construction turns any NFA into an equal DFA whose states are sets of NFA states, at the risk of many more states. Every regular expression has an equal finite automaton, and every finite automaton has an equal regular expression. The example files check this: each compares its machine with the pattern [+-]?[0-9]+(\.[0-9]+)? on every input.

Two ways to write a machine in code. A table puts the transitions in data: an array indexed by state and symbol class, as in the idea block and the C++ file. A step is one lookup, and tools can generate, check and draw the table. Code puts the transitions in a switch or match on the state, as in the other files. This is easier to read and lets each transition run actions, but its structure is less uniform. Languages with enums and exhaustive matching, such as Rust, Java, Kotlin, C# and TypeScript, check that every state has a case, which catches the common bug of a new state that the code forgets.

Machines that act. A recognizer only accepts or rejects. Most machines in programs also produce output or run actions on each transition: a lexer emits a token, a protocol sends a message, a user interface shows a different screen. The TCP standard defines a connection this way: "A connection progresses through a series of states during its lifetime."2 Its states include LISTEN, SYN-SENT, ESTABLISHED and TIME-WAIT, and each event, a segment that arrives or a call from the user, moves the connection to a new state. Writing such logic as an explicit machine makes illegal transitions visible and keeps the state in one variable instead of spread over many flags.

States in the type system. A language with expressive types can make each state a separate type, so that the compiler rejects operations that are illegal in the current state. The Rust book shows this with a blog post that moves from draft to review to published: "we’ll encode the states into different types. Consequently, Rust’s type-checking system will prevent attempts to use draft posts where only published posts are allowed by issuing a compiler error."3 The object-oriented state pattern does the opposite: "The states are represented by a set of state objects, and the value’s behavior changes based on its state."3 See the state pattern.

What finite machines cannot do. A machine with n states cannot tell apart more than n situations. Recognizing balanced brackets of any depth needs a count without limit, so no finite-state machine can do it; a pushdown automaton, which adds a stack, can, and so can a recursive parser. A Turing machine adds a tape without limit and can compute anything that a program can. Real programs live between these models: a machine that has a few counters or a small stack in addition to its state is common, and it is still easy to reason about if the extra memory is small.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomA union of string literal types names the states, and the compiler checks that a switch covers each one.
GoIdiom
RustIdiom
KotlinIdiomAn enum class or a sealed class names the states, and a when expression must cover every case; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomA table of transitions and a recursive query, or MATCH_RECOGNIZE in some databases, run a machine over rows.
BashIdiomA variable holds the state and a case statement in a loop gives the transitions.
PowerShellIdiomAn enum names the states and a switch statement gives the transitions; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no states or transitions.
CSSDoes not applyStyle rules have no machine of their own, although selectors such as :hover react to the state of an element.
Regular expressionsNativeEvery regular expression describes a regular language, and engines compile it to a finite automaton or match it by backtracking.
Language Verdict Mechanism
Python idiom Enum and match with guards; re
JavaScript idiom constants and switch; regular expressions
TypeScript idiom unions of literal types; exhaustive switch
Java idiom enum and exhaustive switch expressions; java.util.regex
Kotlin idiom enum class or sealed class and when
C# idiom enum and switch expressions on tuples; Regex
Go idiom iota constants and switch; regexp
Rust idiom enum and exhaustive match; states as types
C idiom enum and switch; generated tables from lex or re2c
C++ idiom enum class and constexpr tables; std::regex
Bash idiom a state variable and case in a loop
PowerShell idiom enum and switch
SQL idiom transition tables; recursive queries; MATCH_RECOGNIZE
Regex native every pattern describes a finite automaton
HTML n/a no states or transitions
CSS n/a no machine; :hover and :checked react to state

No core language has a construct for state machines, and none needs one: an enumeration for the states, a variable for the current state and a switch or a table for the transitions are enough. Every example file builds the same machine for decimal numbers and runs it on the same seven inputs, and the files that print a last line check that the language's regular expression engine agrees. The difference between the languages is how much the compiler checks. Rust, Java and C# reject or warn about a match or switch that leaves out a state, while JavaScript and Python accept a missing case and send the input to the default.

Regular expressions are the one native case. A pattern is a compact way to write a finite automaton, and engines in the RE2 family, such as Go's regexp and Rust's regex, compile it to one. Their documentation makes a promise that follows from the model: the Go package "is guaranteed to run in time linear in the size of the input."4 Backtracking engines, as in Python, JavaScript, Java and .NET, accept features that are not regular, such as backreferences, and lose that promise.

PythonGitHub
import re
from enum import Enum, auto


class S(Enum):
    START = auto()
    SIGN = auto()
    INT = auto()
    DOT = auto()
    FRAC = auto()
    DEAD = auto()


def step(s, ch):
    digit = ch.isdigit()
    match s:
        case S.START if ch in "+-":
            return S.SIGN
        case S.START | S.SIGN | S.INT if digit:
            return S.INT
        case S.INT if ch == ".":
            return S.DOT
        case S.DOT | S.FRAC if digit:
            return S.FRAC
        case _:
            return S.DEAD


def accepts(text):
    s = S.START
    for ch in text:
        s = step(s, ch)
    return s in (S.INT, S.FRAC)  # accept only in a final state


inputs = ["42", "-3.5", "1.", "+", "007", ".5", "4.2.1"]
for text in inputs:
    print(text, accepts(text))
pattern = re.compile(r"[+-]?[0-9]+(\.[0-9]+)?")
print("regex agrees:", all(bool(pattern.fullmatch(t)) == accepts(t) for t in inputs))
Output
42 True
-3.5 True
1. False
+ False
007 True
.5 False
4.2.1 False
regex agrees: True

This code runs but gives a wrong answer on purpose.

def step(s, ch):
    if s == "start" and ch in "+-":
        return "sign"
    if s in ("start", "sign", "int") and ch.isdigit():
        return "int"
    if s == "int" and ch == ".":
        return "dot"
    if s in ("dot", "frac") and ch.isdigit():
        return "frac"
    return "dead"


def accepts(text):
    s = "start"
    for ch in text:
        s = step(s, ch)
    return s != "dead"  # wrong: "sign" and "dot" are not final states


for text in ["42", "1.", "+", ""]:
    print(repr(text), accepts(text))
Output
'42' True
'1.' True
'+' True
'' True
  • Verdict: idiom. Python has no state machine construct, but an Enum names the states and a match statement with guards gives one case for each transition. The re module compiles a regular expression for the same language, and the two agree on every input.
  • The wrong block accepts the input when the machine has not died, instead of when it stops in a final state. The input 1. ends in the state for a dot and + in the state for a sign, which are live but not final, and the empty string never leaves the start state, so all three are wrongly accepted.
#include <array>
#include <iostream>
#include <regex>
#include <string_view>

enum class S { Start, Sign, Int, Dot, Frac, Dead, Count };
enum class C { Sign, Digit, Dot, Other, Count };

constexpr C kind(char ch) {
    if (ch >= '0' && ch <= '9') return C::Digit;
    if (ch == '+' || ch == '-') return C::Sign;
    return ch == '.' ? C::Dot : C::Other;
}

// one row per state, one column per kind of character
constexpr std::array<std::array<S, 4>, 6> table{{
    {S::Sign, S::Int, S::Dead, S::Dead},  // Start
    {S::Dead, S::Int, S::Dead, S::Dead},  // Sign
    {S::Dead, S::Int, S::Dot, S::Dead},   // Int
    {S::Dead, S::Frac, S::Dead, S::Dead}, // Dot
    {S::Dead, S::Frac, S::Dead, S::Dead}, // Frac
    {S::Dead, S::Dead, S::Dead, S::Dead}, // Dead
}};

constexpr bool accepts(std::string_view text) {
    S s = S::Start;
    for (char ch : text) s = table[static_cast<int>(s)][static_cast<int>(kind(ch))];
    return s == S::Int || s == S::Frac;
}

static_assert(accepts("-3.5") && !accepts("1.")); // runs at compile time

int main() {
    std::regex pattern(R"([+-]?[0-9]+(\.[0-9]+)?)");
    bool agree = true;
    for (std::string_view t : {"42", "-3.5", "1.", "+", "007", ".5", "4.2.1"}) {
        std::cout << t << ' ' << std::boolalpha << accepts(t) << '\n';
        agree = agree && std::regex_match(t.begin(), t.end(), pattern) == accepts(t);
    }
    std::cout << "regex agrees: " << agree << '\n';
}
Output
42 true
-3.5 true
1. false
+ false
007 true
.5 false
4.2.1 false
regex agrees: true
  • Verdict: idiom. The C++ file stores the transitions as a table, one row for each state and one column for each kind of character, so a step is one lookup. The table and the function that runs it are constexpr, and the static_assert runs the machine during compilation. std::regex matches the same language.
JavaGitHub
import java.util.List;
import java.util.regex.Pattern;

public class Main {
    enum S { START, SIGN, INT, DOT, FRAC, DEAD }

    static S step(S s, char ch) {
        boolean digit = ch >= '0' && ch <= '9';
        return switch (s) { // the compiler checks that every state has a case
            case START -> ch == '+' || ch == '-' ? S.SIGN : digit ? S.INT : S.DEAD;
            case SIGN -> digit ? S.INT : S.DEAD;
            case INT -> digit ? S.INT : ch == '.' ? S.DOT : S.DEAD;
            case DOT, FRAC -> digit ? S.FRAC : S.DEAD;
            case DEAD -> S.DEAD;
        };
    }

    static boolean accepts(String text) {
        S s = S.START;
        for (char ch : text.toCharArray()) s = step(s, ch);
        return s == S.INT || s == S.FRAC;
    }

    public static void main(String[] args) {
        List<String> inputs = List.of("42", "-3.5", "1.", "+", "007", ".5", "4.2.1");
        for (String t : inputs) System.out.println(t + " " + accepts(t));
        Pattern p = Pattern.compile("[+-]?[0-9]+(\\.[0-9]+)?");
        System.out.println("regex agrees: "
            + inputs.stream().allMatch(t -> p.matcher(t).matches() == accepts(t)));
    }
}
Output
42 true
-3.5 true
1. false
+ false
007 true
.5 false
4.2.1 false
regex agrees: true
  • Verdict: idiom. A Java enum names the states, and a switch expression over it must cover every constant, so the compiler rejects the method if a new state has no case. java.util.regex matches the same language.
#include <stdbool.h>
#include <stdio.h>

enum state { START, SIGN, INT, DOT, FRAC, DEAD };

static enum state step(enum state s, char ch) {
    bool digit = ch >= '0' && ch <= '9';
    switch (s) {
    case START: return ch == '+' || ch == '-' ? SIGN : digit ? INT : DEAD;
    case SIGN: return digit ? INT : DEAD;
    case INT: return digit ? INT : ch == '.' ? DOT : DEAD;
    case DOT:
    case FRAC: return digit ? FRAC : DEAD;
    case DEAD: return DEAD;
    }
    return DEAD;
}

static bool accepts(const char *text) {
    enum state s = START;
    for (const char *p = text; *p; p++) s = step(s, *p);
    return s == INT || s == FRAC;
}

int main(void) {
    const char *inputs[] = {"42", "-3.5", "1.", "+", "007", ".5", "4.2.1"};
    for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; i++)
        printf("%s %s\n", inputs[i], accepts(inputs[i]) ? "true" : "false");
    return 0;
}
Output
42 true
-3.5 true
1. false
+ false
007 true
.5 false
4.2.1 false
  • Verdict: idiom. C names the states with an enum, and a switch on the state gives the transitions. Compilers warn with -Wswitch when an enum value has no case. Lexers generated by tools such as lex and re2c are C programs of this shape, or with the table in an array.
using System.Text.RegularExpressions;

static S Step(S s, char ch)
{
    bool digit = char.IsAsciiDigit(ch);
    return (s, ch) switch
    {
        (S.Start, '+' or '-') => S.Sign,
        (S.Start or S.Sign or S.Int, _) when digit => S.Int,
        (S.Int, '.') => S.Dot,
        (S.Dot or S.Frac, _) when digit => S.Frac,
        _ => S.Dead,
    };
}

static bool Accepts(string text)
{
    var s = S.Start;
    foreach (var ch in text) s = Step(s, ch);
    return s is S.Int or S.Frac;
}

string[] inputs = ["42", "-3.5", "1.", "+", "007", ".5", "4.2.1"];
foreach (var t in inputs) Console.WriteLine($"{t} {Accepts(t)}");
var pattern = new Regex(@"^[+-]?[0-9]+(\.[0-9]+)?$");
Console.WriteLine($"regex agrees: {inputs.All(t => pattern.IsMatch(t) == Accepts(t))}");

enum S { Start, Sign, Int, Dot, Frac, Dead }
Output
42 True
-3.5 True
1. False
+ False
007 True
.5 False
4.2.1 False
regex agrees: True
  • Verdict: idiom. A C# enum names the states, and a switch expression on the pair of state and character, with or patterns and when guards, reads like the transition table. The compiler warns when a switch expression does not cover every input, and the last arm _ sends the rest to the dead state.
JavaScriptGitHub
const START = 0, SIGN = 1, INT = 2, DOT = 3, FRAC = 4, DEAD = 5;

function step(s, ch) {
  const digit = ch >= "0" && ch <= "9";
  switch (s) {
    case START: return ch === "+" || ch === "-" ? SIGN : digit ? INT : DEAD;
    case SIGN: return digit ? INT : DEAD;
    case INT: return digit ? INT : ch === "." ? DOT : DEAD;
    case DOT:
    case FRAC: return digit ? FRAC : DEAD;
    default: return DEAD;
  }
}

function accepts(text) {
  let s = START;
  for (const ch of text) s = step(s, ch);
  return s === INT || s === FRAC;
}

const inputs = ["42", "-3.5", "1.", "+", "007", ".5", "4.2.1"];
for (const text of inputs) console.log(text, accepts(text));
const pattern = /^[+-]?[0-9]+(\.[0-9]+)?$/;
console.log("regex agrees:", inputs.every((t) => pattern.test(t) === accepts(t)));
Output
42 true
-3.5 true
1. false
+ false
007 true
.5 false
4.2.1 false
regex agrees: true
  • Verdict: idiom. JavaScript has no enum type, so the states are integer constants, and a switch on the current state gives the transitions. Nothing checks that every state has a case. The regular expression literal recognizes the same language.
package main

import (
	"fmt"
	"regexp"
)

type state int

const (
	start state = iota
	sign
	integer
	dot
	frac
	dead
)

func step(s state, ch rune) state {
	digit := ch >= '0' && ch <= '9'
	switch {
	case s == start && (ch == '+' || ch == '-'):
		return sign
	case (s == start || s == sign || s == integer) && digit:
		return integer
	case s == integer && ch == '.':
		return dot
	case (s == dot || s == frac) && digit:
		return frac
	}
	return dead
}

func accepts(text string) bool {
	s := start
	for _, ch := range text {
		s = step(s, ch)
	}
	return s == integer || s == frac
}

func main() {
	inputs := []string{"42", "-3.5", "1.", "+", "007", ".5", "4.2.1"}
	for _, t := range inputs {
		fmt.Println(t, accepts(t))
	}
	re := regexp.MustCompile(`^[+-]?[0-9]+(\.[0-9]+)?$`)
	agree := true
	for _, t := range inputs {
		agree = agree && re.MatchString(t) == accepts(t)
	}
	fmt.Println("regex agrees:", agree)
}
Output
42 true
-3.5 true
1. false
+ false
007 true
.5 false
4.2.1 false
regex agrees: true
  • Verdict: idiom. Go declares the states as a named integer type with iota constants, and a switch with no tag tests one condition for each transition. The regexp package compiles regular expressions to automata and runs in time linear in the length of the input.
RustGitHub
#[derive(Clone, Copy, PartialEq, Debug)]
enum S {
    Start,
    Sign,
    Int,
    Dot,
    Frac,
    Dead,
}

fn step(s: S, ch: char) -> S {
    let digit = ch.is_ascii_digit();
    match (s, ch) {
        (S::Start, '+' | '-') => S::Sign,
        (S::Start | S::Sign | S::Int, _) if digit => S::Int,
        (S::Int, '.') => S::Dot,
        (S::Dot | S::Frac, _) if digit => S::Frac,
        _ => S::Dead,
    }
}

fn accepts(text: &str) -> bool {
    let end = text.chars().fold(S::Start, step);
    matches!(end, S::Int | S::Frac)
}

fn main() {
    for t in ["42", "-3.5", "1.", "+", "007", ".5", "4.2.1"] {
        println!("{t} {}", accepts(t));
    }
}
Output
42 true
-3.5 true
1. false
+ false
007 true
.5 false
4.2.1 false

This code does not compile, on purpose. The error is E0004.

#[derive(Clone, Copy)]
enum S {
    Start,
    Sign,
    Int,
    Dot,
    Frac,
    Dead,
}

fn is_final(s: S) -> bool {
    match s { // the state Dead has no arm
        S::Int | S::Frac => true,
        S::Start | S::Sign | S::Dot => false,
    }
}

fn main() {
    println!("{}", is_final(S::Dead));
}
  • Verdict: idiom. A Rust enum names the states, and a match on the pair of state and character gives the transitions. fold runs the machine over the characters of the input. Libraries such as regex build automata from patterns.
  • The fails block has a match with no arm for the state Dead. Rust requires a match to cover every value, so adding a state to the enum makes the compiler point at every match that does not handle it.
  • Mealy and Moore machines. Machines with output: a Mealy machine produces output on each transition, a Moore machine in each state. Most machines in programs are Mealy machines.
  • Statecharts. David Harel's statecharts add nested states, parallel regions and history to state machines, and UML state machines and libraries such as XState follow them.
  • Lexers. A lexer is a finite-state machine that splits text into tokens. Tools such as lex, flex and re2c generate it from regular expressions.
  • Pushdown automata and parsers. A finite-state machine with a stack recognizes the context-free languages of nested structure, which is the model behind most parsers. See recursion.
  • Coroutines and async functions. Compilers turn generators and async functions into state machines, with one state for each point where the function can pause. See iterators.
  • Workflow and protocol machines. Order processing, document approval and network protocols are long-running machines whose state lives in a database or a connection.
  • Regular expressions. A notation for the languages that finite automata recognize. See find and replace with a regular expression.

Pitfalls

  • Accepting in the wrong states. A machine accepts only if it stops in a final state. Checking only that it did not die accepts partial input, as the wrong block of the Python file shows with 1., + and the empty string.
  • Missing transitions. A state with no case for some input falls into a default that may be wrong. Use exhaustive matching, or make the dead state explicit, as the fails block of the Rust file shows.
  • State in flags. Several booleans such as connected, closing and error allow combinations that make no sense. One variable with one value for each real state removes the illegal combinations.
  • Too many states. Combining independent concerns in one machine multiplies the states. Split the machine into parallel machines, or use the nested states of statecharts.
  • Regular expressions that are not regular. Backreferences and lookaround in backtracking engines can take exponential time on some inputs, which attackers use for denial of service. Prefer engines that compile to automata for untrusted input.
  • Trying to match nesting. No finite machine and no true regular expression can check balanced brackets or HTML of any depth. Use a parser.

Cost

A deterministic machine reads each symbol once and does one lookup or one branch for it, so it runs in time linear in the length of the input and uses constant memory for the state. A transition table costs one entry for each pair of state and symbol class, which is why lexers reduce characters to a few classes first. Turning an NFA into a DFA can, in the worst case, create a number of states exponential in the size of the NFA, so engines such as RE2 build DFA states lazily, only for the inputs they meet, or simulate the NFA directly in time proportional to the product of the input length and the size of the pattern.1 Backtracking engines run fast on common patterns but can take exponential time on bad ones.

History

Warren McCulloch and Walter Pitts modeled neurons as units with finite states in 1943. Stephen Kleene, in a RAND report of 1951 published in 1956, showed that the events such networks can recognize are exactly those described by his regular expressions. George Mealy in 1955 and Edward Moore in 1956 defined the machines with output that carry their names, and in 1959 Michael Rabin and Dana Scott defined nondeterministic finite automata and proved that they recognize the same languages as deterministic ones. Ken Thompson built regular expression search into the QED editor in the 1960s by compiling patterns to machine code that simulated an NFA, and the tools grep, sed, awk and lex brought the method to Unix in the 1970s.1

David Harel introduced statecharts in 1987, and UML adopted them for its state machines in the 1990s. The TCP specification of 1981 described connections as a state machine, and RFC 9293 of 2022 keeps that description.2 Russ Cox's articles from 2007 and the RE2 library revived matching by automata, and Go's regexp and Rust's regex follow that design.4

References

  1. Russ Cox, Regular Expression Matching Can Be Simple And Fast, 2007, Finite Automata
  2. RFC 9293, Transmission Control Protocol (TCP), 2022, 3.3.2 State Machine Overview
  3. Implementing an Object-Oriented Design Pattern, The Rust Programming Language, Introduction and Encoding States and Behavior as Types
  4. Package regexp, Go standard library, Overview

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/ZN6BE8/text.yaml