I have a data file format which includes
- /* comments */
- /* nested /* comments */ too */ and
- // c++ style single-line comments..
As usual, these comments can occur everywhere in the input file where normal white space is allowed.
Hence, rather than pollute the grammar proper with pervasive comment-handling, I have made a skipper parser which will handle white space and the various comments.
So far so good, and i am able to parse all my test cases.
In my use case, however, any of the parsed values (double, string, variable, list, ...) must carry the comments preceding it as an attribute, if one or more comments are present. That is, my AST node for double should be
struct Double {
double value;
std::string comment;
};
and so forth for all the values I have in the grammar.
Hence I wonder if it is possible somehow to "store" the collected comments in the skipper parser, and then have them available for building the AST nodes in the normal grammar?
The skipper which processes comments:
template<typename Iterator>
struct SkipperRules : qi::grammar<Iterator> {
SkipperRules() : SkipperRules::base_type(skipper) {
single_line_comment = lit("//") >> *(char_ - eol) >> (eol | eoi);
block_comment = ((string("/*") >> *(block_comment | char_ - "*/")) >> string("*/"));
skipper = space | single_line_comment | block_comment;
}
qi::rule<Iterator> skipper;
qi::rule<Iterator, std::string()> block_comment;
qi::rule<Iterator, std::string()> single_line_comment;
};
I can store the commments using a global variable and semantic actions in the skipper rule, but that seems wrong and probably won't play well in general with parser backtracking. What's a good way to store the comments so they are later retrievable in the main grammar?