PPArithmeticParser.st
changeset 0 739fe9b7253e
child 4 90de244a7fa2
equal deleted inserted replaced
-1:000000000000 0:739fe9b7253e
       
     1 "{ Package: 'squeak:petitparser' }"
       
     2 
       
     3 PPCompositeParser subclass:#PPArithmeticParser
       
     4 	instanceVariableNames:'terms addition factors multiplication power primary parentheses
       
     5 		number'
       
     6 	classVariableNames:''
       
     7 	poolDictionaries:''
       
     8 	category:'PetitTests-Examples'
       
     9 !
       
    10 
       
    11 
       
    12 !PPArithmeticParser methodsFor:'accessing'!
       
    13 
       
    14 start
       
    15 	^ terms end
       
    16 ! !
       
    17 
       
    18 !PPArithmeticParser methodsFor:'grammar'!
       
    19 
       
    20 addition
       
    21 	^ (factors separatedBy: ($+ asParser / $- asParser) token trim) 
       
    22 		foldLeft: [ :a :op :b | a perform: op value asSymbol with: b ]
       
    23 !
       
    24 
       
    25 factors
       
    26 	^ multiplication / power
       
    27 !
       
    28 
       
    29 multiplication
       
    30 	^ (power separatedBy: ($* asParser / $/ asParser) token trim)
       
    31 		foldLeft: [ :a :op :b | a perform: op value asSymbol with: b ]
       
    32 !
       
    33 
       
    34 number
       
    35 	^ ($- asParser optional , #digit asParser plus , ($. asParser , #digit asParser plus) optional) token trim ==> [ :token | token value asNumber ]
       
    36 !
       
    37 
       
    38 parentheses
       
    39 	^ $( asParser flatten trim , terms , $) asParser flatten trim ==> #second
       
    40 !
       
    41 
       
    42 power
       
    43 	^ (primary separatedBy: $^ asParser token trim) foldRight: [ :a :op :b | a raisedTo: b ]
       
    44 !
       
    45 
       
    46 primary
       
    47 	^ number / parentheses
       
    48 !
       
    49 
       
    50 terms
       
    51 	^ addition / factors
       
    52 ! !
       
    53 
       
    54 !PPArithmeticParser class methodsFor:'documentation'!
       
    55 
       
    56 version_SVN
       
    57     ^ '$Id: PPArithmeticParser.st,v 1.1 2011-08-18 18:56:17 cg Exp $'
       
    58 ! !