使用PetitParser定义左关联解析器

Dam*_*sou 5 smalltalk pharo petitparser

http://pharobooks.gforge.inria.fr/PharoByExampleTwo-Eng/latest/中,定义了ExpressionGrammar.但是,它是正确联想的

parser parse: '1 + 2 + 6'.    ======> #(1 $+ #(2 $+ 6))
Run Code Online (Sandbox Code Playgroud)

我怎样才能使它成为左关联的呢

parser parse: '1 + 2 + 6'.
Run Code Online (Sandbox Code Playgroud)

结果是

#(#(1 $+ 2) $+ 6)
Run Code Online (Sandbox Code Playgroud)

Luk*_*gli 7

对于左关联语法,请使用:

term := (prod sepratedBy: $+ asParser trim) foldLeft: [ :a :op :b |
Run Code Online (Sandbox Code Playgroud)

...]

对于右关联语法,请使用:

raise := (prod sepratedBy: $^ asParser trim) foldRight: [ :a :op :b |
Run Code Online (Sandbox Code Playgroud)

...]

或者,您可能希望查看PPExpressionParser,它会自动为您处理所有详细信息.您只需告诉它操作符是左关联,右关联,前缀或后缀运算符.看一下课堂评论,进行深入讨论.