Permalink
Browse files

. cleanup

  • Loading branch information...
1 parent fe1a84d commit 545dbbc1281137c01c826d5afbcd3ca672cf0acb @kschiess committed Aug 10, 2012
Showing with 10 additions and 2 deletions.
  1. +10 −2 example/calc.rb
View
@@ -7,6 +7,8 @@
require 'parslet'
require 'parslet/rig/rspec'
+# This is the parsing stage. It expresses left associativity by compiling
+# list of things that have the same associativity.
class CalcParser < Parslet::Parser
root :addition
@@ -28,6 +30,7 @@ class CalcParser < Parslet::Parser
rule(:space?) { match['\s'].repeat }
end
+# Classes for the abstract syntax tree.
Int = Struct.new(:int) {
def eval; self end
def op(operation, other)
@@ -65,16 +68,21 @@ def call(left)
end
}
+# Transforming intermediary syntax tree into a real AST.
class CalcTransform < Parslet::Transform
rule(i: simple(:i)) { Int.new(Integer(i)) }
rule(o: simple(:o), r: simple(:i)) { LeftOp.new(o, i) }
rule(l: simple(:i)) { i }
rule(sequence(:seq)) { Seq.new(seq) }
end
+# And this calls everything in the right order.
def calculate(str)
- tree = CalcParser.new.parse(str)
- CalcTransform.new.apply(tree).eval.to_i
+ intermediary_tree = CalcParser.new.parse(str)
+ abstract_tree = CalcTransform.new.apply(intermediary_tree)
+ result = abstract_tree.eval
+
+ result.to_i
end
# A test suite for the above parser

0 comments on commit 545dbbc

Please sign in to comment.