Table of contents
1.
Introduction
2.
1. Left Recursion
2.1.
1.1 Why Is Left Recursion a Problem?
2.1.1.
Example of Left Recursion
2.1.2.
Example (Problem Demonstration)
2.2.
1.2 How to Eliminate Left Recursion?
2.2.1.
Example of Left Recursion Elimination
2.2.2.
Example (Fixed Version)
3.
2. Left Factoring
3.1.
2.1 Why Do We Use Left Factoring?
3.1.1.
Example of Ambiguous Grammar
3.1.2.
Left Factored Version
3.2.
2.2 Example of Left Factoring in Code
4.
Key Differences Between Left Factoring and Left Recursion
5.
Frequently Asked Questions
5.1.
What is the main problem with left recursion in parsing?
5.2.
Why do we use left factoring in grammar transformation?
5.3.
How do you fix left recursion in a grammar?
6.
Conclusion
Last Updated: Mar 17, 2025
Medium

Left Recursion (LR) and Left Factoring (LF)

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Left Recursion (LR) and Left Factoring (LF) are two important concepts in compiler design related to grammar transformation. Left Recursion occurs when a non-terminal in a grammar rule refers to itself as the first symbol, causing issues in recursive descent parsers. Left Factoring is used to transform a grammar when multiple productions share a common prefix, helping in predictive parsing. 

Left Recursion (LR) and Left Factoring (LF)

In this article, we will learn the differences between Left Recursion and Left Factoring with examples.

1. Left Recursion

In formal grammar, left recursion occurs when a non-terminal symbol appears on the leftmost side of its own production rule. This can cause issues in top-down parsers, particularly recursive descent parsers, leading to infinite recursion.

1.1 Why Is Left Recursion a Problem?

When using recursive descent parsing, a left-recursive grammar leads to an infinite loop, making it impossible for the parser to terminate. This happens because the parser keeps expanding the leftmost non-terminal indefinitely without reaching a terminal symbol.

Example of Left Recursion

Consider the following grammar:

A -> Aα | β

Here, A calls itself at the beginning, making it left-recursive. If we try to parse using recursive descent, it keeps calling itself indefinitely.

Example (Problem Demonstration)

# This function enters an infinite loop due to left recursion
def left_recursive_parser():
    print("Calling A")
    left_recursive_parser()  # Recursive call without termination
# Uncommenting this will result in infinite recursion
# left_recursive_parser()

 

Since the function keeps calling itself without a base condition, it results in infinite recursion.

1.2 How to Eliminate Left Recursion?

To convert a left-recursive grammar into a non-left-recursive form, we follow a transformation process:

  1. Identify the left-recursive production rule: A -> Aα | β
     
  2. Replace it with:
A -> βA'
A' -> αA' | ε

Example of Left Recursion Elimination

Original Grammar

S -> S a | b


Transformed Grammar:

S -> b S'
S' -> a S' | ε

Example (Fixed Version)

def non_left_recursive_parser(input_string):
    if input_string.startswith("b"):
        print("Valid string starting with 'b'")
        remainder = input_string[1:]
        while remainder.startswith("a"):
            print("Processing 'a'")
            remainder = remainder[1:]
        print("Parsing complete")
    else:
        print("Invalid string")
# Example usage
non_left_recursive_parser("baaa")
You can also try this code with Online Python Compiler
Run Code


Output:

Valid string starting with 'b'
Processing 'a'
Processing 'a'
Processing 'a'
Parsing complete

2. Left Factoring

Left factoring is a grammar transformation technique used when multiple production rules start with the same prefix. It helps parsers make unambiguous decisions while parsing.

2.1 Why Do We Use Left Factoring?

When a grammar has two or more production rules that start with the same symbols, a predictive parser might struggle to choose the correct rule to apply. Left factoring ensures that the parser can make a single decision at each step.

Example of Ambiguous Grammar

A -> αβ | αγ

Here, both rules start with α, making it difficult for a parser to decide which path to take.

Left Factored Version

A -> αA'
A' -> β | γ

This version separates the common prefix α, making parsing simple.

2.2 Example of Left Factoring in Code

def left_factored_parser(input_string):
    if input_string.startswith("α"):
        print("Common prefix α found")
        remainder = input_string[1:]
        if remainder.startswith("β"):
            print("β detected, applying rule A -> αβ")
        elif remainder.startswith("γ"):
            print("γ detected, applying rule A -> αγ")
        else:
            print("Invalid string")
    else:
        print("Invalid string")
# Example usage
left_factored_parser("αγ")
You can also try this code with Online Python Compiler
Run Code


Output:

Common prefix α found
γ detected, applying rule A -> αγ

Key Differences Between Left Factoring and Left Recursion

ParametersLeft RecursionLeft Factoring
DefinitionA non-terminal calls itself at the start of its productionRemoves common prefixes in production rules
Issue CausedLeads to infinite recursion in top-down parsersCreates ambiguity for predictive parsers
SolutionConvert to non-left-recursive formFactor out common prefixes
Example Issue`A -> Aαβ` causes infinite recursion
Transformation`A -> βA', A' -> αA'ε`

Frequently Asked Questions

What is the main problem with left recursion in parsing?

Left recursion leads to infinite recursion in top-down parsers, making them unable to parse certain grammars correctly. It must be eliminated for a parser to work efficiently.

Why do we use left factoring in grammar transformation?

Left factoring is used to eliminate ambiguity in predictive parsers, ensuring they can make clear, unambiguous choices during parsing.

How do you fix left recursion in a grammar?

Replace A → Aα | β with A → βA', A' → αA' | ε to remove left recursion and make parsing more efficient.

Conclusion

In this article, we learned about Left Recursion (LR) and Left Factoring (LF) in context-free grammars. Left recursion can cause infinite loops in top-down parsers, so we eliminate it by rewriting the rules in right-recursive form. Left factoring helps resolve ambiguities by factoring out common prefixes, making the grammar suitable for predictive parsing. Both techniques are essential for designing efficient parsers in compiler construction.

Live masterclass