Skip to content Skip to footer
0 items - $0.00 0

Fixing left and mutual recursions in grammars by brightprogramer

Fixing left and mutual recursions in grammars by brightprogramer

6 Comments

  • Post Author
    mrkeen
    Posted February 2, 2025 at 9:07 am

    Imo this missed the punchline.

    I banged my head on the table for days trying to fix a left-recursive grammar, just by moving bits around and hoping.

    The key is precedence! Parse loose expressions first (plus, minus, etc), these loose expressions can in turn call into tighter expressions (mul, div), and so on down to parentheses.

    Parentheses do form a loop – that is, they call all the way back to the top – but at long as the parser makes progress i.e. can only proceed if it moves past a '(', no infinite loops and you're golden.

  • Post Author
    tempodox
    Posted February 2, 2025 at 9:27 am

    An interesting and worthwhile topic. This kind of problem pops up regularly.

    Those diagrams are really handy, does anyone know how they were made? I'm always looking for alternatives / companions to the Railroad Diagram Generator (https://rr.red-dove.com/ui).

  • Post Author
    earleybird
    Posted February 2, 2025 at 10:44 am

    Use an Earley parser. A properly implemented Earley parser will do unambiguous grammars with left/right/mutual recursion in linear time. The worst case ambiguous I've worked with is UBDA (Earley, 1970). UBDA produces the equivalent of all the permutations of a binary tree – which is Catalan(n). If you generate all the combinations as you parse it won't complete before the heat death of the universe for fairly short strings.

  • Post Author
    briffid
    Posted February 2, 2025 at 12:04 pm

    An example of an actual grammar, like arithmetic expressions, would be helpful.

  • Post Author
    fjfaase
    Posted February 2, 2025 at 3:29 pm

    It is possible to write a (top-down) parser that can deal with the left recursion without having to rewrite the grammar itself. Simply split the left recursive ones and not. Then first try to accept a non-left recursive rule and if that succeeds, use the result to try to parse any of the left recursive ones. (If I am not mistaken, this also works for mutual recursion of left recursive rules.) I have implemented this several times.

  • Post Author
    hyperhello
    Posted February 2, 2025 at 5:31 pm

    Left recursive BNF was an interest of mine. For a much less technically oriented solution you can check out https://hypervariety.com/BNFToLPEG/

Leave a comment

In the Shadows of Innovation”

© 2025 HackTech.info. All Rights Reserved.

Sign Up to Our Newsletter

Be the first to know the latest updates

Whoops, you're not connected to Mailchimp. You need to enter a valid Mailchimp API key.