Permalink
Browse files

added eof parser

  • Loading branch information...
youngnh committed Feb 7, 2011
1 parent ea33d1a commit 292a2102fbc3fcaa4960f235ff24d8ba0208a913
Showing with 27 additions and 7 deletions.
  1. +14 −5 src/the/parsatron.clj
  2. +13 −2 test/parsatron/test.clj
View
@@ -24,7 +24,10 @@
(ParseError. pos ["Error"]))
(defn unexpect-error [msg pos]
- (ParseError. pos [msg]))
+ (ParseError. pos [(str "Unexpected " msg)]))
+
+(defn expect-error [msg pos]
+ (ParseError. pos [(str "Expected " msg)]))
(defn merge-errors [{:keys [pos] :as err} other-err]
(ParseError. pos (flatten (concat (:msgs err) (:msgs other-err)))))
@@ -95,7 +98,7 @@
(let [newpos (nextpos-f pos item rest-of-input)
newstate (InputState. rest-of-input newpos)]
(cok item newstate))
- (eerr (unexpect-error (str "Found unexpected " (show-f item)) pos))))
+ (eerr (unexpect-error (show-f item) pos))))
(eerr (unexpect-error "Input is empty" pos)))))
(defn many [p]
@@ -130,6 +133,12 @@
(let [p (first parsers)]
(either p (apply choice (rest parsers))))))
+(defn eof []
+ (fn [{:keys [input pos] :as state} cok cerr eok eerr]
+ (if (empty? input)
+ (eok nil state)
+ (eerr (expect-error "end of input" pos)))))
+
(defn updatepos-char [{:keys [line column]} c]
(case c
\newline (SourcePos. (inc line) 1)
@@ -167,11 +176,11 @@
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; run parsers
(defn run-parser [p state]
- (letfn [(cok [item ztate]
+ (letfn [(cok [item _]
(Ok. item))
(cerr [err]
- (Err. err))
- (eok [item state-prime]
+ (Err. (show-error err)))
+ (eok [item _]
(Ok. item))
(eerr [err]
(Err. (show-error err)))]
View
@@ -31,7 +31,7 @@
(is (parser-result? 5 (either (never) (always 5)) "")))
(testing "when neither succeed, errors are merged"
- (is (thrown-with-msg? RuntimeException #"Found unexpected c, Found unexpected c"
+ (is (thrown-with-msg? RuntimeException #"Unexpected c, Unexpected c"
(run (either (char \a) (char \b)) "c")))))
(deftest test-token
@@ -48,7 +48,7 @@
nxtpos (constantly (SourcePos. 1 2))
show-token (constantly "a")]
(is (parser-result? \a (token consume nxtpos show-token) "a"))
- (is (thrown-with-msg? RuntimeException #"Found unexpected a"
+ (is (thrown-with-msg? RuntimeException #"Unexpected a"
(run (token dont-consume nxtpos show-token) "a"))))))
(deftest test-many
@@ -89,3 +89,14 @@
"a"
"b"
"c")))
+
+(deftest test-eof
+ (testing "parser succeeds, returns nil when no more input left"
+ (is (parser-result? nil (eof) ""))
+ (is (parser-result? nil (>> (char \a) (eof)) "a")))
+
+ (testing "parser fails with message when input if left"
+ (is (thrown-with-msg? RuntimeException #"Expected end of input"
+ (run (eof) "a")))
+ (is (thrown-with-msg? RuntimeException #"Expected end of input"
+ (run (>> (char \a) (eof)) "ab")))))

0 comments on commit 292a210

Please sign in to comment.