Search code examples
smalltalkpharopetitparser

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)

?


Solution

  • 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.