Clojure Instaparse Parser Tutorial: Parse Error
When parsing, if the input string is invalid according to the grammar, then, it is a parsing failure.
- the
parse
function will return a failure object if parse failed. - the
parses
function will return a empty list, with failure object attached as Clojure metadata, if parse failed.
The following functions are related to failure object:
(instaparse.core/failure? result)
-
Return
true
if result is a parsing failure. The result is output from(instaparse.core/parse …)
or(instaparse.core/parses …)
(instaparse.core/get-failure result)
- get the failure object.
Check for Parse Failure
(ns example.core (:require [instaparse.core :as insta])) (def x7 (insta/parser "S = AB* AB = A B A = 'a'+ B = 'b'+")) (x7 "aaa") ; returns a failure object. prints as: ;; Parse error at line 1, column 4: ;; aaa ;; ^ ;; Expected one of: ;; "b" ;; "a" (insta/parses x7 "aaa") ;; returns () (insta/failure? (insta/parses x7 "aaa")) ; true (insta/get-failure (insta/parses x7 "aaa")) ;; returns the failure object. prints ;; #_=> Parse error at line 1, column 4: ;; aaa ;; ^ ;; Expected one of: ;; "b" ;; "a"
Notes
If your grammar is perfect, then parsing failure means the input string is invalid. (That is: not accepted by the grammar)
If you are creating a language, failure may mean that your grammar is still bad.
Helpful ways to deal with parser failure are:
Use the (parses f :total true)
to force return a parse tree, with failure embedded in the tree. 〔see Clojure Instaparse Parser Tutorial: Total Parse〕
Use the (parses f :partial true)
to see how the parser walks the input. 〔see Clojure Instaparse Parser Tutorial: Partial Parse〕