Defining a Left Associative Analyzer with PetitParser

At http://pharobooks.gforge.inria.fr/PharoByExampleTwo-Eng/latest/ , ExpressionGrammar is defined. However, it is a right-associative

parser parse: '1 + 2 + 6'.    ======> #(1 $+ #(2 $+ 6))

How can I make it left-associative so that

parser parse: '1 + 2 + 6'.

leads to

#(#(1 $+ 2) $+ 6)

?

+5
source share
2 answers

For left associative grammars use:

term := (prod sepratedBy: $+ asParser trim) foldLeft: [ :a :op :b |

...]

For correct associative grammars use:

raise := (prod sepratedBy: $^ asParser trim) foldRight: [ :a :op :b |

...]

Alternatively, you can see PPExpressionParserwhich automatically processes all the details. You simply say which operators are left-associative, right-associative, prefix or postfix operators. Take a look at the class comment for an in-depth discussion.

+7

PPExpressionParser.

,

+4

All Articles