如何使用 FParsec 解析评论 [英] How to parse comments with FParsec

查看:13
本文介绍了如何使用 FParsec 解析评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 FParsec 从 s 表达式语言中解析 lisp 样式的注释.我在上一个线程中解析单行注释时得到了一些帮助 - How to convert用于解析空格的 FParsec 解析器

I'm attempting to parse lisp-style comments from an s-expression language with FParsec. I got a bit of help with parsing single-line comments in this previous thread - How to convert an FParsec parser to parse whitespace

虽然解决了,但我仍然需要解析多行注释.这是当前的代码 -

While that was resolved, I still need to parse multiline comments. Here's the current code -

/// Read whitespace character as a string.
let spaceAsStr = anyOf whitespaceChars |>> fun chr -> string chr

/// Read a line comment.
let lineComment = pchar lineCommentChar >>. restOfLine true

/// Read a multiline comment.
/// TODO: make multiline comments nest.
let multilineComment =
    between
        (pstring openMultilineCommentStr)
        (pstring closeMultilineCommentStr)
        (charsTillString closeMultilineCommentStr true System.Int32.MaxValue)

/// Read whitespace text.
let whitespace =
    lineComment <|>
    multilineComment <|>
    spaceAsStr

/// Skip any white space characters.
let skipWhitespace = skipMany whitespace

/// Skip at least one white space character.
let skipWhitespace1 = skipMany1 whitespace

不幸的是,multilineComment 解析永远不会成功.由于这是一个组合器,我无法放置断点或分析它为什么不起作用.

Unfortunately, the multilineComment parse never succeeds. Since this is a combinator, I can't put breakpoints or analyze why it won't work.

知道为什么它不起作用吗?

Any ideas why it won't work?

推荐答案

尝试将 closeMultilineCommentStr 的 bool 参数更改为 false

Try changing the bool argument for closeMultilineCommentStr to false

(charsTillString closeMultilineCommentStr false System.Int32.MaxValue)

否则它将跳过 closeMultilineCommentStr 字符串.

Otherwise it will skip over the closeMultilineCommentStr string.

使其与嵌套评论一起使用

To make it work with nested comments

let rec multilineComment o=
    let ign x = charsTillString x false System.Int32.MaxValue
    between
        (pstring openMultilineCommentStr)
        (pstring closeMultilineCommentStr)
        (attempt (ign openMultilineCommentStr >>. multilineComment >>. ign closeMultilineCommentStr) <|> 
        ign closeMultilineCommentStr) <|o

这篇关于如何使用 FParsec 解析评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆