What's the correct way to create BNF for nested expressions, for custom language?


Hi, I'm trying to write BNF file for my custom language plugin. I'm getting confused with the rules for nested expressions. My custom language contains both binary operator expressions and array reference expressions. So I wrote the BNF file like this:


expr ::= binary_expr| array_ref_expr | const_expr

const_expr ::= number
binary_expr ::= expr '+' expr
array_ref_expr ::= id '[' expr ']'

But when I tried to evaluate expressions like 'a[1+1]' , I got an error:

']' expected, got '+'

What would I need to do?

Many thanks


1 comment
Comment actions Permalink

Hi Hao,

It seems that the parser cannot handle the input correctly when binary_expr is at the beginning of expr. It might cause the recursion issue as the parser will try to parse: expr -> binary_expr -> expr -> binary_expr -> expr -> binary_expr -> etc.

To resolve this issue, move the binary_expr rule to the end:

expr ::= array_ref_expr | const_expr | binary_expr



Please sign in to leave a comment.