1. Kaspar Schiess
  2. par

Commits

Kaspar Schiess  committed 2ced7db

A first real example

  • Participants
  • Parent commits ef2e6f5
  • Branches master

Comments (0)

Files changed (3)

File lib/par.rb

View file
           concat(obj, other.obj))
       end
 
-      self.class.bot
+      bot
+    end
+    def | other
+      self
     end
 
     def new obj
       self.class.new obj
     end
+    def bot
+      self.class.bot
+    end
+    def top
+      self.class.top
+    end
     
     def concat obj1, obj2
       obj1 + obj2
       def >> other
         self
       end
+
+      def | other
+        other
+      end
     end
   end
+  class Source
+    attr_reader :str 
 
-  def r str
+    def initialize str
+      @str = str
+      @pos = 0
+    end
+
+    def string str
+      if head(str.size) == str
+        return Par.result(self.n(str.size))
+      end
+
+      Par.bot
+    end
+
+    def n n
+      head(n).tap { @pos += n }
+    end
+
+    def head n=nil
+      str[@pos, n]
+    end
+  end
+
+module_function
+  def result str
     Result.new str
   end
+  def source str
+    Source.new str
+  end
   def bot 
     Result.bot
   end

File spec/lib/par/result_spec.rb

View file
   include Par
 
   context 'given 2 results' do
-    let(:a) { r 'foo' }
-    let(:b) { r 'bar' }
+    let(:a) { result 'foo' }
+    let(:b) { result 'bar' }
     
     it "should allow concatenation" do
       (a >> b).to_s.should == 'foobar'
     end
+    it "should allow alternation" do
+      (a | b).should == a
+    end
   end
   context '.bot' do
-    let(:any) { r 'any' }
+    let(:any) { result 'any' }
 
     it "cannot be concatenated left" do
       (bot >> any).should == bot
     it "cannot be concatenated right" do
       (any >> bot).should == bot 
     end
+    it "can be alternated left" do
+      (bot | any).should == any
+    end
+    it "can be alternated right" do
+      (any | bot).should == any
+    end
   end
   context '.top' do
     let(:top) {}

File spec/lib/par_spec.rb

View file
 require 'spec_helper'
 
 describe Par do
-  
+  include Par
+
+  describe "sequences" do
+    let(:s) { source 'foobar' }
+
+    it "parse" do
+      (s.string('foo') >> s.string('bar')).should_not == bot
+    end
+  end
 end