# Exact arithmetic and bounded CFG comparison

This document describes the arithmetic that the library uses to compare context-free grammars with infinite languages. It separates what is implemented from what the theory offers. The implemented parts are the Presburger arithmetic package, the Parikh formula of a grammar, the exact comparison of count images in a bounded envelope, and the separation of two grammars by a count vector. Resource exhaustion is always an explicit result, never a negative logical answer.

The motivating example is equality of two descriptions of

\[
\{a^n b^m:n\ge m\ge0\}.
\]

`S -> a S b | a S | ε` and `T -> A B; A -> a A | ε; B -> a B b | ε` have different syntax and infinite languages, so no finite sample proves their equality. Both grammars stay inside the envelope `a* b*`, where a word is determined by its exponent vector. The procedure compares the two exact sets of exponent vectors.

## What the library implements

| Part                        | Package and file                                                                              | What it does                                                                                                                  |
| --------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Presburger arithmetic       | [`toc-toolkit/arithmetic`](../subjects/arithmetic.md)                                         | Decides integer formulas with the Cooper and Omega backends, and cross-checks one against the other (`decideSatisfiability`). |
| Parikh formula of a grammar | `src/decisions/context-free/parikh/formula.ts`                                                | Builds the existential formula of the count vectors that a grammar generates (`parikhFormula`).                               |
| Bounded equality            | `src/decisions/context-free/bounded` (`decideBounded`, `boundedProcedure`)                    | Proves two grammars equal inside a common envelope, by exact semilinear covers of their count images.                         |
| Parikh separation           | `src/decisions/context-free/parikh` (`decideParikhSeparation`, `parikhSeparationProcedure`)   | Proves two grammars different by a count vector that only one of their images contains.                                       |
| Independent checks          | `toc-toolkit/verification` (`CertificateKind.Semilinear`, `CertificateKind.ParikhSeparation`) | Replays the covers and the separating vector without the producing procedures.                                                |

The decision procedures solve the count equations of the grammar directly as semilinear sets. `decideBounded` accepts a backend as its third argument, with Cooper as the default. Its default proof uses exact covers. A selected alternative backend tests the symmetric difference of the images before that proof, and a fourth backend requests independent corroboration. Agreement that the difference is empty yields `CrossChecked` trust without a certificate. `decideParikhSeparation` accepts the same backend arguments and tests membership of its proposed separating vector in the target image. A disagreement declines the procedure, so the scheduler can return `Unknown`.

The Parikh formula is also available as data, and the application dumps it for inspection. Completed formulas are shared for the same reference grammar, formula pool and coordinate identities. A changed coordinate map is checked again and gets its own formula.

## Exact CFG count formulas

For a production `p`, let `y_p` denote its number of uses. The formula requires `y_p >= 0`. For each nonterminal `A`, it imposes

\[
[A=S]+\sum_p |\operatorname{rhs}(p)|_A y_p
-\sum_{\operatorname{lhs}(p)=A}y_p=0.
\]

For each terminal `a`, its coordinate satisfies

\[
x_a=\sum_p |\operatorname{rhs}(p)|_a y_p.
\]

These equations are insufficient on their own. For example, `S -> a; A -> A b` admits a disconnected positive circulation at `A`, despite no accepted word containing `b`. The formula therefore also requires every used nonterminal to be reachable from the start through productions with a positive count. Balance and this connected support characterize the count vectors of complete derivations, by the communication-free Petri-net result restated as Theorem 3 by Verma, Seidl and Schwentick. Their Theorem 4 applies it to CFG Parikh images. [1]

The formula expresses connectivity with one fresh rank variable for each nonterminal (`formula-ranks.ts`). A nonterminal with a positive use count needs an incoming used production from a parent of smaller rank, and the start has no such requirement. Production counts and ranks are existentially bound, and only the terminal coordinates are free.

## Presburger arithmetic

The arithmetic domain is the integers, and terms and coefficients are `bigint` values. Equalities, inequalities, divisibility, their negations, Boolean combinations and nested quantifiers are supported by the Cooper backend. Equality systems are reduced by Hermite integer row operations before elimination. The Omega backend decides existential formulas and projects alternating quantifiers when equality pivots or one side of each inequality projection have unit coefficients. It declines the other quantified projections. `decideSatisfiability` runs one backend, replays its model on the quantifier-free form, and checks an unsatisfiable answer with the second backend.

For one quantified variable, the Cooper step first makes its coefficients unit-sized by scaling the variable and adding the necessary divisibility constraint. It then considers a finite set of residue classes at lower-bound boundaries and a case below every boundary. This removes the quantified variable while preserving all parameter values. [2] The solver reconstructs free-variable assignments by reversing the recorded elimination steps, and it evaluates the final model against the quantifier-free formula.

Neither formula construction nor elimination is assumed cheap. A new formula charges its depth to the fuel of its `Budget`, which replaces the fixed depth cap of 1000. An exhausted budget is not a negative logical result.

## Distinct-letter envelopes

For distinct atomic terminals `a1,...,ak`, each word in `a1*...ak*` is determined by its count vector. Once both grammars generate only words of that envelope, equality of their count images is equivalent to equality of their languages.

`commonOrder` (`bounded/discover.ts`) looks for one order of the terminals that suits both grammars. It removes useless rules, computes the terminals that each useful variable can produce, and derives precedence edges between terminals that occur in separate, ordered components of a right side. A cycle prevents a global order, and a topological order supplies one. Useful reduction matters because unreachable or unproductive productions impose no constraint on accepted words. Every unary grammar has the one-letter envelope.

When no common order exists, `comparePhaseEnvelopes` tries the two three-phase envelopes `a* b* a*` and `b* a* b*` over the two tokens that the grammars use. It builds a canonical phase grammar for each operand, and that grammar gives each greedy phase of a word its own coordinate. This applies only when the grammars use exactly two tokens. The result carries a `GreedyPhaseEncoding` so that the checker can rebuild the coordinates.

## Periodic word bounds

`discoverWordBounds` reads literal runs from useful productions and computes their primitive roots with the prefix failure function. Roots follow a traversal of the productions in derivation order, with a reversed order as another candidate. The proposals include `(ab)*c*` and `a*(bc)*` for the corresponding recursive presentations.

`proveWordBound` builds an automaton for the proposed envelope and proves that the whole grammar lies inside it with a `RegularInvariant` certificate. A false bound fails this containment test. After both operands have proved containment, `decideBounded` tries the existing induction prover and returns its independently checked certificate on success.

`envelopeEquality` accepts arbitrary supplied nonempty words `w1,...,wk`. It proves both original languages are inside `w1*...wk*`, then uses a typed port to construct each inverse image under `h(t_i)=w_i` and intersect it with `t1*...tk*`. Equality of the ordered inverse images is equivalent to equality of the original bounded languages. This holds when words overlap or repeat because every decomposition is present in the inverse image. Distinct token counts determine the ordered token word.

The `Semilinear` body retains the words, fresh tokens and both construction frames per operand. Its independent checker rebuilds the regular word envelope, computes original grammar transition relations to prove containment, verifies each construction frame and binds its terminal map and ordered monitor. It then checks the count covers over the ordered inverse images. A separating vector gives a compressed word in the `OriginalWord` form of `BlockExponents`. Its checker expands that word when the budget permits and replays membership in both original grammars.

`recognizeBounded` tries the proposed periodic bounds and can also prove unboundedness from two direct noncommuting loops on the same side of the start variable and a terminal base rule. Two loops on opposite sides do not meet that condition. The union of `{a^n b^n}` and `{b^n a^n}` is bounded by `a*b*a*`. Other unproved cases return `Unknown`, so this is an incomplete recognizer.

## Exact count images and covers

`solveImage` computes the exact count image of every variable as a semilinear set, which is a finite union of sets `base + n1 p1 + ... + nm pm` with nonnegative integer coefficients. It processes the dependency components in order, so a component sees the solved images of everything it depends on. A single variable with recursive rules uses the star of the loop contributions. A component of several variables with linear rules is solved by elimination of the coefficient matrix. A component with a nonlinear recursive rule across several variables is outside the supported shape, and the procedure declines with `ContextFreeReason.UnsupportedBoundedScc`.

`coverImage` then proves that every linear set of one image lies in the other image. It searches for a cover by components and records each step. If the procedure completes both directions, the two images are equal and the grammars are equal on the envelope. If it finds no cover, it declines with `ContextFreeReason.NoSemilinearCover`. The answer of the procedure is `Equivalent` only, and a failed cover gives no claim of inequality.

## Parikh separation

`decideParikhSeparation` computes the count images of the two grammars over their common alphabet and searches for a vector that one image contains and the other does not. A separating vector proves that the word languages differ, and the checker verifies the vector without the producing code. Equal count images alone prove nothing about the word languages, because `{ab}` and `{ba}` have equal images. The procedure therefore answers `Different` only and gives no concrete word.

## What the library does not implement

- A complete boundedness recognizer. A grammar outside the proposed word bounds and direct same-side pumping cases gives an inconclusive result.

## Results and budgets

The registered procedures answer through the `decide` scheduler. `decideBounded` is decided as equivalent, declined or exhausted. `decideParikhSeparation` is decided as different, declined or exhausted. A declined result says that the grammars fall outside the supported shape, and an exhausted result says that a resource limit stopped the work. The explicit facade `equivalentInEnvelope` supplies the construction port for `envelopeEquality` and returns its outcome.

The sampling limit `Resource.Words` does not constrain these exact proofs. The limits that apply are the fuel, cells, time, state and production limits of the `Budget`. Original-word compressed witness replay also charges `Resource.WordLength` before expansion.

## Primary references

1. Kumar Neeraj Verma, Helmut Seidl and Thomas Schwentick. **On the Complexity of Equational Horn Clauses.** CADE 2005, 337–352. Section 3, especially Theorems 3 and 4. [Author PDF](https://www2.in.tum.de/bib/files/Verma05Complexity.pdf). The rank variables of the formula follow the idea of the paper's linear-size rank encoding, and the library makes no claim about the size bound of the paper.
2. D. C. Cooper. **Theorem Proving in Arithmetic without Multiplication.** _Machine Intelligence 7_, 91–99, 1972. [Primary paper](https://www21.in.tum.de/teaching/logik/SS16/Exercises/Cooper.pdf).

The broader historical decidability results and the remaining roadmap are in [CFG equivalence research](CFG_EQUIVALENCE_RESEARCH.md). The implemented procedures use standard exact reductions and are not new decidability theorems.
