# Context-free language implementation notes

This document describes the context-free algorithms of TOC Playground. The grammar model is in [`toc-toolkit/grammars/context-free`](../subjects/grammars-context-free.md), recognition in [`toc-toolkit/grammars/parsing`](../subjects/grammars-parsing.md), transformations in [`toc-toolkit/grammars/rewriting`](../subjects/grammars-rewriting.md) and the comparison and ambiguity procedures in [`toc-toolkit/decisions/context-free`](../subjects/decisions-context-free.md). The input and output types are plain serializable data. Functions do not mutate their arguments. Expensive calls belong in the computation worker.

## Model and notation

A grammar has declared `variables`, declared `terminals`, one `start` variable, and productions with a stable `id`, a single variable `lhs`, and a token-array `rhs`. An empty `rhs` means the empty word. Variables and terminals must be disjoint. Duplicate structural productions are a set: repeating a row does not manufacture ambiguity. Production IDs are presentation/provenance identifiers, not mathematical alternatives.

The fluent input parser accepts `A -> A a | b | epsilon`, Unicode `→` and `ε`, the alias `eps`, and compact conventional input such as `S -> aSb | ε`. All left sides are collected before right sides are scanned. Longest declared-variable matching permits variables such as `Expr`, `A1`, and `S₀`. Other unquoted characters are Unicode code-point terminals. JSON-quoted strings denote a single terminal, including tokens such as `"identifier"`, `"|"`, or a literal `"ε"`. Only **unquoted** epsilon notation means an empty right side. `∅` as a whole alternative means no production, and permits textual representation of an empty-language variable. The structured editor can build the same arrays directly.

In a context-sensitive or unrestricted grammar a bare name on a left side is still one symbol, so `CB -> BC` declares a variable called `CB`. `packedLeftSideIssues` of `toc-toolkit/grammars/syntax` warns when the text spells the code points of such a name as symbols elsewhere, and its fix writes the symbols apart with the terminals quoted, as in `C B` and `"a" B` (D230). A context-free grammar gets no warning, because its left side is one variable.

`formatGrammar` quotes every terminal so that terminal text cannot be confused with a variable or operator. This text format preserves the grammar language and start variable, while a JSON workspace export additionally preserves IDs, unused alphabet declarations, and UI metadata.

An explicit variable reference is a JSON string inside angle brackets, such as `<"A name">` or `<"[p,A,q]">`. It is accepted on either side of a production and must refer to a declared variable. `formatGrammarVariable` leaves familiar identifiers bare and uses this notation for reserved aliases or names containing spaces/operators. This preserves arbitrary validated variable identities, including embedded quotes, arrows, backslashes, and escaped newlines. A bare whole `eps`/`epsilon` refers to that exact declared variable when present; otherwise it retains its empty-word meaning. The explicit glyph ε remains the empty-word notation.

## Earley recognition

`parseEarley(cfg, word, budget, options)` of `toc-toolkit/grammars/parsing` recognizes arbitrary CFGs directly. It does not require CNF, so students see their original variables and productions throughout the trace.

An item contains a production index, a dot position, an origin input position, and its current chart position. A chart is a `Map` keyed by production/dot/origin, with a separate append-only work agenda. Indexes identify items awaiting each variable. Each variable is predicted at most once per chart. A completed `(variable, origin, end)` span is joined to its waiting parents once. Additional completing productions contribute packed alternatives to the shared symbol node instead of repeating those joins.

The nullable case needs both directions. Completion advances existing waiters. When a new waiter appears after a nullable completion at the same chart position, the predictor also consults the completed-span set. This prevents the common bug where a grammar such as `S → A A A`, `A → ε | a` loses parses.

A successful completed augmented-start item at the final input position proves membership. Exhausting all finite Earley items without that item proves nonmembership. A resource limit before either conclusion yields `unknown`. If a complete derivation has already been recognized when trace construction reaches a limit, membership remains proved and the trace is marked truncated.

Let `n` be the token count and `g` the total number of production positions. Recognition has `O(g n²)` items. With indexed and shared completion, its conservative worst-case time is `O(g n³)` under the usual constant-time token and map assumptions. Prediction and scanning are smaller terms. Chart storage is `O(g n²)`. This implementation does not claim Leo optimization or linear time for every deterministic grammar. String-key construction and trace serialization add costs proportional to their stored text.

## Shared forest and multiple trees

The recognizer optionally builds a finite shared packed forest with three node kinds:

- A terminal node represents one consumed token.
- An intermediate node represents a production prefix and points to its earlier prefix and final child.
- A symbol node represents one variable over one input span. Its families identify the completed production and prefix node.

Families are deduplicated independently from Earley items. Their references remain live even when more alternatives are later discovered. Thus a deduplicated chart does not discard ambiguity. Packed families can require `O(g n³)` space in the worst case even though the item count is quadratic.

A forest can have cycles. For example, `S → S | ε` has infinitely many trees for the empty word but finitely many chart and packed nodes. The tree enumerator computes the smallest distinct finite unfoldings by a bounded fixed point. Each symbol node adds one parse-tree vertex; intermediate nodes concatenate child fragments. At each forest node it retains the best `k + 1` distinct candidates, ordered by tree size with stable interned identities breaking ties. The extra candidate tells the UI that more than `k` trees exist. A parent worklist propagates improvements. Every genuine recursive unfolding adds a symbol vertex, so this method can expose ambiguity from epsilon cycles instead of suppressing all repeated nodes.

Each immutable output-tree vertex is interned by its symbol, span, production ID, and child identities. A candidate fragment is a list of those identities. Equality checks therefore inspect a local production-sized key instead of repeatedly serializing entire nested trees. Equal vertices share their child objects internally; the output remains a finite serializable tree/DAG with no object cycles. This optimization preserves structural tree identity and distinct derivations; it changes only the tie order among equal-size trees.

Only nodes reachable from the accepted root are enumerated. At most 16 explicit trees are requested in one call. The packed forest remains available for further inspection. The extraction charges fuel and cells to the `Budget` for combination expansions, tree vertices, retained candidates and interned vertices and edges, and it checks the clock. Such bounds matter because even a small acyclic grammar can have one exponentially large explicit tree. Recognition can therefore return `accepted` while reporting that explicit tree expansion stopped. It must not pretend that a tree limit means rejection or uniqueness.

For extraction costs, let `K ≤ 17` be the retained candidate count and `r` the maximum original right-side length. A binary packed-family visit combines at most `K²` candidate pairs. Fragment copying/identity keys have length at most `r`; sorting its candidate products adds a `log K` factor. A node with `f` families also deduplicates and sorts at most `O(fK)` finished candidates. Thus work is proportional to the actual family visits and worklist relaxations, including their local key/trim costs. It is deliberately not advertised as a polynomial bound on enumerating all parses: there can be exponentially many parses, infinitely many cyclic unfoldings, or an exponentially large smallest explicit tree. The finite budgets apply even in those cases.

Tree production IDs, child symbols, child spans, and terminal yields are checked in tests. Two different orders of expanding the same parse tree are not treated as ambiguity. This matches Sipser’s Definition 2.7, which uses distinct leftmost derivations.

A tree that exceeds the budget stops expansion while the completed membership decision and the flat packed forest stay available.

## FIRST, FOLLOW, and ambiguity

`Cfg.analyze` computes nullable, productive, and reachable variables, FIRST sets, FOLLOW sets, and predictive-table conflicts by finite fixed points. It allocates no end-marker symbol. The array `followEnd` marks the variables whose FOLLOW set holds the end of input, so a terminal that the grammar declares cannot collide with the marker.

FIRST/FOLLOW sets can retain `O(VT)` variable/token entries and the predictive table can retain `O(PT)` production/lookahead associations, for `V` variables, `P` productions, and `T` lookahead tokens including end-of-input. The analysis charges the entries that it retains to its `Budget` before it inserts them, so a short unit-chain grammar cannot create an unbounded variable/terminal matrix. When the budget runs out, the analysis stops with an exhaustion, and the decision procedures report that instead of certifying a partial table.

The ambiguity procedure of `toc-toolkit/decisions/context-free` has three sound outcomes:

1. `unambiguous` when productivity proves the language empty, or when the FIRST/FOLLOW predictive table has no LL(1) conflicts.
2. `ambiguous` when one concrete word has two distinct verified finite parse trees. The word and trees are returned.
3. `unknown` otherwise, with the number of tested words, the fully checked length bound, and the stopping reason.

A conflict in the LL(1) table is not itself an ambiguity proof. An unambiguous grammar can require more than one lookahead symbol. Likewise, testing finitely many words without finding ambiguity never proves unambiguity. The current implementation does not decide inherent ambiguity of a language.

Words are enumerated by increasing token length, then deterministic alphabet order, without retaining an exponentially large BFS queue. If `s` is the alphabet size and `L` the length cap, the potential count is `1 + s + … + s^L`; the `Resource.Words` limit and the aggregate deadline cap actual work. Each tested word invokes the same recognizer and forest implementation used by ordinary membership.

## Chomsky normal form

`Cfg.toCnf` produces exactly Sipser’s convention: `A → B C`, `A → a`, and optionally `S0 → ε`, where `S0` is the new start variable, with the start variable absent from every right side. The conversion records its intermediate grammar after each named stage.

The stages use the transformations in Sipser’s proof of Theorem 2.9, with binarization moved earlier to control growth:

1. Introduce a fresh protected start and remove obviously useless symbols.
2. Lift terminals inside long right sides into shared singleton variables.
3. Binarize long right sides. Bottom-up pair interning shares equal suffixes without repeatedly copying full suffix strings.
4. Compute nullable variables and add omission variants. Each rule now has at most two symbols, so it has at most four variants.
5. Compute each variable’s unit-reachability closure and copy reachable non-unit rules.
6. Remove nonproductive and unreachable variables.

Every stage preserves the start language. Early binarization prevents the `2^r` nullable-subset expansion of a long rule with `r` nullable occurrences. Before unit closure the transformed size is linear in the original production length. Unit closure can create a quadratic number of rules in that size. The simple fixed-point analyses and per-variable reachability searches are polynomial; output limits still apply because a quadratic grammar can be large. Empty languages are represented by a start variable with no productions.

## Greibach normal form

`Cfg.toGnf` first obtains the protected-start CNF grammar. It temporarily separates the possible start epsilon rule. It orders the remaining variables, substitutes earlier leading variables, and eliminates direct left recursion with an auxiliary variable for a **nonempty** repetition. For example, the mechanism replacing `A → A α | β` uses `A → β | β R` and `R → α | α R`. It introduces no new epsilon production.

After ordered elimination, a head-dependency graph is acyclic. Resolving that graph exposes a terminal at the beginning of every nonempty production. Remaining symbols are variables. The saved start epsilon rule is then restored, and useless variables are removed. An explicit invariant check validates the result.

Substitution can greatly increase the output grammar. The implementation is output-sensitive and budgeted; it does not claim a polynomial-size GNF for this particular construction or a guaranteed small interactive result for every grammar. A limit aborts the conversion instead of returning a partial grammar disguised as equivalent output.

## Equivalence and the supplied paper

The equivalence question on two grammars, answered by the procedures of `toc-toolkit/decisions/context-free`, is a **sound partial decision procedure**, not a solution to general CFG equivalence. It implements these proof-producing routes:

- Both languages are empty by productivity.
- A start-preserving variable bijection maps the production sets exactly.
- Unit/useless-symbol elimination or CNF normalization produces such an isomorphism.
- Both grammars are uniformly right-linear or left-linear, allowing exact NFA comparison.
- Both normalized variable-dependency graphs are acyclic and their entire finite languages can be enumerated within the budget.

The isomorphism search uses joint color refinement, including outgoing productions and incoming occurrences, to reduce candidate mappings. Colors are only a pruning device. Every successful bijection is checked against the actual complete production sets. An exponential worst-case search remains possible and is explicitly bounded.

For linear grammars, a production contributes a path between variable states and a final state. A left-linear grammar is reversed to a right-linear one; reversing the resulting automaton restores the original language. Mixed left/right recursion is not assumed regular.

If proof routes do not settle the comparison, length-ordered enumeration searches for a word accepted by exactly one grammar. Such a witness proves difference. No witness within a finite bound yields `unknown`, never equality.

The exact acyclic-language route budgets completed languages and both live intermediate prefix maps during each Cartesian-product step. A long fixed prefix followed by many short alternatives therefore cannot evade the aggregate token-storage limit until the entire production finishes. Linear-grammar conversion counts its extra accepting state before creating any terminal transitions, including for epsilon/unit-only grammars.

This follows the **architecture** of Schmellenkamp et al. (2024), especially their combination of normalization, grammar isomorphism, and counterexamples. The library implements parts of their toolbox. `toc-toolkit/isomorphism` computes canonical forms and renamings of coloured graphs, which the isomorphism and orbit procedures use on encoded grammars. `decideParikhSeparation` and `decideBounded` compare exact count images by semilinear covers, as described in [CFG_BOUNDED_ARITHMETIC.md](CFG_BOUNDED_ARITHMETIC.md). `toc-toolkit/arithmetic` decides Presburger formulas, but no grammar procedure calls it. The library does **not** reproduce their transformation DSL, corpus cache or boundedness-witness search.

## References

- Michael Sipser, _Introduction to the Theory of Computation_, 3rd edition, Chapter 2. Definition 2.7 (p. 108) fixes ambiguity; Definition 2.8 and Theorem 2.9 (pp. 109–110) fix the CNF convention and transformations. The supplied PDF was the source inspected.
- Jay Earley, [An Efficient Context-Free Parsing Algorithm](https://doi.org/10.1145/362007.362035), _Communications of the ACM_ 13(2), 1970, pp. 94–102.
- Andreas Opedal et al., [Efficient Semiring-Weighted Earley Parsing](https://arxiv.org/abs/2307.02982), ACL 2023. This provides a modern primary reference for Earley deduction and shared-completion efficiency. TOC Playground is unweighted and does not implement the paper’s semiring or grammar-automaton features.
- Sheila A. Greibach, [A New Normal-Form Theorem for Context-Free Phrase Structure Grammars](https://doi.org/10.1145/321250.321254), _Journal of the ACM_ 12(1), 1965, pp. 42–52.
- Marko Schmellenkamp et al., [Detecting and explaining (in)equivalence of context-free grammars](https://arxiv.org/html/2407.18220v1), 2024, especially Sections 2–4.
