# TOC Playground: regular-language core

The finite automata are in [`toc-toolkit/automata`](../subjects/automata.md), the expression syntax in [`toc-toolkit/automata/regex`](../subjects/automata-regex.md), the conversions in [`toc-toolkit/conversions/regular`](../subjects/conversions-regular.md) and the comparison procedures in [`toc-toolkit/decisions/regular`](../subjects/decisions-regular.md). The editor, worker, converter and comparison page all use these algorithms. None of the algorithms use JavaScript regular-expression matching to recognize the user's language.

## Mathematical contract

A finite automaton stores the five components `(Q, Σ, δ, q₀, F)`. State ids identify elements of `Q`; labels and coordinates are presentation data. A transition without a `read` field consumes ε. Every other transition reads exactly one alphabet token. An NFA accepts a word if some finite run consumes the entire word and finishes in `F`. Following an ε cycle forever is not an accepting run.

The `kind` discriminant distinguishes `dfa` and `nfa`, even though they share their data structure and implementation. DFA validation forbids ε edges and more than one transition from a state for the same symbol. While editing, an omitted DFA cell means an implicit rejecting sink. It is reported as a warning. `complete` of `toc-toolkit/automata` constructs the sink explicitly before operations that need a total transition function. This editing convention does not silently treat an incomplete machine as a mathematically complete DFA.

These definitions follow Sipser, _Introduction to the Theory of Computation_, third edition, Definitions 1.5 and 1.37 and the accompanying definitions of computation. The supplied book is the primary course reference.

## Expressions and structured editing

The stored representation is `{ kind: ExpressionKind.Regex, source: string }`. Checking the source produces a normalized term (`Regex` of `toc-toolkit/automata/regex`) with nodes for the empty language, epsilon, literals, union, concatenation, star, intersection and complement. A union or concat node holds a list of parts, a literal holds one alphabet symbol and a star holds one inner node. Every node is interned in a `RegexBuilder`, so equal subterms share one id.

The term is derived data, so the persisted model cannot contain a source string and a conflicting term. The UI may keep incomplete text as an editor draft while the last valid model remains available. A `RegexIssue` carries a `span` of UTF-16 source offsets, as used by browser text selections.

| Notation       | Meaning                            |
| -------------- | ---------------------------------- |
| `a`            | One alphabet symbol                |
| `ab` or `a·b`  | Concatenation                      |
| `a             | b`or`a∪b`                          | Union |
| `a*` or `a∗`   | Zero or more repetitions           |
| `a+`           | Abbreviation for `aa*`             |
| `a?`           | Abbreviation for `(a               | ε)`   |
| `( … )`        | Grouping                           |
| `ε`            | The empty word                     |
| `∅`            | The empty language                 |
| `"identifier"` | One multi-character alphabet token |
| `" "`          | A literal space token              |
| `\*` or `"*"`  | A literal asterisk                 |

Bare characters are Unicode code points. Thus an emoji is one symbol, whereas bare `id` is two symbols. Whitespace outside quotes separates notation and is ignored. Quoted strings support JSON-style control and Unicode escapes, plus `\u{…}`. An empty expression editor means ε. Empty alternatives such as `a|` are errors and must be written explicitly as `a|ε`.

Words such as `eps` and `epsilon` are not reserved. Otherwise typing a legitimate word would silently change its language. An autocomplete action can replace a requested abbreviation with the actual ε operator.

`parseSyntax` reads the source into a spanned syntax tree, and the checker desugars `+` and `?`. The smart constructors of `RegexBuilder` simplify identities including `R∪R=R`, `R∪∅=R`, `εR=Rε=R`, `∅R=R∅=∅`, `∅*=ε`, and `(R*)*=R*`. They do not claim to compute a canonical expression for every regular language. Equivalence of two different expression trees is decided by the shared automaton comparison.

Source notation also declares an alphabet. Every decoded literal token contributes to it, including a token in a term that simplifies to ∅. For example, `a∅` denotes the empty language over `{a}`. `checkRegex` returns the normalized term together with every declared literal, so the term keeps the source universe. Thompson construction (`compileRegex`) reads the alphabet of the term and not only its remaining literals.

The parser uses precedence climbing through recursive-descent stages for union, concatenation and postfix operators. The builder interns structurally identical nodes. Its n-ary union and concatenation nodes avoid deeply nested trees for flat input. The maximum source size is `MAX_SOURCE_LENGTH` (200,000 UTF-16 code units), and the number of groups open at once is bounded by `MAX_NESTING_DEPTH` (256). These are implementation limits, not mathematical limits on regular languages. Some nested flattening and canonical union sorting can take superlinear time in source size; the implementation does not advertise the entire normalization path as a strictly linear parser.

## Indexed NFA execution

The dense `Nfa` of `toc-toolkit/automata` numbers its states and separates two adjacency structures.

- `epsilon[q]` lists the ε successors of state `q`.
- `moves[q][a]` is the sorted list of successors of `q` on the symbol with index `a`.

An ε closure uses a work queue and a visited set. Each reachable state and each outgoing ε edge is processed once. An input step follows the appropriate symbol edges from every active state and then computes ε closure again. The empty active set is permanently rejecting.

The simulation invariant is that after consuming prefix `w[0..i)`, the active set contains exactly the states reachable by a run consuming that prefix and then any finite number of ε edges. The initial frame establishes the invariant by closing the start state. The transition step preserves it by the definition of NFA computation. After the last token, membership is exactly intersection of the active set with `F`.

Frames record the consumed-input index, the active states, and all relevant transition ids. This is a layer of all simultaneous possibilities, not one arbitrarily selected nondeterministic run. ε cycles terminate because closure deduplicates states.

Let `n` be the state count, `m` the transition count, and `w` the word length. Ignoring trace storage, the simulation takes `O((w+1)(n+m+n log n))` time in the straightforward worst case and `O(n+m)` working space. The `n log n` term is the explicit sort used to give each closure a stable canonical order; it can be removed with bitsets or timestamped state arrays if larger instances justify that optimization. For a DFA, active sets contain at most one state, so indexed transition work is linear in the input length after index construction. Recorded frames add their actual active-set and edge-id storage. A capped trace does not change the recognition result.

## Regex to NFA

Each AST node produces a fragment with one entry and one exit. Literals use one labeled edge; ε uses an ε edge; ∅ leaves entry and exit disconnected. Concatenation joins fragments, union adds an ε choice, and star adds an ε bypass and repetition path.

Structural induction on the AST shows that paths between the fragment endpoints recognize exactly the corresponding expression. This is the same inductive regular-language construction used in Sipser §1.3; the fragment organization is commonly called Thompson construction. See Ken Thompson, _Regular Expression Search Algorithm_, CACM 11(6), 1968, [DOI 10.1145/363347.363387](https://doi.org/10.1145/363347.363387).

For an expanded expression tree of size `s`, the construction has `O(s)` states, edges, time and space. The qualifier “expanded” matters: `+` is desugared, and a shared AST subtree may appear at more than one position. Work limits are checked while fragments are created.

## NFA to DFA

`determinize` interns ε-closed state subsets as sorted arrays. The initial subset is `E({q₀})`, and reading `a` maps a subset `S` to `E(δ(S,a))`. Reachable subsets are explored in breadth-first order. A subset is accepting if it intersects `F`. The empty subset is the explicit sink when reachable.

This is Sipser Theorem 1.39. The NFA execution invariant immediately proves the construction correct. Only reachable subsets are materialized, but some NFAs require exponentially many of them. A conversion cannot promise both a complete explicit DFA and polynomial worst-case output size.

If `r` reachable subsets are created and `k` is the alphabet size, there are exactly `kr` output transitions. The implementation spends at most `O(kr(n+m+n log n))` time in a conservative bound, with transition caching preventing recomputation of a subset/symbol pair. Stored subset members use `O(rn)` space in the worst case, in addition to `O(kr)` transitions. It separately caps state count, transition count and total stored subset memberships.

## DFA minimization

The algorithm first completes the DFA and removes unreachable states. It then refines an initial partition into accepting and rejecting states. For each selected splitter block and symbol, inverse transition lists identify the predecessor states that must be split off from their current blocks. A state-to-block array avoids searching for the affected block.

Blocks are sets. Removing a touched intersection costs time proportional to that intersection, without scanning the untouched remainder. The work queue schedules the smaller block unless both pieces are already required by a pending splitter. This detail is essential: repeatedly filtering an entire old block would make the implementation quadratic on simple chains even though the high-level algorithm was called Hopcroft.

No refinement separates language-equivalent states: each split is justified by a symbol leading into already distinguished blocks. At termination, states in a block have identical acceptance and lead to the same blocks on each symbol. Induction on word length proves that all states in one block recognize the same continuation language. Reachability ensures that the resulting quotient is the minimal complete DFA.

For an already deterministic input, completion and indexing cost `O(kn+m)`. Hopcroft refinement takes `O(kn log n)` expected time under the usual constant-time map/set-operation model and `O(kn+n)` space. An NFA input first pays for determinization. This is an implementation of the partition-refinement method described by John Hopcroft, _An n log n Algorithm for Minimizing States in a Finite Automaton_, Stanford report STAN-CS-71-190, 1971 ([original report](https://www.cs.cmu.edu/~cdm/resources/Hopcroft1971.pdf)).

## Automaton to regex

The converter first removes states that cannot lie on an accepting path. It then adds a new entry with an ε edge to the old start and a new exit with ε edges from all old accepting states. Parallel edges receive the union of their labels.

Removing state `k` updates every surviving label by

```text
R(i,j) := R(i,j) ∪ R(i,k) (R(k,k))* R(k,j).
```

The first term preserves paths that do not visit `k`; the second preserves paths entering `k`, looping there zero or more times, and leaving it. Repeating this invariant leaves one expression between the new entry and exit. This is Sipser Lemma 1.60 and Claim 1.65.

The adjacency map is sparse. `nfaToRegex` chooses the next state to remove by an exact printed-size estimate, and `nfaToRegexWithOrder` also returns the order of removal. The choice changes expression size and never correctness. Hash-consed expression nodes share repeated subexpressions. The implementation checks estimated printed size before allocating a potentially enormous final source string.

There are `O(n³)` potential label-update positions across elimination, but expression construction and flattening add their own cost. The final expression can be exponentially large. Neither the heuristic nor DAG sharing removes that worst-case output-size barrier. The converter stops with a resource-limit error instead of returning a truncated expression that recognizes the wrong language.

## Exact comparison and counterexamples

The comparison performs BFS on pairs of reachable ε-closed subsets. At every pair, it compares acceptance. A mismatch is a distinguishing word. Predecessor links reconstruct the word without storing a full copy on every queue node. BFS makes the returned witness shortest in token length. Ties follow the combined alphabet order.

If the queue empties without a mismatch, every word leads to a reachable pair whose components agree, so equivalence is proved. The complete explored product is a finite certificate in principle, although the current UI reports the visited-pair count and explanation rather than exporting that full certificate. If a limit is hit, the return value is `unknown`.

For two DFAs with `n₁,n₂` states and alphabet size `k`, this BFS has `O(k n₁ n₂)` worst-case time and `O(n₁ n₂)` pair storage, plus indices. For NFAs, reachable subset counts can be exponential. Each subset/symbol transition is cached independently on each side. The implementation uses this product search because it supplies a shortest explanatory witness; it does not claim it is the asymptotically fastest equivalence test for DFAs.

## Comparison backends

Several backends decide equivalence in `toc-toolkit/decisions/regular`. Hopcroft-Karp handles two DFAs, HKC handles DFAs, NFAs and regular expressions, and the derivative backend handles two regular expressions. Each is described in [HOPCROFT_KARP_EQUIVALENCE.md](HOPCROFT_KARP_EQUIVALENCE.md) or its package README. The breadth-first search of the previous section is `productSearch` in the same package, which also returns the shortest distinguishing word.

## Composition

Union, concatenation, star and reversal use linear-size NFA constructions. The construction rules are the same regular-language closure proofs that underlie the regex adapter. State ids are renamed before composition, preventing collisions between independently created objects.

Intersection and difference use the shared reachable subset-product engine. Complement first determinizes if necessary and completes the machine, then flips acceptance. Complement is relative to a declared finite alphabet. A regex's alphabet is inferred from its literal tokens: the complement of `∅` with no supplied alphabet is `{ε}`, not all words over an unspecified universe. To choose a larger universe, convert to an automaton and declare or complete that alphabet before complementing.

Literal collection precedes simplification: the complement of `a∅` is `a*`, because the source declares `{a}`. Automaton-to-regex conversion also preserves the machine's full declared alphabet. When state elimination omits unused symbols, the generated source includes a language-empty term such as `(b|"token")∅`. This term contributes no accepted words; it retains those tokens for a subsequent complement operation. A construction step explains this annotation, and its formatted length counts against the same output budget as the main expression. Empty-language machines receive the same treatment. No additional metadata or file-format change is required.

## Resource and error contract

The shared limits bound input/output states, transitions/configurations, execution steps, retained frames and elapsed work. Algorithms check time periodically and inside expensive loops. The surrounding worker can also be terminated immediately, which is necessary because a synchronous worker cannot receive a cooperative cancellation message while executing a long JavaScript loop.

The GNFA heuristic checks its time guard throughout the candidate-score scan, which can itself require quadratic graph queries.

- A completed simulation returns `accepted` or `rejected`.
- A simulation stopped before a conclusion returns `unknown` with its valid prefix trace.
- Complete regular comparison returns `equivalent` or `different`.
- Incomplete comparison returns `unknown`, never an empirical equivalence claim.
- A transformation that cannot finish stops with a limit error; it never masquerades as a complete conversion.
- Invalid mathematical objects are reported as issues that name the state or transition.
- Invalid expression syntax is separate from resource exhaustion.

Layout changes are semantically inert. Input, transition, accepting-state, start-state and alphabet changes require a fresh run. The application owns revision tracking and stale-worker-result rejection.
