tzlaine / parser

A C++ parser combinator library.
Boost Software License 1.0
70 stars 12 forks source link

How to skip comments without producing attributes? #79

Closed akrzemi1 closed 5 months ago

akrzemi1 commented 5 months ago

This is more a request for an advice.

I want to parse a sequence of ints, skipping potential comments, and produce a vector<int>. Here's a sample input:

3 [comment][comment] 4 [comment]

I built the following parser:

const bp::rule<struct comment_tag> comment = "comment";
const auto comment_def = '[' >> *(bp::char_ - ']') >> ']';
BOOST_PARSER_DEFINE_RULES(comment);
auto parser = +(bp::int_ | comment);

But it doesn't do the trick: it puts a 0 to my vector upon every encountered comment. Boost.Spirit, due to its clever attribute transformation does exactly what I need.

Full example: https://godbolt.org/z/vsa5eK5Gx

Is there a way to write a parser for that that does not involve custom actions?

You can consider it a suggestion to document the differences between Boost.Spirit parsers and Boost.Parser parsers.

akrzemi1 commented 5 months ago

Also, why does it arbitrarily choose to produce value 0?

akrzemi1 commented 5 months ago

Skipper, fool! https://godbolt.org/z/dTcbqdzMK

I still wonder about the zero, though.

tzlaine commented 5 months ago

Also, why does it arbitrarily choose to produce value 0?

First, this question. It produces an int, value-initialized, because you told it to. :) int_ | comment has the attribute type int, and always succeeds. If it matches an int, it's the value of that int. If it does not, it's the initial value of the attribute, which as I said is value-initialized, or 0 for an int.

tzlaine commented 5 months ago

Skipper, fool! https://godbolt.org/z/dTcbqdzMK

I still wonder about the zero, though.

I wasn't going to call you a fool, but this is exactly right! :)