在 Instaparse 中以字符串形式获取错误消息的最简单方法?
Easiest way to get an error message as a string in Instaparse?
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
documented here。
(with-err-str
(negative-lookahead-example "abaaaab"))
我不记得 instaparse
是否写入 stdout 或 stderr,但其中之一会执行您想要的操作。
我们再看看失败案例中parse
的return类型:
(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
版本来构建字符串而不是打印字符串。
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
documented here。
(with-err-str
(negative-lookahead-example "abaaaab"))
我不记得 instaparse
是否写入 stdout 或 stderr,但其中之一会执行您想要的操作。
我们再看看失败案例中parse
的return类型:
(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
版本来构建字符串而不是打印字符串。