如何在Boost.Spirit中跳过行/块/嵌套块注释? [英] How to skip line/block/nested-block comments in 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.
#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屋!