Defining a left-associative parser with PetitParser

137 Views Asked by At

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

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

How can I make it left-associative so that

parser parse: '1 + 2 + 6'.

results in

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

?

2

There are 2 best solutions below

0
On BEST ANSWER

For left associative grammars use:

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

...]

For right associative grammars use:

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

...]

Alternatively you might want to look at PPExpressionParser, that handles all the details automatically for you. You just tell it what operators are left-associative, right-associative, prefix, or postfix operators. Have a look at the class comment for a in-depth discussion.

0
On

look at PPExpressionParser class.

it's designed for that and you have a great example in the class comment