Reading a Small Recursive Grammar

A recursive grammar can describe arbitrarily deep nested structures using a limited set of production rules.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Build a concrete sentence
  2. Map the rule to a procedure
  3. Build a derivation using the recursive alternatives
  4. Check where a recognizer must consume input

Build a concrete sentence

If \(S\) may become the empty string or become an opening parenthesis followed by \(S\) and a closing parenthesis, the language includes empty, (), and (()). It does not generate ()() with this rule alone. Context-free grammars provide the formal vocabulary.

Map the rule to a procedure

A generator can add one enclosing pair per supplied depth and stop at zero. A parser for this narrow grammar can check one enclosing pair and recurse on the inside. Choosing a base case ensures the empty structure is accepted deliberately.[1]

Build a derivation using the recursive alternatives

Take the grammar where \(S\) can be empty or \(aSb\). Applying the second choice twice and then the empty choice derives aabb. The leading a and trailing b occur as matching pairs. A string with balanced counts in another order, such as abab, cannot be produced by this grammar. See matched delimiters.

S → a S b
  → a a S b b
  → a a b b
The innermost S derives the empty string

Check where a recognizer must consume input

A recursive rule that calls itself immediately at the same input position can cause a direct recursive-descent parser to repeat without progress. Test the smallest accepted input and a nearly valid word with one unmatched symbol. Keep recognition and grammar derivation distinct.

References

  1. Jeff Erickson, Algorithms ↩