PPArithmeticParser.st
changeset 0 739fe9b7253e
child 4 90de244a7fa2
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/PPArithmeticParser.st	Thu Aug 18 20:56:17 2011 +0200
@@ -0,0 +1,58 @@
+"{ Package: 'squeak:petitparser' }"
+
+PPCompositeParser subclass:#PPArithmeticParser
+	instanceVariableNames:'terms addition factors multiplication power primary parentheses
+		number'
+	classVariableNames:''
+	poolDictionaries:''
+	category:'PetitTests-Examples'
+!
+
+
+!PPArithmeticParser methodsFor:'accessing'!
+
+start
+	^ terms end
+! !
+
+!PPArithmeticParser methodsFor:'grammar'!
+
+addition
+	^ (factors separatedBy: ($+ asParser / $- asParser) token trim) 
+		foldLeft: [ :a :op :b | a perform: op value asSymbol with: b ]
+!
+
+factors
+	^ multiplication / power
+!
+
+multiplication
+	^ (power separatedBy: ($* asParser / $/ asParser) token trim)
+		foldLeft: [ :a :op :b | a perform: op value asSymbol with: b ]
+!
+
+number
+	^ ($- asParser optional , #digit asParser plus , ($. asParser , #digit asParser plus) optional) token trim ==> [ :token | token value asNumber ]
+!
+
+parentheses
+	^ $( asParser flatten trim , terms , $) asParser flatten trim ==> #second
+!
+
+power
+	^ (primary separatedBy: $^ asParser token trim) foldRight: [ :a :op :b | a raisedTo: b ]
+!
+
+primary
+	^ number / parentheses
+!
+
+terms
+	^ addition / factors
+! !
+
+!PPArithmeticParser class methodsFor:'documentation'!
+
+version_SVN
+    ^ '$Id: PPArithmeticParser.st,v 1.1 2011-08-18 18:56:17 cg Exp $'
+! !