简体   繁体   English

如何处理PEG语法中的负数?

[英]How do I handle negative numbers in a PEG grammar?

I'm trying to write a simple int expression parser using tatsu , a PEG-based Python parser generator. 我正在尝试使用基于PEG的Python解析器生成器tatsu编写一个简单的int表达式解析器。 Here is my code: 这是我的代码:

import tatsu

grammar = r'''
    start = expression $ ;
    expression = add | sub | term ;
    add = expression '+' term ;
    sub = expression '-' term ;
    term = mul | div | number ;
    mul = term '*' number ;
    div = term '/' number ;
    number = [ '-' ] /\d+/ ;
'''
parser = tatsu.compile(grammar)
print(parser.parse('2-1'))

The output of this program is ['-', '1'] instead of the expected ['2', '-', '1'] . 该程序的输出是['-', '1']而不是预期的['2', '-', '1']

I get the correct output if I either: 如果我要么得到正确的输出:

  • Remove support for unary minus, ie change the last rule to number = /\\d+/ ; 删除对一元减号的支持,即将最后一条规则更改为number = /\\d+/ ;
  • Remove the term, mul and div rules, and support only addition and subtraction 删除term,mul和div规则,仅支持加法和减法
  • Replace the second rule with expresssion = add | sub | mul | div | number ; expresssion = add | sub | mul | div | number ;替换第二条规则 expresssion = add | sub | mul | div | number ;

The last option actually works without leaving any feature out, but I don't understand why it works. 最后一个选项实际上可以工作而不会留下任何功能,但我不明白为什么它的工作原理。 What is going on? 到底是怎么回事?

EDIT : If I just flip the add/sub/mul/div rules to get rid of left recursion, it also works. 编辑 :如果我只是翻转add / sub / mul / div规则来摆脱左递归,它也有效。 But then evaluating the expressions becomes a problem, since the parse tree is flipped. 但是,然后评估表达式成为一个问题,因为翻译了解析树。 ( 3-2-1 becomes 3-(2-1) ) 3-2-1变成3-(2-1)

There are left recursion cases that TatSu doesn't handle, and work on fixing that is currently on hold. 有一些TatSu无法处理的递归案例,并且正在处理目前处于暂停状态的修复工作。

You can use left/right join/gather operators to control the associativity of parsed expressions in a non-left-recursive grammar. 您可以使用左/右连接/聚集运算符来控制非左递归语法中已解析表达式的关联性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM