Nested-count context-free grammar (source code)

= Nested-count context-free grammar

A <context-free grammar> can enforce several matched counts by nesting their dependencies. For example,
$$
S\to0S0\mid T,\qquad T\to1T0\mid\varepsilon
$$
generates the <context-free language> $\{0^n1^m0^{n+m}:n,m\geq0\}$. Applying the first recursive <production rule> $n$ times places $n$ zeros at both ends. Applying the second recursive <production rule> $m$ times places $m$ ones before the inner block and $m$ further zeros after it. Thus
$$
S\Rightarrow^*0^nT0^n\Rightarrow^*0^n1^mT0^{m+n}\Rightarrow0^n1^m0^{n+m}.
$$
Every terminal <grammar derivation> has this form, because it must switch from $S$ to $T$ exactly once. The nesting is useful: the final block records the sum of two independently chosen counts without requiring a <context-sensitive grammar>.