Kaspar Schiess avatar Kaspar Schiess committed ada4d86

First simple parse succeeds

Comments (0)

Files changed (3)

examples/integers.rb

+$:.unshift File.dirname(__FILE__) + "/../lib"
+
+require 'par'
+include Par
+
+def integer source
+  source.pattern(/\+|-/) >>
+    source.pattern(/\d+/)
+end
+
+p integer(source('1234'))
+p integer(source('+23'))
+p integer(source('abc'))
     def to_s
       obj.to_s
     end
+    def <=> other
+      return obj <=> other.to_str if other.respond_to? :to_str
+    end
+    include Comparable
 
     def self.bot
       @bot ||= Bot.new
 
     def string str
       if head(str.size) == str
-        return Par.result(self.n(str.size))
+        return self.n(str.size)
       end
 
       Par.bot
     end
+    def pattern pat
+      idx = head.index(pat)
+      return bot unless idx == 0
+      md =head.match(pat)
+      n(md[0].size)
+    end
 
     def n n
-      head(n).tap { @pos += n }
+      Par.result(head(n)).tap { @pos += n }
     end
 
     def head n=nil
-      str[@pos, n]
+      n && str[@pos, n] || str[@pos..-1]
     end
   end
 

spec/lib/par/source_spec.rb

       s.n(2).should == 'öü'
     end
   end
+  describe "#pattern" do
+    let(:s) { source 'foobar' }
+    it "matches a pattern and consumes it" do
+      r = s.pattern /foo/
+      r == 'foo'
+    end
+  end
 end
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.