Instaparse可以将漂亮的错误消息打印到 REPL
=> (negative-lookahead-example "abaaaab")
Parse error at line 1, column 1:
abaaaab
^
Expected:
NOT "ab"
但我找不到将消息作为字符串获取的内置函数。怎么做?
Instaparse可以将漂亮的错误消息打印到 REPL
=> (negative-lookahead-example "abaaaab")
Parse error at line 1, column 1:
abaaaab
^
Expected:
NOT "ab"
但我找不到将消息作为字符串获取的内置函数。怎么做?
您总是可以使用以下方法包装它with-out-str
:
(with-out-str
(negative-lookahead-example "abaaaab"))
您可能也有兴趣使用with-err-str
这里记录的。
(with-err-str
(negative-lookahead-example "abaaaab"))
我不记得是否instaparse
写入标准输出或标准错误,但其中之一会做你想要的。
我们来看看parse
失败情况下的返回类型:
(p/parse (p/parser "S = 'x'") "y")
=> Parse error at line 1, column 1:
y
^
Expected:
"x" (followed by end-of-string)
(class *1)
=> instaparse.gll.Failure
这种漂亮的打印行为在 Instaparse 中是这样定义的:
(defrecord Failure [index reason])
(defmethod clojure.core/print-method Failure [x writer]
(binding [*out* writer]
(fail/pprint-failure x)))
在 REPL 中,这打印为有用的人类可读描述,但它也可以被视为地图:
(keys (p/parse (p/parser "S = 'x'") "y"))
=> (:index :reason :line :column :text)
(:reason (p/parse (p/parser "S = 'x'") "y"))
=> [{:tag :string, :expecting "x", :full true}]
你可以这样做:
(with-out-str
(instaparse.failure/pprint-failure
(p/parse (p/parser "S = 'x'") "y")))
=> "Parse error at line 1, column 1:\ny\n^\nExpected:\n\"x\" (followed by end-of-string)\n"
或者编写您自己的版本pprint-failure
来构建一个字符串而不是打印它。