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

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

问题描述

我正在尝试使用FParsec从S表达式语言中解析Lisp样式的注释.在上一个线程中,我在解析单行注释时获得了一些帮助-如何转换一个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天全站免登陆