Appetizer #3 Before Parsing: Eliminating Left Recursions
DefinitionPermalink
Why eliminate?
Top-down parsing methods cannot handle left-recursive grammars. It causes endless recursive calls.
Definition: A grammar
Eliminating Direct Left RecursionPermalink
Consider the easiest case:
where
It can be rewritten to:
and done! The rewriting simply converts left recursion to right recursion.
If you don’t like introducing an
If we have more productions like:
where
If you don’t like introducing an
Eliminating Indirect Left RecursionPermalink
Indirect left recursion involves multiple derivation steps, like
Intuition: If we know there would be an indirect left recursion
Problem: How do we find such variable
Method #1: VDG (Variable Dependency Graph) on LHS variables and leftmost variables on RHS. E.g. draw an edge
Method #2: Variable Relabeling:
- Relabel the variables in some order
. Any order should work, but the naive one (left-to-right in any single production, top-down in the production list) is the most straightforward. - If there is an indirect left recursion, it must be like
(or more productions involved, depending on the length of the -loop in VDG described above). - Therefore whenever we see a production
where , it is possible that has an indirect left recursion.- We say “possible” because an
path might not exist in the VDG to begin with.
- We say “possible” because an
However anyway we can just substitute
In the Dragon Book we have the following algorithm:
Note that it uses subscripts
留下评论