JetBrains / Grammar-Kit

Grammar files support & parser/PSI generation for IntelliJ IDEA
Other
723 stars 126 forks source link

Working around left recursion #201

Closed Nihlus closed 6 years ago

Nihlus commented 6 years ago

I'm rather new to grammar-kit, and I'm having trouble wrapping my head around how to eliminate or work around a set of left-recursive rules.

My goal is to create an Ada language plugin for the JetBrains ecosystem, but an integral part of the offical BNF specification of Ada uses left recursion - element names. While I have a slight idea of the basics behind it, I'm not versed enough to apply it to the problem I'm facing - especially with the extensions Grammar-Kit offers.

These are the rules in question, as well as the full BNF.

element_name ::= direct_name |
         slice |
         selected_component |
         attribute_reference |
         type_conversion |
         function_call |
         'character_literal' |
         explicit_dereference |
         indexed_component

function_call ::= (function_name | prefix) [ actual_parameter_part ]
function_name ::= element_name
type_conversion ::= subtype_mark "(" (expression | element_name) ")"
attribute_reference ::= prefix 'single_quote' attribute_designator
selected_component ::= prefix '.' selector_name
slice ::= prefix "(" discrete_range ")"
explicit_dereference ::= element_name '.' 'all'
indexed_component ::= prefix "(" expression { ',' expression } ")"
prefix ::= element_name
subtype_mark ::= element_name

https://gist.github.com/Nihlus/f65e1a77487d5c571eb27f36cb024306

Given that I'm working with grammar-kit, how would I approach this and eliminate or support this left recursion?

gregsh commented 6 years ago

Try the following approach: https://github.com/JetBrains/Grammar-Kit/blob/master/HOWTO.md#24-compact-expression-parsing-with-priorities

Nihlus commented 6 years ago

@gregsh I'm afraid I'm really having trouble understanding how to apply that method to the BNF I have. I'm still very new to the world of formal grammars, and this has my brain in a complete meltdown.

Could you show me an example using my grammar as a basis?

gregsh commented 6 years ago

I've tried explain that in this forum thread: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001258300-What-s-the-alternative-to-left-recursion-in-GrammarKit-?page=1#community_comment_360000201199

Please feel free to ask additional questions on that forum. More people = more utility :-)

Nihlus commented 6 years ago

Thanks a bunch! That makes it a lot clearer - I'll investigate more tomorrow :)