1

Instaparse可以将漂亮的错误消息打印到 REPL

=> (negative-lookahead-example "abaaaab")
Parse error at line 1, column 1:
abaaaab
^
Expected:
NOT "ab"

但我找不到将消息作为字符串获取的内置函数。怎么做?

4

2 回答 2

2

您总是可以使用以下方法包装它with-out-str

(with-out-str 
  (negative-lookahead-example "abaaaab"))

您可能也有兴趣使用with-err-str 这里记录的

(with-err-str 
  (negative-lookahead-example "abaaaab"))

我不记得是否instaparse写入标准输出或标准错误,但其中之一会做你想要的。

于 2018-10-12T18:46:11.643 回答
2

我们来看看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来构建一个字符串而不是打印它。

于 2018-10-12T20:08:42.213 回答