TOC Toolkit API - v0.1.0
    Preparing search index...

    TOC Playground — algorithms, data structures, and correctness boundaries

    TOC Playground is a formal-language workbench whose representations share mathematical engines. A regular expression can become an NFA, the NFA can become a grammar, and that grammar can become a PDA; the result of each supported conversion is another ordinary workspace object. Membership, comparison, composition, transformation, and explanation use these same representations. A conversion does not create an isolated visualization that cannot be used by the next operation.

    This document describes the implemented algorithms, their proof obligations, and practical limits. Detailed implementation chapters are linked where useful, but the main design and its limits are stated here.

    The course conventions follow Michael Sipser, Introduction to the Theory of Computation, third edition. The supplied book was inspected directly, including the definitions of NFA computation, CFG ambiguity and CNF, PDA computation and CFG/PDA equivalence, and the semi-infinite Turing-tape convention. Additional parser and implementation sources appear in the references.

    Every input word is an array of tokens. A token may be one Unicode code point or a quoted string such as "identifier". An empty array is the empty word. An ε transition has no read field; the literal token "ε" is an ordinary consumed symbol. Grammar ε is an empty right side. These distinctions survive conversion and interchange.

    The workbench makes three separate kinds of claim:

    Operation Completed result Incomplete or unresolved result
    Regular or CFG membership Accepted or rejected by an exact algorithm Unknown when a work limit prevents a decision
    PDA membership An accepting computation, a completely exhausted nonaccepting configuration graph, or a decision through an equivalent CFG Unknown when the practical simulation and grammar route cannot finish
    LBA and 2DFA membership A decision after an accepting path or complete closure of the finite marked-input configuration graph Unknown when a practical limit stops closure; 2DFA also supports exact DFA compilation
    TM, two-stack, queue membership An accepting computation, or a finite closed configuration graph with no accepting configuration Unknown when the search remains open at a resource limit
    Regular equivalence Equivalent through a completed exact backend, or different with a verified witness; completed product search certifies shortest length Unknown when all applicable exact routes reach their limits
    CFG/PDA equivalence Equivalent through a stated sufficient proof route, or different with a verified word or exact compact separator Unknown when those proof routes and the bounded search do not settle the question
    CFG ambiguity Ambiguous with a word and two trees; unambiguous only through an empty-language, LL(1) or LR(1) certificate Unknown after an inconclusive finite search

    General CFG equivalence and ambiguity are undecidable; general TM-equivalent machine membership is undecidable. A finite collection of successful test words does not override those boundaries. Conversely, a limit on an explanation does not erase a membership decision that has already been proved. A trace or explicit tree can be truncated while the decision remains accepted or rejected. [1, 5]

    An editor can contain missing DFA cells. A missing cell means a transition into an implicit rejecting sink, and validation reports it. A checked public DFA handle completes that sink explicitly. Complement therefore flips acceptance only after totalizing the transition function; flipping the visible accepting circles in an incomplete graph would be incorrect.

    Complement always has a finite alphabet universe. An automaton uses its declared alphabet, including unused symbols. A regex infers its alphabet from all source literal tokens before algebraic simplification, including literals in language-empty terms such as a∅. Thus the complement of regex ∅ with an empty inferred alphabet is {ε}. To complement over {a,b}, use a model that declares those symbols. Automaton-to-regex conversion retains otherwise absent alphabet symbols in explicit language-empty terms, so converting and then complementing preserves that universe. Binary regular operations use the union of the operands' alphabets.

    Persisted objects are serializable DTOs. A state has an identity independent of its displayed label and coordinates. Transitions refer to identities. A grammar has declared variable and terminal sets, a start variable, and identified productions with token-array right sides. Parsed expression ASTs and execution indexes are derived data.

    Fluent CFG source uses ordinary JSON quotes for terminals and explicit <"JSON-escaped name"> notation for variables whose names would be ambiguous. Familiar variable names remain bare. The grammar formatter and autocomplete share this representation, so names with spaces, arrows, quotes, or reserved epsilon aliases survive the source/editor roundtrip. A quoted terminal that looks like variable notation remains a terminal.

    The public domain layer turns DTOs into checked, immutable handles. Each algorithm then builds local mutable indexes appropriate to its task: adjacency maps, dense integer arrays, hash sets, queues, partition blocks, packed forests, or interned expression nodes. These local structures never become competing sources of persistent truth. The application's handles live in apps/web/src/domain.

    The regular routes share one adapter:

    flowchart TD
    R["Regex source"] --> T["Parsed formal expression"]
    T --> N["ε-NFA"]
    D["DFA"] --> N
    N --> M["Indexed membership"]
    N --> S["Reachable subsets"]
    S --> P["Exact product comparison"]
    S --> Q["DFA minimization"]
    N --> E["State elimination"]

    DFA and NFA share a representation and most implementation code, with different validation rules. Regex membership uses the NFA engine; there is no second recognizer based on JavaScript's RegExp. All nine regular-representation comparison combinations are supported by the regular portfolio. It includes Hopcroft–Karp for explicit DFAs, HKC for NFAs, and derivatives for regular expressions; exact subset-product search supplies shortest counterexamples when it completes. The procedures are in toc-toolkit/decisions/regular.

    CFG/PDA operations similarly share Earley recognition and the exact PDA/CFG conversions. A finite automaton becomes a right-linear CFG by making each state a variable, translating transitions into productions, and allowing accepting-state variables to derive ε. This permits regular and context-free objects to participate in the supported common operations without duplicate engines.

    The application dispatches CPU work to a worker through a promise-based client. React's scheduling is not treated as a substitute for a worker: a synchronous parsing loop would still occupy whichever thread invokes it. Worker request IDs, interruption, reference checks, and termination are described in Section 9 and docs/app/WORKER_LIFECYCLE.md.

    The expression grammar supports empty language, empty word, literal, union, concatenation, and star. + and ? are syntactic conveniences desugared into these constructors. Concatenation binds more tightly than union; postfix repetition binds more tightly than concatenation. Quoted tokens and escaped operators avoid lexical ambiguity.

    The parser builds n-ary union/concatenation nodes and interns equivalent structural nodes. It simplifies elementary identities such as R ∪ ∅ = R, εR = R, and (R*)* = R*. This is local algebra, not a canonical form for all regular languages. Two different ASTs can denote the same language; the automaton comparator decides that question.

    Source/output text is capped at 200,000 characters and nesting at 256 levels. Flattening and canonical union handling can be superlinear, so the implementation does not advertise the entire normalization path as a strictly linear parser. Fluent editing keeps incomplete draft text separately from the last valid mathematical model, and source parsing runs in the worker. Detailed notation is in REGULAR_ALGORITHMS.md.

    Each expression node produces an NFA fragment with one entry and one exit. A literal contributes a labeled edge; ε contributes an ε edge; ∅ leaves the endpoints disconnected. Concatenation links fragments, union adds a choice, and star adds bypass/repetition paths.

    Structural induction proves that the paths between a fragment's endpoints recognize the corresponding subexpression. For an expanded expression tree of size s, construction uses O(s) states, edges, time, and space. A shared subtree can be visited at multiple expression positions, so the bound is not stated only in terms of unique DAG nodes. Work limits are charged as fragments are created. [1, 2]

    The engine assigns dense integer indices to states, stores ε edges separately from token-indexed edges, and maintains the ε-closed active set after each consumed prefix. Each closure uses a work queue and visited set, so an ε cycle terminates without hiding any finite accepting run.

    The invariant is exact: the active set after prefix w[0..i) contains every state reachable by consuming that prefix and then taking finitely many ε moves. Acceptance after the final token is intersection with the accepting-state set. An empty active set is permanently rejecting.

    For n states, m edges, and input length w, a conservative worst-case bound is O((w+1)(n+m+n log n)); the sorting term comes from canonical state-set order. Working storage excluding trace is O(n+m). A DFA has at most one active state, so its indexed transition work is linear in the input length after preprocessing. Stored trace frames add their actual set and edge storage.

    Subset construction interns sorted ε-closed state sets and explores only reachable ones. Reading token a maps S to E(δ(S,a)). A subset accepts exactly when it contains an accepting NFA state. The empty subset is the rejecting sink when it is reachable. This follows the same invariant as direct NFA execution. [1, Theorem 1.39]

    If r subsets are reached and the alphabet has k symbols, the output has kr transitions. A conservative time bound is O(kr(n+m+n log n)), with O(rn+kr) output/index storage. Some NFAs require 2^n subsets; reachable-only construction improves ordinary examples without removing that output barrier.

    Minimization first completes the DFA and discards unreachable states. Hopcroft refinement maintains accepting/rejecting blocks, inverse transition lists, a state-to-block map, and a work queue of splitters. Only touched states are removed from a block; the untouched remainder is not repeatedly scanned. The smaller-block scheduling rule gives the usual O(kn log n) refinement bound under expected constant-time map/set operations. Space is O(kn+n). An NFA pays determinization cost first. [3]

    At termination, states in one block have the same acceptance and transition into the same blocks. Induction on continuation length proves they recognize the same right language. Reachability and complete refinement give a minimal complete DFA. An independent classic table-filling test checks the resulting minimality in generated tests.

    The comparison explores pairs of reachable ε-closed subsets. It tests acceptance at every pair and caches each side's subset transitions independently. A mismatch gives a distinguishing word. Parent pointers reconstruct that word; breadth-first order makes it shortest in token count, including an empty-word witness when the starts disagree.

    If the queue empties, every reachable pair agrees. Every word leads to one such pair, which proves equivalence. If a resource limit interrupts exploration, the result is unknown. The finite word-length setting used by CFG heuristics does not limit this exact regular search.

    For complete DFAs with n₁,n₂ states and alphabet size k, product exploration takes O(k n₁ n₂) time and O(n₁ n₂) pair storage, plus indexes. Missing-cell sinks are included in those effective state counts. NFAs can have exponentially many reachable subsets. The product method is chosen partly because it produces a shortest explanatory witness; the implementation does not claim the fastest possible DFA equivalence algorithm.

    State elimination first removes states that cannot lie on an accepting path, adds a fresh entry/exit, and unions parallel labels. Eliminating q updates surviving labels using

    [ R_{ij}\leftarrow R_{ij}\cup R_{iq}(R_{qq})^*R_{qj}. ]

    The old term represents paths avoiding q; the added term represents entering q, looping there, then leaving. The sparse adjacency map and a degree/label-weight heuristic reduce many intermediate expressions. Interning shares repeated expression structure, and a printed-size estimate is checked before a huge output is materialized.

    There are O(n³) possible label-update positions, but manipulating expressions costs more than a constant per update. The final expression may be exponentially large. A limit therefore aborts a conversion rather than returning a shortened expression with a different language. [1, Lemma 1.60 and Claim 1.65]

    Union, concatenation, star, and reversal use linear-size NFA closure constructions. State IDs are renamed before joining independent objects. Intersection and difference use the reachable subset-product engine with different acceptance predicates. Complement totalizes and then flips acceptance over the declared alphabet. These operations return ordinary automata, which can immediately be simulated, compared, minimized, converted, or composed again.

    For a CFG and a regular language, the grammar product records the DFA states before and after each variable. Quotients also record where the retained part of a word meets the part read by the DFA. Shuffle inserts DFA path variables between grammar symbols. A homomorphism substitutes each terminal by its image, including an empty image. Its inverse uses a PDA that reads one input letter and then simulates its complete image. Each construction is charged to the caller's budget.

    Earley recognizes the student's original CFG, including ε rules and left recursion. It avoids imposing CNF merely to ask whether a word belongs, and its dotted items naturally support an explanatory chart. CYK would be a reasonable alternative for a CNF grammar, but would make the conversion and reconstruction of original derivations part of every ordinary membership operation. No claim is made that this Earley implementation is optimal for every grammar family. [4, 6]

    An item stores a production, dot position, origin, and current chart position. Charts use deduplicated maps and append-only work agendas. Indexes identify items waiting for each variable. Prediction occurs once per variable per chart, and each completed (variable, origin, end) span joins its waiting parents once. Extra completing productions add forest alternatives instead of repeating those joins.

    Nullable completion must work in both orders: a completion advances existing waiters, and a new waiter consults already completed empty spans. This avoids a common loss of parses with several adjacent nullable variables.

    For input length n and g total dotted production positions, there are O(g n²) items and a conservative O(g n³) worst-case recognition time under unit-cost token/map assumptions. Chart storage is O(g n²). Text keys and trace serialization add their stored-text costs. The implementation does not include Leo optimization or claim linear recognition for every deterministic grammar.

    The recognizer builds terminal nodes, production-prefix intermediate nodes, and variable/span symbol nodes. Packed families retain alternative derivations without copying complete trees. Chart-item deduplication therefore does not discard ambiguity. The forest may use O(g n³) packed-family storage in the worst case.

    Forests can be cyclic: S → S | ε has infinitely many distinct finite parse trees for ε. The extractor computes a bounded fixed point of the smallest distinct finite trees. Each symbol adds one vertex; intermediate nodes concatenate fragments. Keeping k+1 candidates reveals whether more than the requested k trees exist. A parent worklist propagates improvements.

    Tree vertices are interned by their local label, production, span, and child identities. Candidate equality no longer repeatedly serializes entire nested trees. The optimization preserves structural tree identity and changes only tie order among equally sized trees.

    At most 16 explicit trees are requested per call. Budget charges bound tree size, stored candidates, combinations, interned nodes and edges, and time. A tree that exceeds the budget stops expansion, and the word keeps its decision and flat packed forest with a tree-truncation explanation. Even a small grammar can require an enormous explicit tree, so enumeration is not advertised as an unbounded polynomial operation.

    CNF follows Sipser's convention: A → BC, A → a, and optionally a fresh start rule S0 → ε; the start variable never occurs on a right side. The converter records each stage:

    1. Protect the start and remove useless symbols.
    2. Replace terminals in long right sides with shared singleton variables.
    3. Binarize long right sides, sharing equal suffixes through bottom-up pair interning.
    4. Compute nullable variables and generate omission variants.
    5. Close unit-production reachability and copy the reached non-unit rules.
    6. Remove unproductive and unreachable definitions.

    Binarization comes before nullable omission. A length-40 rule with independent nullable occurrences therefore does not enumerate all 2^40 subsets. Each binary rule has at most four omission variants. Before unit closure, transformed size is linear in the original total production length; unit closure can yield quadratic output. The simple fixed-point analyses and pruning keep the construction polynomial, with additional variable factors in the straightforward implementation. [1, Definition 2.8 and Theorem 2.9]

    GNF starts from protected-start CNF, temporarily sets aside start ε, substitutes earlier leading variables in a fixed order, and removes direct left recursion with a helper for nonempty repetition. For example, A → Aα | β becomes the corresponding A → β | βR, R → α | αR family. The head-dependency graph is then acyclic, allowing leading variables to be expanded until a terminal appears first. Remaining symbols are variables; the possible start ε is restored.

    The implementation checks the GNF invariant before returning. Substitution can greatly increase the output grammar. This particular construction does not promise a polynomial-size or human-minimal result. On a limit, it reports an incomplete conversion instead of exposing a partial grammar as equivalent. [7]

    The comparison tries sufficient proof routes, then searches for a counterexample:

    • Both start languages are empty by productivity.
    • A start-preserving variable bijection maps the complete production sets exactly.
    • Unit/useless-symbol elimination or CNF normalization exposes such an isomorphism.
    • Both grammars are uniformly left-linear or right-linear, permitting exact NFA comparison.
    • Both normalized dependency graphs are acyclic, permitting complete finite-language enumeration within the budget.
    • Otherwise, increasing-length word enumeration checks exact membership on both sides and returns the first mismatch.

    Color refinement is only a pruning device for grammar isomorphism. Every successful full bijection is checked against the actual deduplicated production sets. Graphs with identical refinement colors can still fail that final check. Terminal tokens are never renamed.

    The left-linear adapter reverses right-side token order to obtain a right-linear construction, then reverses all NFA edges. A multi-character token remains atomic. A mixture of arbitrary left and right recursion is not assumed regular.

    Finite-language enumeration only claims completeness for acyclic dependencies. JSON token-array keys distinguish, for example, the one-token word ["ab"] from the two-token word ["a","b"]. Storage is charged while intermediate Cartesian prefixes are being created, not just when an entire production finishes. A long fixed prefix followed by many choices cannot evade the token budget.

    PDA operands are converted once to CFGs and passed through the proven readability rewrites before comparison. This can expose a compact structural proof without changing other conversion paths. A readability limit retains an earlier equivalent checkpoint; if preparation throws a limit error, comparison uses the exact raw grammar. The initial independent equal-block PDA comparison improved from unknown to verified isomorphism through this preparation; no finite test was promoted into a proof.

    The orbit procedure of toc-toolkit/decisions/context-free adds an explicit rewrite search after the other procedures decline. It prepares each operand once, applies the bounded readability portfolio to both CFGs, and attempts a complete start-preserving grammar isomorphism. A successful mapping is checked again by a separate linear structural verifier and attached with both normalized CFGs. This is a structural certificate after trusted language-preserving normalization, not a replay certificate for the entire normalization history. A non-isomorphic pair remains unknown; structural mismatch cannot establish different languages. Standard comparison behavior is unchanged. The additional operation divides one monotonic remaining-time budget across preparation, initial comparison, both normalizations, and final isomorphism.

    This architecture is inspired by the supplied Schmellenkamp et al. paper: normalize, look for structural equivalence, and seek useful counterexamples. The library implements parts of the toolbox. toc-toolkit/isomorphism canonicalizes encoded grammars, and decideParikhSeparation and decideBounded compare exact count images by semilinear covers (see CFG_BOUNDED_ARITHMETIC.md). toc-toolkit/arithmetic decides Presburger formulas, but no grammar procedure calls it. The library does not implement the paper's transformation DSL, corpus cache or boundedness-witness procedure. [5]

    FIRST, FOLLOW, nullable, productive, and reachable sets are computed by finite fixed points. The end of input is marked by a flag (followEnd) and not by a token, so a declared terminal cannot collide with parser metadata.

    An LL(1) predictive table or an LR(1) automaton with no conflicts provides a sufficient unambiguity certificate. An empty language is also unambiguous. Otherwise, the search enumerates words and asks for two distinct parse trees. A concrete pair proves ambiguity in Sipser's sense of different leftmost derivations. LL(1) conflicts alone do not prove ambiguity, and failing to find two trees does not prove unambiguity. Inherent ambiguity of a language is not decided. [1, Definition 2.7]

    The CFG construction uses a one-state empty-stack PDA. Start with the grammar's start variable on the stack. A production expands the top variable through an ε transition; a terminal transition reads and pops the same terminal. Whole-input empty-stack acceptance corresponds exactly to a completed leftmost derivation. Top-of-stack is index zero, so the first right-side symbol is pushed first in the represented top-first word. Construction takes O(P+T+R) time/space for P productions, T terminals, and total right-side length R. [1, Lemma 2.21]

    Generalized input conventions are first normalized: arbitrary initial stacks, no-pop actions, multi-symbol pushes, and final-state/empty-stack acceptance. A fresh protected bottom marker represents the original empty stack. A no-pop transition is expanded for every possible top symbol; it does not become an incorrect empty-stack test. Long pushes pass through private states and are reduced to pop-one/push-at-most-two transitions.

    A return variable [p,A,q] generates exactly the words that remove A while moving from p to q, leaving the stack below it untouched. A normalized move reading a, popping A, and moving to r yields:

    Push Production
    Nothing [p,A,r] → a
    B [p,A,q] → a[r,B,q]
    BC [p,A,q] → a[r,B,s][s,C,q] for the possible intermediate states s

    The leading a is omitted for an ε-input move. The two-push case is exact because B must be removed before C becomes accessible. Decomposing a finite run gives a derivation; induction over a derivation reconstructs the corresponding run.

    The implementation first computes productive return summaries by a dependency worklist, then emits only productive rules reachable from the overall return. It does not eagerly allocate every theoretical triple. For a normalized PDA with N states, stack alphabet size G, and D transitions, there are at most N²G summaries and O(DN²) possible productions. The indexed saturation has worst-case O(DN²+N²G) time and O(DN+N²G) space before reachable rule materialization. Normalization additionally pays for possible stack tops and total push length. [Source: MACHINE_ALGORITHMS.md; relation to Sipser Lemma 2.27 is explained there.]

    The raw construction is mathematically useful but can expose many auxiliaries. The readability pass removes useless symbols and unit scaffolding, merges variables under a stable structural bisimulation, inlines suitable non-self-recursive equations, factors profitable shared context, and folds a narrowly checked commuting recursive context. It preserves the raw grammar, intermediate models, source-production origins, and exact variable-language origins.

    The merge proof is induction on the least-fixed-point approximants of the grammar equations: variables in a stable class have the same polynomial in the class languages, beginning at the empty language. Inlining substitutes a defining equation that does not mention its own variable. A fresh-variable factor expands back to the original alternatives. None of these rules concludes equality from sampled words or inspects a generator's state-name convention.

    A further rule reuses an existing variable's complete definition. If A ≠ B and the alternatives of A contain every uβv for β in the current definition of B, that entire copied subset can become uBv, leaving B unchanged. At any full-language fixed point, distributivity and the unchanged B equation make the old and new A equations equal. The systems therefore have exactly the same fixed points and the same least one, even when B depends recursively on A. Matching must include ε alternatives and use one exact common context. The implementation requires a strict cost reduction and skips an empty prefix-plus-suffix context to avoid repeated unit-elimination churn.

    All of these guarantees concern the language. They do not imply a bijection of parse trees or preservation of ambiguity. Ambiguity is analyzed on the grammar actually selected by the student; it is not transferred from an earlier representation solely because the languages are equal.

    The recursive context rule checks literal commutation and finite base-set inclusions. If B=C∪F(B) with F(X)=⋃pᵢXqᵢ, then the wrapper uBv can be absorbed into an owner's equation only under the stated commutation/base conditions. This recovers common shifted helpers such as S→aB|ε, B→aBb|b, yielding S→aSb|ε.

    The selection score is 4 × variables + 2 × productions + right-side symbols. It is a local preference, not a minimum-grammar theorem or a universal measure of pedagogy. A named category can be easier to teach even when inlining it decreases that score. The smallest visited valid checkpoint is retained if a later rewrite expands the grammar or the search reaches a limit.

    The optional Simplify further action compares three completed paths: the classical baseline, algebraic-plus-finite-derivation search, and a separate path that first includes exact complete-product factoring. All start from the original grammar and share one parent time/work/candidate budget. The first advanced path receives at most half the remaining allowance; the second uses the actual remainder. Selection uses the complete concrete CFG cost and retains the baseline on ties. This protects against a locally useful factor leading to a worse final result than ordinary simplification. It still does not find a globally minimum grammar.

    A mathematically equivalent grammar need not reproduce the original variable names or presentation. A checker result of unknown is retained when its sufficient proof routes cannot recover the expected relationship. Raw and readable grammars remain inspectable so the conversion itself is reviewable.

    An e-graph can retain many alternatives justified by a chosen set of equality rules and extract one under a cost model. It does not supply correct CFG equality rules or resolve undecidability. Recursive grammar variables denote least solutions, so binding, recursion, and those semantics must survive the encoding. Congruence alone is insufficient justification for an arbitrary replacement of recursive equations.

    The ordinary readability pass uses explicit bounded rewrite rules with provenance. An optional extended search adds a small TypeScript equality-saturation kernel for CFG right-side expressions, with opaque variable atoms and only pointwise language-semiring identities. It does not bundle the Rust egg runtime or infer arbitrary equality of recursive grammar variables. Factored expressions are lowered through fresh acyclic helpers and accepted only after their complete CFG cost is checked. Exact complete-product factoring supplies a separate candidate generator; its proposed finite polynomials are fully re-expanded and checked. The portfolio keeps the cheapest completed classical, unseeded advanced, or seeded advanced path under one shared budget. Finite-derivation deletion is another sufficient rule with a replayable production/position certificate. The explicit additional comparison operation can use these trusted language-preserving outputs before a verified structural proof; the e-graph itself is not a CFG equivalence oracle. The rewriting rules are in toc-toolkit/grammars/rewriting. [8]

    These engines explore complete configurations, not just control states. A configuration contains the input position plus stack(s) or queue; a TM configuration contains the head and all nonblank tape cells. State-indexed transitions avoid rescanning unrelated moves. Exact configuration keys prevent a repeated full configuration from creating an infinite duplicate search.

    Breadth-first exploration is fair: one infinite branch cannot starve a shorter accepting computation. Parent links reconstruct a real accepting path with its transition IDs. PDA, queue, and two-stack acceptance requires complete input consumption. A TM accepts when it enters an accepting state, even if its head has not inspected every original cell.

    The TM tape is semi-infinite to the right; a left move from cell zero stays there. Accept/reject states halt, and a missing transition halts that branch without accepting. Stay-put moves are an explicit convenience. Multiple choices are permitted and visibly treated nondeterministically.

    Exhausting a finite closed reachable configuration graph proves nonmembership, even if a branch loops. The explanation does not claim every original branch halted. If the frontier remains open at a depth, count, time, or memory bound, the result is unknown. For a PDA only, an unknown direct simulation can be followed by exact CFG membership; the displayed bounded machine trace is then labeled separately from the grammar-based decision.

    For C stored configurations, E inspected outgoing moves, and maximum represented memory size M, stack/queue copying and exact keys cost conservatively O(EM) time and O(CM) space. Tape key construction sorts nonblank addresses, adding a logarithmic factor. These describe bounded work; C itself can grow exponentially with search depth, and there is no general decision algorithm for the TM-equivalent models.

    Symbols in this table are local to each row. Bounds assume ordinary expected constant-time map/set access and unit-cost token identities; retained textual labels and explanations add their actual storage/serialization costs.

    Operation Main structures Cost or unavoidable growth
    Regex → NFA Interned AST, Thompson fragments Linear in expanded AST size
    NFA membership Token adjacency, ε adjacency, active sets O((w+1)(n+m+n log n)) conservative time; O(n+m) working space
    NFA → DFA Interned subsets and cached transitions Output-sensitive in reachable subsets; up to 2^n
    DFA minimization Inverse edges, block sets, state-to-block array O(kn log n) refinement after completion; O(kn+n) space
    Regular equivalence BFS subset pairs, predecessor links DFA case O(k n₁ n₂); NFA subset growth can be exponential
    Automaton → regex Sparse GNFA labels, interned expression DAG Cubic label-update positions, potentially exponential expression output
    Earley recognition Charts, agendas, waiting/completion indexes O(g n³) conservative time, O(g n²) chart storage
    Packed forest Symbol/prefix nodes, packed families Up to O(g n³) family storage; explicit enumeration separately bounded
    CFG → CNF Nullable/productive sets, binary helpers, unit closure Polynomial construction; quadratic output can occur
    CFG → GNF Ordered substitution and recursion helpers Output-sensitive growth; this construction has no small-output guarantee
    CFG isomorphism Joint color refinement, verified backtracking Worst-case exponential search, with exact final checking
    CFG counterexample search Length-ordered words and Earley calls Up to 1+k+…+k^L words before caps; agreement is not equality
    CFG → PDA Production-expansion and terminal-match transitions O(P+T+R)
    Normalized PDA → CFG Productive return summaries and dependencies O(DN²+N²G) saturation time, with O(DN²) potential output rules
    Memory-machine search BFS configurations, exact keys, parent links Bounded-run O(EM) or tape O(EM log(M+1)); configuration growth unrestricted

    None of the exponential or undecidable cases is hidden by framework terminology. The system keeps the UI responsive by moving work off-thread and lets the user stop it; it does not promise that every mathematical output can be made small or computed quickly.

    Normal core budgets are 500 execution steps, 20,000 configurations, 2,048 states, 12,000 productions, 8,000 ms, 600 trace frames, 10,000 search words, and searched word length at most eight. Operations use the limits relevant to them: Earley does not interpret the machine-step cap as a parse-depth bound. Stack, queue and tape entries that a search stores are charged as cells, 1,000,000 by default. Source, output text, tree, schema, and sharing limits are stated in their respective chapters.

    Transformations return a complete result with the requested semantics or a typed failure. Representation conversions preserve the language; complement and reversal deliberately compute a different requested language operation. The readability pass has a heuristic target: an earlier equivalent checkpoint is still a valid complete result of a bounded readability search. Exact searches and simulations report unknown when interrupted before a mathematical conclusion. A bounded trace, however, cannot change an already proved answer.

    compute<K> ties a worker job's input and output through JobMap. An injected WorkerFactory supplies the port. Every exit, which is a result, a failure, a timeout, or a cancelled abort signal, removes the listeners and terminates the worker. Termination can stop a non-yielding synchronous loop; a posted cancel message by itself could not be processed until that loop yielded.

    The outer default deadline is twice the requested core time allowance plus 3,000 ms. Individual adapter stages may have their own core guards; the worker deadline supplies an end-to-end cap. The worker checks each model before an algorithm reads it. Algorithm proofs and independent tests establish mathematical correctness.

    The additional readability portfolio and the orbit procedure also share remaining time explicitly across their internal phases. Portfolio work and candidate accounting flow through one parent ledger; comparison phases retain their ordinary per-algorithm structure caps.

    One job owns one worker. This favors simple hard cancellation and stale-result isolation over worker-pool startup reuse. UI rendering, layout, and structured cloning still have costs; worker use is not a blanket animation-rate guarantee. docs/app/WORKER_LIFECYCLE.md, and apps/web/src/worker/WorkerClient.ts.]

    1. Michael Sipser, Introduction to the Theory of Computation, third edition. Supplied PDF inspected. Chapters 1–3 provide the model and construction conventions; Definition 2.7 states ambiguity, Definition 2.8 and Theorem 2.9 state CNF, and Section 2.2 gives PDA/CFG equivalence.
    2. Ken Thompson, Regular Expression Search Algorithm, CACM 11(6), 1968.
    3. John Hopcroft, An n log n Algorithm for Minimizing States in a Finite Automaton, Stanford report STAN-CS-71-190, 1971.
    4. Jay Earley, An Efficient Context-Free Parsing Algorithm, CACM 13(2), 1970.
    5. Marko Schmellenkamp et al., Detecting and explaining (in)equivalence of context-free grammars, 2024. Supplied paper inspected; the implementation boundary is stated in Section 5 above.
    6. Andreas Opedal et al., Efficient Semiring-Weighted Earley Parsing, ACL 2023. Used as a modern primary reference for Earley deduction and shared-completion efficiency; weighted parsing is not implemented here.
    7. Sheila A. Greibach, A New Normal-Form Theorem for Context-Free Phrase Structure Grammars, JACM 12(1), 1965.
    8. Max Willsey et al., egg: Fast and Extensible Equality Saturation, POPL 2021. Background for the optional bounded TypeScript RHS e-graph; it is not a CFG-equivalence oracle or the Rust egg runtime.

    Implementation-specific details: regular algorithms, CFG algorithms, memory machines, docs/app/WORKER_LIFECYCLE.md, docs/app/INTERCHANGE.md, and docs/app/PERSISTENCE.md.