Permalink
Browse files

left to right evaluation

  • Loading branch information...
1 parent dcb75ae commit 525496985722f7faaca2187d4b3a5b3caf2cb274 @kassens kassens committed Jul 25, 2010
@@ -4,7 +4,10 @@ grammar Arithmetic
end
rule comparative
- operand_1:additive space operator:equality_op space operand_2:additive <BinaryOperation>
+ head:additive
+ tail:(
+ space operator:equality_op
+ space operand:additive)* <BinaryOperation>
end
rule equality_op
@@ -16,11 +19,10 @@ grammar Arithmetic
end
rule additive
- operand_1:multitive
- space operator:additive_op space
- operand_2:additive <BinaryOperation>
- /
- multitive
+ head:multitive
+ tail:(
+ space operator:additive_op
+ space operand:multitive)* <BinaryOperation>
end
rule additive_op
@@ -38,11 +40,10 @@ grammar Arithmetic
end
rule multitive
- operand_1:primary
- space operator:multitive_op space
- operand_2:multitive <BinaryOperation>
- /
- primary
+ head:primary
+ tail:(
+ space operator:multitive_op
+ space operand:primary)* <BinaryOperation>
end
rule multitive_op
@@ -94,4 +95,4 @@ grammar Arithmetic
rule space
' '*
end
-end
+end
@@ -1,7 +1,9 @@
module Arithmetic
class BinaryOperation < Treetop::Runtime::SyntaxNode
def eval(env={})
- operator.apply(operand_1.eval(env), operand_2.eval(env))
+ tail.elements.inject(head.eval(env)) do |value, element|
+ element.operator.apply(value, element.operand.eval(env))
+ end
end
end
-end
+end
@@ -43,6 +43,10 @@ def test_order_of_operations
assert_equal 11, parse('1 + 2 * 3 + 4').eval
end
+ def test_left_to_right
+ assert_equal 2, parse('5 - 2 - 1').eval
+ end
+
def test_parentheses
assert_equal 25, parse('(5 + x) * (10 - y)').eval('x' => 0, 'y' => 5)
end

0 comments on commit 5254969

Please sign in to comment.