如何在Boost.Spirit中跳过行/块/嵌套块注释? [英] How to skip line/block/nested-block comments in Boost.Spirit?

查看:66
本文介绍了如何在Boost.Spirit中跳过行/块/嵌套块注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Boost.Spirit解析语言时,如何确保跳​​过

When parsing a language using Boost.Spirit, how can I ensure that I skip

// line comments

/* block
   comments */ and

/* /* nested
   block */ comments */

何时阅读代码?此刻,我只是将phrase_parse转换为预定义的qi::grammar.我想我需要的是某种跳过词法分析器,对吧?

when reading in the code? At the moment, I just do a phrase_parse into a predefined qi::grammar. I guess what I need is some sort of skipping lexer, right?

推荐答案

无需词法分析器.

以下是实现该示例的示例语法:

Here's a sample grammar that implements it: Cross-platform way to get line number of an INI file where given option was found, but regardless you can use a skipper like this:

using Skipper = qi::rule<Iterator>;

Skipper block_comment, single_line_comment, skipper;

single_line_comment = "//" >> *(char_ - eol) >> (eol|eoi);
block_comment = "/*" >> *(block_comment | char_ - "*/") > "*/";

skipper = single_line_comment | block_comment;

当然,如果空白也是可以跳过的,请使用

Of course if white-space is also skippable, use

skipper = space | single_line_comment | block_comment;

这支持嵌套的块注释,如果缺少*/,则抛出qi::expectation_failure<>.

This supports nested block-comments, throwing qi::expectation_failure<> if there is a missing */.

请注意,它特别不支持以单行注释开头的块注释.

Note that it specifically doesn't support block comments starting in a single-line-comment.

在Coliru上直播

#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

int main() {
    using Iterator = boost::spirit::istream_iterator;
    using Skipper  = qi::rule<Iterator>;

    Skipper block_comment, single_line_comment, skipper;

    {
        using namespace qi;
        single_line_comment = "//" >> *(char_ - eol) >> (eol|eoi);
        block_comment       = ("/*" >> *(block_comment | char_ - "*/")) > "*/";

        skipper             = space | single_line_comment | block_comment;
    }

    Iterator f(std::cin >> std::noskipws), l;

    std::vector<int> data;
    bool ok = phrase_parse(f, l, *qi::int_, skipper, data);
    if (ok) {
        std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout << "Parsed ", " "));
        std::cout << "\n";
    } else {
        std::cout << "Parse failed\n";
    }

    if (f!=l) {
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
    }
}

哪些印刷品:

Parsed 123 456 567 901 

提供输入

123 // line comments 234

/* block 345
   comments */ 456

567

/* 678 /* nested
   789 block */ comments 890 */

901

这篇关于如何在Boost.Spirit中跳过行/块/嵌套块注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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