Problem of left recursion and solution in cfgs

preview_player
Показать описание
okay, let's dive deep into the problem of left recursion in context-free grammars (cfgs) and explore various solutions.

**what is left recursion?**

left recursion occurs in a cfg when a non-terminal symbol can derive a string starting with itself in one or more steps. in simpler terms, a non-terminal's definition directly or indirectly refers to itself at the *beginning* of the right-hand side of a production rule.

there are two main types of left recursion:

1. **immediate left recursion:** this is the most straightforward case. a production rule has the form:

`a - aα | β`

where:
* `a` is a non-terminal.
* `α` is a string of terminals and/or non-terminals (excluding the empty string).
* `β` is a string of terminals and/or non-terminals that *does not* start with `a`.

for example: `e - e + t | t`

2. **indirect (or hidden) left recursion:** this is more subtle. a non-terminal derives a string that eventually leads back to itself through a chain of productions.

for example:

here, `a` derives `b α`, which derives `c β α`, which derives `a γ β α`. so, `a` derives a string starting with itself (indirectly).

**why is left recursion a problem for top-down parsers?**

top-down parsers (like recursive descent parsers and ll parsers) work by starting from the start symbol of the grammar and attempting to derive the input string. they predict which production rule to apply based on the current non-terminal and the next input token.

left recursion causes infinite loops in these parsers. let's illustrate with the immediate left recursion example:

`e - e + t | t`

suppose the parser wants to parse the expression "id + id".

1. the parser starts with `e`.
2. it sees that `e` can derive `e + t`. it decides to try this production.
3. now, the parser needs to derive `e`, but it sees the same rule `e - e + t | t`.
4. it again chooses `e - e + t`, and so on...
5. the parser gets stuck in an infinite loop, repeatedly ...

#LeftRecursion #CFGs #CompilerDesign

left recursion
context-free grammars
CFG
parsing techniques
eliminatation of left recursion
recursive descent parsing
grammar transformation
top-down parsing
left factoring
backtracking
syntax trees
ambiguity resolution
parsing algorithms
language processing
compiler design
Рекомендации по теме
welcome to shbcf.ru