【问题标题】:Parsec - improving error message for "between"Parsec - 改进“之间”的错误消息
【发布时间】:2021-10-23 18:53:36
【问题描述】:

我正在学习 Parsec。我有这个代码:

import Text.Parsec.String (Parser)
import Control.Applicative hiding ((<|>))
import Text.ParserCombinators.Parsec hiding (many)

inBracketsP :: Parser [String]
inBracketsP = (many $ between (char '[') (char ']') (many $ char '.')) <* eof

main :: IO ()
main =  putStr $ show $ parse inBracketsP "" "[...][..."

结果是

Left (line 1, column 10):
unexpected end of input
expecting "." or "]"

此消息没有用(添加. 不会解决问题)。我希望像']' expected 这样的东西(只有] 解决了这个问题)。

使用 Parsec 可以轻松实现这一目标吗?我已经看到了 SO 问题 Parsec: error message at specific location,这很鼓舞人心,但如果可能的话,我更愿意坚持使用 between 组合器,而不需要手动前瞻或其他过度工程(某种)。

【问题讨论】:

  • 但是没有规定最多有 3 个点,所以另一个 . 可以去那里。
  • 是的,将解析另一个点(因此是默认错误消息)。但是,我希望解析错误指示丢失的结束标记,而不是列出将要解析的所有内容(在语法更复杂的情况下会列出很多内容)。

标签: haskell parsec


【解决方案1】:

您可以通过将空标签附加到终端(parser &lt;?&gt; "")来隐藏终端,使其不显示在预期的输入列表中:

inBracketsP :: Parser [String]
inBracketsP = (many $ between (char '[') (char ']') (many $ (char '.' <?> ""))) <* eof

-- >>> main
-- Left (line 1, column 10):
-- unexpected end of input
-- expecting "]"

在megaparsec中,也有一个hidden combinator可以达到同样的效果。

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多