Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a left-associative parser with PetitParser

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)

?

like image 340
Damien Cassou Avatar asked Jan 28 '13 13:01

Damien Cassou


2 Answers

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.

like image 88
Lukas Renggli Avatar answered Nov 06 '22 13:11

Lukas Renggli


look at PPExpressionParser class.

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

like image 43
Larcheveque Guillaume Avatar answered Nov 06 '22 14:11

Larcheveque Guillaume