英斯塔帕斯可以将漂亮的错误消息打印到REPL。
=> (negative-lookahead-example "abaaaab")
Parse error at line 1, column 1:
abaaaab
^
Expected:
NOT "ab"但是我找不到一个内置函数来将消息作为字符串来获取。怎么做?
发布于 2018-10-12 18:46:11
您可以始终使用with-out-str包装它。
(with-out-str
(negative-lookahead-example "abaaaab"))您也可能对使用with-err-str 记录在这里感兴趣。
(with-err-str
(negative-lookahead-example "abaaaab"))我不记得instaparse是写到stdout还是stderr,但是其中一个会做您想做的事情。
发布于 2018-10-12 20:08:42
让我们看看失败情况下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,生成一个字符串而不是打印它。
https://stackoverflow.com/questions/52785284
复制相似问题