重写解析表达式语法(PEG),无需左递归

2023-12-20

Using https://github.com/JetBrains/Grammar-Kit https://github.com/JetBrains/Grammar-Kit如何在没有左递归的情况下重写语法?

grammar ::= exprs
exprs::= (sum_expr (';')?)*
private sum_expr::= sum_expr_infix | sum_expr_prefix
sum_expr_infix ::= number sum_expr_prefix


left sum_expr_prefix::= op_plus number


private op_plus ::= '+'    
number ::= float | integer
float ::= digit+ '.' digit*
integer ::= digit+
private digit ::=('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')

输入示例:

10+20+30.0;
10+20+30.0

Answer shall maintain parse tree property that nodes contain 2/3 children: enter image description here


这个问题引导了正确的方向:不使用左手递归解析布尔表达式 https://stackoverflow.com/questions/15506088/parsing-boolean-expression-without-left-hand-recursion

grammar ::= e*
e ::=  math separator?

math ::= add
add ::=
    mul op_plus math
 |  mul op_minus math
 |  mul


mul ::=
    factorial op_mul mul
  | factorial op_div mul
  | factorial

factorial ::= term op_factorial space* | term
op_factorial ::= '!'

term ::= parentheses | space* number space*
parentheses ::= '(' math ')'


op_minus ::= '-'
op_plus ::= '+'
op_div ::= '/'
op_mul ::= '*'
number ::= float | integer
float ::= (digit+'.') digit*
integer ::=digit+
digit ::= '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
space ::= ' ' | '\t'
separator ::= ';'

测试输入:

1!
3*2+1
3*2+1+3.0!
3*2+1 + 3.0!
1+1+(1+1)!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重写解析表达式语法(PEG),无需左递归 的相关文章

随机推荐