# TOC Playground: memory machines and grammar conversion

This document describes the memory-machine and grammar-conversion algorithms. The breadth-first search that simulates every machine kind is in [`toc-toolkit/machines`](../subjects/machines.md) (`search` and `compileMachine`), together with the machine models. The PDA conversions are in [`toc-toolkit/machines/pushdown`](../subjects/machines-pushdown.md), and the conversions that involve Turing machines are in [`toc-toolkit/machines/turing`](../subjects/machines-turing.md). The membership algorithms take token arrays. The interface can turn a character string into Unicode code points or accept whitespace-separated tokens; the algorithms do not assume that a symbol occupies one UTF-16 code unit.

## Mathematical conventions

The PDA model follows Sipser, _Introduction to the Theory of Computation_, third edition, Definition 2.13 and the computation definition on pages 113–114. Input ε and stack ε are separate choices. A transition that does not pop is applicable to every stack, including the empty stack. It does **not** test that the stack is empty. An explicit bottom marker is how the examples test for emptiness.

The implementation also accepts an initial stack and a word pushed by one transition. These are compact, explicitly defined macros for ordinary PDA operations. They do not increase computational power. The PDA-to-CFG conversion expands them correctly before applying its return-summary construction.

| Machine           | Memory                                             | Transition                                                                                     | Acceptance                                                                       |
| ----------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| PDA               | One stack; index 0 is the top                      | Optionally read input; optionally pop one matching symbol; prepend a word                      | All input consumed, and either an accepting state or an empty stack, as selected |
| Two-stack machine | Two stacks, both top-first                         | Optionally read input; independently pop and push on both stacks in the same transition        | All input consumed in an accepting state                                         |
| Queue machine     | FIFO word; index 0 is the front                    | Optionally read input; optionally dequeue one matching front symbol; append a word at the rear | All input consumed in an accepting state                                         |
| Turing machine    | Semi-infinite tape indexed by nonnegative integers | Read one tape symbol, write one, move L, R, or S                                               | Enter an accepting state                                                         |

A queue dequeue of ε leaves the queue unchanged before appending. It is not an empty-queue test. The two stack operations happen together, so both required pops must be available before either stack changes.

The Turing tape uses Sipser's Definition 3.3 and its following computation convention. Input starts at cell 0, the head starts at cell 0, and an L move from cell 0 stays there. Blank cells extend to the right. `S` is supported as an explicit stay-put convenience. Accept and reject states halt. Missing transitions halt that branch without accepting. Multiple transitions with the same state and read symbol are allowed, with a visible nondeterminism warning; the simulator explores them fairly. The interface is not claiming that nondeterministic Turing machines have a decidable general membership problem.

## Bounded simulation

### Configurations, rather than control states

A PDA configuration consists of its state, input position, and entire stack. A two-stack configuration contains both stacks. A queue configuration contains the queue. A Turing configuration contains its state, head position, and every nonblank tape cell. These components determine all future behavior.

The simulator stores configurations in a breadth-first search queue and an exact visited map. Transitions are indexed by their source state. A visited key contains the entire configuration, rather than a hash used without equality checking. Blank tape cells are omitted and tape entries are sorted by address, so writing a blank cannot create a false new configuration.

Breadth-first search discovers an accepting computation with the fewest transitions among all computations within the resource allowance. In particular, an infinite branch cannot starve a shorter accepting branch. Each stored node has its parent index. Following these pointers reconstructs an actual computation, including the specific transition used at each step.

Acceptance requires the **whole** input for PDA, two-stack, and queue machines. Reaching an accepting state early does not accept a suffix that has not been read. A Turing machine instead accepts on entering its accepting state; its tape head need not have visited every original input cell.

### Three possible answers

- **Accepted:** a finite accepting computation has been found. The returned witness and trace show that computation.
- **Rejected:** all reachable configurations have been explored, and none accepts, or an input token is outside the declared alphabet. The reachable graph may contain cycles. A repeated full configuration can certify that a branch never accepts even if that branch does not halt.
- **Unknown** (the `Exhausted` status of a run): a time, depth, configuration or memory allowance was reached while the search remained open. This is not rejection and is not evidence that the machine runs forever.

The distinction concerns membership in the language. When a complete finite configuration graph contains a loop but no accepting state, the explanation explicitly says that some branches may loop. It does not claim that the original machine halted and rejected.

### Trace representation

Accepted runs show a single real accepting path. Other runs show the breadth-first frontier after each transition count. A frontier may contain configurations that have consumed different amounts of input because ε moves do not advance the input. `frontierSize` gives the full number of configurations, and a `SearchFrame` holds at most 24 of them for rendering.

A long trace may be summarized independently of the decision. `isTruncated` of the trace marks this, and the explanation states how many intermediate configurations were omitted. A truncated trace does not change a proven acceptance or finite-graph rejection into an unknown result.

### Resource and complexity bounds

The defaults of `DEFAULT_LIMITS` in `toc-toolkit/foundation` are 20,000 configurations, 8,000 ms of time, 600 trace frames, 2,048 states, 12,000 productions and 1,000,000 stored cells. The cells count the stack, queue and tape entries that the search retains. The step bound of a run is a separate option of the application, which uses 500 steps, and it fixes the fuel at the step bound times the configuration limit. A caller passes its own `Limits` to lower or raise any of them.

Let `C` be the number of visited configurations, `E` the transitions inspected from those configurations, and `M` the maximum represented memory size. For stacks and queues, copying memory and forming an exact key cost `O(M)` per successor. The resulting bound is `O(E M)` time and `O(C M)` space. For tapes, sorting the nonblank cells adds `O(M log M)` to key construction, giving the conservative bound `O(E M log(M+1))`. An index by source state avoids scanning transitions from unrelated states.

These are bounds on a **bounded run**, not a polynomial-time algorithm for general language membership. The number of configurations can grow exponentially with the permitted depth. A PDA has a separate decidable membership path: convert it to a CFG and invoke the grammar engine. That conversion can itself exceed a practical work allowance; the UI must retain the unknown result in that case.

## CFG to PDA

This uses the usual leftmost-derivation construction behind Sipser's Lemma 2.21, pages 117–120, represented as a one-state empty-stack PDA.

1. Put the grammar's start variable on the initial stack.
2. For every production `A → X₁ … Xₖ`, add an ε transition that pops `A` and pushes `[X₁, …, Xₖ]` with `X₁` on top.
3. For every terminal `a`, add a transition that reads `a` and pops `a`.
4. Accept when the whole input has been consumed and the stack is empty.

The invariant is that the already consumed input followed by the current stack is a sentential form of the grammar, using the simulated leftmost derivation. Expanding a top variable applies the next production. Matching a top terminal transfers that terminal from the pending sentential form into the consumed prefix. Thus an empty stack at the input end exists exactly when the grammar derives the input word.

For a grammar with `P` productions, `T` terminals, and total right-hand-side length `R`, the construction takes `O(P + T + R)` time and space. It creates one state and `P + T` transitions. Simulation of the resulting machine need not be fast on a left-recursive or highly ambiguous grammar. Use Earley recognition when the goal is membership; use the PDA view to study an actual computation.

## PDA to CFG

### 1. Normalize the machine

Choose a fresh bottom marker `⊥` that is not already a stack symbol. A new start state begins with `[⊥]` and loads the original initial stack above it.

For final-state acceptance, each original accepting state may enter a new drain state. The drain removes the remaining stack, then removes `⊥` and enters a new finish state. These moves consume no input, so entering the drain before the input end cannot accept unread input.

For empty-stack acceptance, each original control state may remove `⊥` and enter the new finish state. This move is available exactly when the original stack is empty.

Next, replace a no-pop transition by one transition for each possible top symbol `A`: pop `A` and push the original replacement word followed by `A`. This includes the protected bottom marker. The original empty stack is represented by that marker, so no case is lost.

Finally, split each push longer than two symbols into transitions through fresh private states. The first move pushes the last two symbols. Each following move prepends the preceding symbol while preserving the current top. The first move reads the original input symbol; the remaining moves read ε. Private intermediate states cannot interleave other operations. Every resulting transition pops exactly one symbol and pushes zero, one, or two.

### 2. Define return variables

For each relevant triple `(p,A,q)`, create a variable `[p,A,q]`. It generates the input strings that remove `A` while moving from state `p` to state `q`, without changing the stack below `A`.

A normalized transition from `p` that reads `a`, pops `A`, and moves to `r` gives one of these rule families. Here `a` is omitted when the transition reads ε.

| Pushed word | Grammar rule                                                  |
| ----------- | ------------------------------------------------------------- |
| ε           | `[p,A,r] → a`                                                 |
| `B`         | `[p,A,q] → a [r,B,q]`                                         |
| `BC`        | `[p,A,q] → a [r,B,s] [s,C,q]` for each intermediate state `s` |

The start variable represents removing the protected bottom from the new start to the new finish.

**Why the rules are exact.** A zero-push transition removes `A` immediately. A one-push transition must subsequently remove `B`. A two-push transition must remove `B` before it can remove `C`; the state where the first removal finishes is the intermediate state `s`. Decomposing a finite computation this way gives a grammar derivation. Conversely, induction over a grammar derivation concatenates exactly these valid computations. The untouched suffix is preserved at every step.

This is the standard return-variable formulation of PDA/CFG equivalence. It has the same semantic goal as Sipser's Lemma 2.27, pages 121–125, but uses `[p,A,q]` variables rather than his empty-stack `[p,q]` construction. It is useful here because it avoids enumerating a separate state sequence of length equal to an arbitrary pushed word.

### 3. Compute productivity before creating rules

The code does not eagerly allocate every possible triple. It first finds productive return summaries by a finite least-fixed-point computation. Zero-push transitions seed the worklist. One-push and two-push transitions register dependencies. Discovering a first return for a two-symbol push registers a dependency on the second return. Each new productive triple is processed once.

This computes exactly those triples for which some finite input word effects the return. Cyclic dependencies with no terminating return do not become productive. A pure ε cycle cannot create a language accidentally.

The code then starts at the required overall return and creates only productive rules and reachable variables. Unreachable and unproductive branches never appear in the output grammar. If the overall return is not productive, the result is a valid grammar with its start variable and no productions, representing the empty language.

### Cost of the construction

Let the normalized PDA have `N` states, stack alphabet size `G`, and `D` transitions. There are at most `N²G` productive triples. With the indexed dependency worklist, productivity uses `O(D N² + N²G)` time in the worst case and `O(DN + N²G)` space. Materializing rules uses at most `O(D N²)` productions, with the same order of generation work. The actual output can be much smaller because productivity and reachability are applied first.

For the original generalized PDA, normalization cost depends on the sum of push lengths and on the number of possible stack tops for no-pop transitions. No-pop operations may acquire `G+1` alternatives. Each push of length `k > 2` adds `k-2` private states. These costs are charged before constructing the grammar; no exponential dependence on the original push length is hidden in an enumeration of state sequences.

The default limits cap normalized states at 2,048, grammar productions at 12,000 and productive summaries at 20,000 configurations. Waiting dependencies for the second half of a two-symbol push can have a separate cap of cells, which the caller passes and which is charged before each new entry. This matters when many first returns finish but the second symbol is unproductive: the dependency map can grow even while the count of productive summaries remains small. Exceeding a cap exhausts the `Budget`, and the conversion reports the exhaustion as a failed result. No partial grammar is presented as equivalent to the input.

## Example machines

- The PDA for `aⁿbⁿ` pushes once per `a`, then pops once per `b`. The protected marker ensures that both counts finish together.
- The Turing-machine decider for `aⁿbⁿ` marks a matched pair as `X` and `Y`, returns to the marked prefix, and repeats. It checks that only marked `b` symbols remain before accepting.
- The two-stack machine for `aⁿbⁿcⁿ` counts the `a` symbols on the first stack, transfers the count to the second stack while reading `b`, and removes it while reading `c`.
- The queue machine for `ww` guesses the midpoint. It stores the first half, moves the protected front marker to the rear, then consumes the second half against the queue in order.

All four accept the empty word.
