Skip to content
Browse files

added attempt & lookahead, make nxt simpler

  • Loading branch information...
1 parent ceb4fe2 commit 90e2d59cdde6429f531e57bdd9e01272ad597d1c @youngnh committed Sep 22, 2011
Showing with 29 additions and 8 deletions.
  1. +13 −8 src/the/parsatron.clj
  2. +16 −0 test/parsatron/test.clj
View
21 src/the/parsatron.clj
@@ -45,14 +45,6 @@
(fn [state cok cerr eok eerr]
(eok x state)))
-(defn nxt [p q]
- (fn [state cok cerr eok eerr]
- (letfn [(pcok [item state]
- (q state cok cerr cok cerr))
- (peok [item state]
- (q state cok cerr eok eerr))]
- (p state pcok cerr peok eerr))))
-
(defn bind [p f]
(fn [state cok cerr eok eerr]
(letfn [(pcok [item state]
@@ -63,6 +55,9 @@
(q state cok cerr eok eerr)))]
(p state pcok cerr peok eerr))))
+(defn nxt [p q]
+ (bind p (fn [_] q)))
+
(defmacro defparser [name args & body]
`(defn ~name ~args
(fn [state# cok# cerr# eok# eerr#]
@@ -94,6 +89,10 @@
(q state cok cerr eok qeerr)))]
(p state cok cerr eok peerr))))
+(defn attempt [p]
+ (fn [state cok cerr eok eerr]
+ (p state cok eerr eok eerr)))
+
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; token
(defn token [consume?]
@@ -130,6 +129,12 @@
(eok (repeat n item) state))]
(p state pcok cerr peok eerr)))))
+(defn lookahead [p]
+ (fn [state cok cerr eok eerr]
+ (letfn [(ok [item _]
+ (eok item state))]
+ (p state ok cerr eok eerr))))
+
(defn choice [& parsers]
(if (empty? parsers)
(never)
View
16 test/parsatron/test.clj
@@ -35,6 +35,15 @@
(is (thrown-with-msg? RuntimeException #"Unexpected token 'c', Unexpected token 'c'"
(run (either (char \a) (char \b)) "c")))))
+(deftest test-attempt
+ (testing "success returns value of p"
+ (is (parser-result? \a (attempt (char \a)) "a")))
+
+ (testing "failure is same as never"
+ (is (thrown? RuntimeException (run (attempt (char \a)) "b")))
+ (is (parser-result? \c (either (attempt (>> (char \a) (char \b)))
+ (>> (char \a) (char \c))) "ac"))))
+
(deftest test-token
(testing "throws error on empty input"
(is (thrown-with-msg? RuntimeException #"Unexpected end of input"
@@ -74,6 +83,13 @@
(is (parser-result? [\a \a \a] (times 3 (char \a)) "aaa"))
(is (parser-result? [5 5 5] (times 3 (always 5)) ""))))
+(deftest test-lookahead
+ (testing "returns value of p on success"
+ (is (parser-result? \a (lookahead (char \a)) "a")))
+
+ (testing "does not consume input on success"
+ (is (parser-result? \a (>> (lookahead (char \a)) (char \a)) "a"))))
+
(deftest test-choice
(testing "choice with no choices throws an exception"
(is (thrown? RuntimeException (run (choice) ""))))

0 comments on commit 90e2d59

Please sign in to comment.
Something went wrong with that request. Please try again.