Reference articles on history, science, culture and more
Encyclopedia

Left recursion

Theory of computer sciences

In the formal language theory of computer science, left recursion is a special case of recursion where a string is recognized as part of a language by the fact that it decomposes into a string from that same language (on the left) and a suffix (on the right). For instance, 1+2+3 can be recognized as a sum because it can be broken into 1+2, also a sum, and {}+3, a suitable suffix.

In terms of context-free grammar, a nonterminal is left-recursive if the leftmost symbol in one of its productions is itself (in the case of direct left recursion) or can be made itself by some sequence of substitutions (in the case of indirect left recursion).

01Definition

A grammar is left-recursive if and only if there exists a nonterminal symbol A that can derive to a sentential form with itself as the leftmost symbol. Symbolically,

A\Rightarrow ^{+}A\alpha,

where \Rightarrow ^{+} indicates the operation of making one or more substitutions, and \alpha is any sequence of terminal and nonterminal symbols.

Direct left recursion

Direct left recursion occurs when the definition can be satisfied with only one substitution. It requires a rule of the form

A\to A\alpha

where \alpha is a sequence of nonterminals and terminals . For example, the rule

{\mathit {Expression}}\to {\mathit {Expression}}+{\mathit {Term}}

is directly left-recursive. A left-to-right recursive descent parser for this rule might look like

void Expression() { Expression(); match('+'); Term(); }

and such code would fall into infinite recursion when executed.

Indirect left recursion

Indirect left recursion occurs when the definition of left recursion is satisfied via several substitutions. It entails a set of rules following the pattern

A_{0}\to \beta _{0}A_{1}\alpha _{0}
A_{1}\to \beta _{1}A_{2}\alpha _{1}
\cdots
A_{n}\to \beta _{n}A_{0}\alpha _{n}

where \beta _{0},\beta _{1},\ldots ,\beta _{n} are sequences that can each yield the empty string, while \alpha _{0},\alpha _{1},\ldots ,\alpha _{n} may be any sequences of terminal and nonterminal symbols at all. Note that these sequences may be empty. The derivation

A_{0}\Rightarrow \beta _{0}A_{1}\alpha _{0}\Rightarrow ^{+}A_{1}\alpha _{0}\Rightarrow \beta _{1}A_{2}\alpha _{1}\alpha _{0}\Rightarrow ^{+}\cdots \Rightarrow ^{+}A_{0}\alpha _{n}\dots \alpha _{1}\alpha _{0}

then gives A_{0} as leftmost in its final sentential form.

Left-recursive parsing of a double subtraction
Left-recursive parsing of a double subtraction

02Uses

Left recursion is commonly used as an idiom for making operations left-associative: that an expression a+b-c-d+e is evaluated as (((a+b)-c)-d)+e. In this case, that evaluation order could be achieved as a matter of syntax via the three grammatical rules

{\mathit {Expression}}\to {\mathit {Term}}
{\mathit {Expression}}\to {\mathit {Expression}}+{\mathit {Term}}
{\mathit {Expression}}\to {\mathit {Expression}}-{\mathit {Term}}

These only allow parsing the {\mathit {Expression}} a+b-c-d+e as consisting of the {\mathit {Expression}} a+b-c-d and {\mathit {Term}} e, where a+b-c-d in turn consists of the {\mathit {Expression}} a+b-c and {\mathit {Term}} d, while a+b-c consists of the {\mathit {Expression}} a+b and {\mathit {Term}} c, etc.

03Removing left recursion

Left recursion often poses problems for parsers, either because it leads them into infinite recursion (as in the case of most top-down parsers) or because they expect rules in a normal form that forbids it (as in the case of many bottom-up parsers). Therefore, a grammar is often preprocessed to eliminate the left recursion.

Removing direct left recursion

The general algorithm to remove direct left recursion follows. Several improvements to this method have been made. For a left-recursive nonterminal A, discard any rules of the form A\rightarrow A and consider those that remain:

A\rightarrow A\alpha _{1}\mid \ldots \mid A\alpha _{n}\mid \beta _{1}\mid \ldots \mid \beta _{m}

where:

  • each \alpha is a nonempty sequence of nonterminals and terminals, and
  • each \beta is a sequence of nonterminals and terminals that does not start with A.

Replace these with two sets of productions, one set for A:

A\rightarrow \beta _{1}A^{\prime }\mid \ldots \mid \beta _{m}A^{\prime }

and another set for the fresh nonterminal A' (often called the "tail" or the "rest"):

A^{\prime }\rightarrow \alpha _{1}A^{\prime }\mid \ldots \mid \alpha _{n}A^{\prime }\mid \epsilon

Repeat this process until no direct left recursion remains.

As an example, consider the rule set

{\mathit {Expression}}\rightarrow {\mathit {Expression}}+{\mathit {Expression}}\mid {\mathit {Integer}}\mid {\mathit {String}}

This could be rewritten to avoid left recursion as

{\mathit {Expression}}\rightarrow {\mathit {Integer}}\,{\mathit {Expression}}'\mid {\mathit {String}}\,{\mathit {Expression}}'
{\mathit {Expression}}'\rightarrow {}+{\mathit {Expression}}{\text{ }}{\mathit {Expression}}'\mid \epsilon

Removing all left recursion

The above process can be extended to eliminate all left recursion, by first converting indirect left recursion to direct left recursion on the highest numbered nonterminal in a cycle.

Inputs A grammar: a set of nonterminals A_{1},\ldots ,A_{n} and their productions
Output A modified grammar generating the same language but without left recursion
  1. For each nonterminal A_{i}:
    1. Repeat until an iteration leaves the grammar unchanged:
      1. For each rule A_{i}\rightarrow \alpha _{i}, the \alpha _{i} being a sequence of terminals and nonterminals:
        1. If \alpha _{i} begins with a nonterminal A_{j} and j<i:
          1. Let \beta _{i} be \alpha _{i} without its leading A_{j}.
          2. Remove the rule A_{i}\rightarrow \alpha _{i}.
          3. For each rule A_{j}\rightarrow \alpha _{j}:
            1. Add the rule A_{i}\rightarrow \alpha _{j}\beta _{i}.
    2. Remove direct left recursion for A_{i} as described above.

Step 1.1.1 amounts to expanding the initial nonterminal A_{j} in the right hand side of some rule A_{i}\to A_{j}\beta, but only if j<i. If A_{i}\to A_{j}\beta was one step in a cycle of productions giving rise to a left recursion, then this has shortened that cycle by one step, but often at the price of increasing the number of rules.

The algorithm may be viewed as establishing a topological ordering on nonterminals: afterwards there can only be a rule A_{i}\to A_{j}\beta if j>i. Note that this algorithm is highly sensitive to the nonterminal ordering; optimizations often focus on choosing this ordering well.

Right-recursive parsing of a double subtraction
Right-recursive parsing of a double subtraction

04Pitfalls

Although the above transformations preserve the language generated by a grammar, they may change the parse trees that witness strings' recognition. With suitable bookkeeping, tree rewriting can recover the originals, but if this step is omitted, the differences may change the semantics of a parse.

Associativity is particularly vulnerable; left-associative operators typically appear in right-associative-like arrangements under the new grammar. For example, starting with this grammar:

{\mathit {Expression}}\rightarrow {\mathit {Expression}}\,-\,{\mathit {Term}}\mid {\mathit {Term}}
{\mathit {Term}}\rightarrow {\mathit {Term}}\,*\,{\mathit {Factor}}\mid {\mathit {Factor}}
{\mathit {Factor}}\rightarrow ({\mathit {Expression}})\mid {\mathit {Integer}}

the standard transformations to remove left recursion yield the following:

{\mathit {Expression}}\rightarrow {\mathit {Term}}\ {\mathit {Expression}}'
{\mathit {Expression}}'\rightarrow {}-{\mathit {Term}}\ {\mathit {Expression}}'\mid \epsilon
{\mathit {Term}}\rightarrow {\mathit {Factor}}\ {\mathit {Term}}'
{\mathit {Term}}'\rightarrow {}*{\mathit {Factor}}\ {\mathit {Term}}'\mid \epsilon
{\mathit {Factor}}\rightarrow ({\mathit {Expression}})\mid {\mathit {Integer}}

Parsing the string "1 - 2 - 3" with the first grammar in an LALR parser (which can handle left-recursive grammars) would have resulted in the parse tree:

This parse tree groups the terms on the left, giving the correct semantics (1 - 2) - 3.

Parsing with the second grammar gives

which, properly interpreted, signifies 1 + (-2 + (-3)), also correct, but less faithful to the input and much harder to implement for some operators. Notice how terms to the right appear deeper in the tree, much as a right-recursive grammar would arrange them for 1 - (2 - 3).

05Accommodating left recursion in top-down parsing

A formal grammar that contains left recursion cannot be parsed by a LL(k)-parser or other naive recursive descent parser unless it is converted to a weakly equivalent right-recursive form. In contrast, left recursion is preferred for LALR parsers because it results in lower stack usage than right recursion. However, more sophisticated top-down parsers can implement general context-free grammars by use of curtailment. In 2006, Frost and Hafiz described an algorithm which accommodates ambiguous grammars with direct left-recursive production rules. That algorithm was extended to a complete parsing algorithm to accommodate indirect as well as direct left recursion in polynomial time, and to generate compact polynomial-size representations of the potentially exponential number of parse trees for highly ambiguous grammars by Frost, Hafiz and Callaghan in 2007. The authors then implemented the algorithm as a set of parser combinators written in the Haskell programming language.

Watch videos about Left recursionExplainers and documentaries on YouTube (opens in a new tab)

Sources and credits

This article is adapted from the Wikipedia article Left recursion, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.

Images, from Wikimedia Commons:

Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.