Lably
Skip to content

Left recursion

Theory of computer sciences

  • 5 min read
  • 5 chapters

Related on Lably

Through Computer science, Recursion (computer science) and Context-free grammar

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).

Definition

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⇒+Aα,

where ⇒+ indicates the operation of making one or more substitutions, and α 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→Aα

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

Expression→Expression+Term

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

<span id="mwLQ"></span><span class="kt" id="mwLg">void</span><span class="w" id="mwLw"> </span><span class="nf" id="mwMA">Expression</span><span class="p" id="mwMQ">()</span><span class="w" id="mwMg"> </span><span class="p" id="mwMw">{</span> <span class="w" id="mwNA"> </span><span class="n" id="mwNQ">Expression</span><span class="p" id="mwNg">();</span> <span class="w" id="mwNw"> </span><span class="n" id="mwOA">match</span><span class="p" id="mwOQ">(</span><span class="sc" id="mwOg">'+'</span><span class="p" id="mwOw">);</span> <span class="w" id="mwPA"> </span><span class="n" id="mwPQ">Term</span><span class="p" id="mwPg">();</span> <span class="p" id="mwPw">}</span>

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

A0→β0A1α0
A1→β1A2α1
⋯
An→βnA0αn

where β0,β1,…,βn are sequences that can each yield the empty string, while α0,α1,…,αn may be any sequences of terminal and nonterminal symbols at all. Note that these sequences may be empty. The derivation

A0⇒β0A1α0⇒+A1α0⇒β1A2α1α0⇒+⋯⇒+A0αn…α1α0

then gives A0 as leftmost in its final sentential form.

Sign in to keep reading

4 more chapters are free with a Lably account.

More in Computing and communication