Permalink
Browse files

+ Start of a transformation class, naming is not final

  • Loading branch information...
1 parent c0a680e commit 2cc4ac71cedbbf242149fa5e2303eeb6435d9458 @kschiess committed Feb 21, 2011
Showing with 56 additions and 0 deletions.
  1. +18 −0 lib/parslet/atoms/transform.rb
  2. +38 −0 spec/parslet/atoms/transform_spec.rb
@@ -0,0 +1,18 @@
+
+require 'parslet/atoms/visitor'
+
+# A helper class that allows transforming one grammar into another.
+#
+class Parslet::Atoms::Transform
+ def apply(grammar)
+ grammar.accept(self)
+ end
+
+ def visit_str(str)
+ Parslet.str(str)
+ end
+
+ def visit_sequence(parslets)
+ parslets[1..-1].inject(parslets[0]) { |a,p| a >> p }
+ end
+end
@@ -0,0 +1,38 @@
+require 'spec_helper'
+
+require 'parslet/atoms/transform'
+
+describe Parslet::Atoms::Transform do
+ include Parslet
+
+ context "when used directly" do
+ it "should transform all inputs onto itself"
+ end
+
+ class ModifyAll < Parslet::Atoms::Transform
+ def visit_str(s)
+ super(s.reverse)
+ end
+ def visit_sequence(seq)
+ super(seq.reverse)
+ end
+ end
+ describe ModifyAll do
+ subject { ModifyAll.new }
+ def apply(grammar)
+ subject.apply(grammar)
+ end
+
+ context "str" do
+ it "should reverse the string" do
+ apply(str('foo')).should parse('oof')
+ end
+ end
+ context "sequence" do
+ it "should reverse sequences" do
+ apply(str('a') >> str('b')).should parse('ba')
+ end
+ end
+ end
+
+end

0 comments on commit 2cc4ac7

Please sign in to comment.