Boost.Spirit: Difference between operators "%=" and "="
Asked Answered
T

1

6

I don't understand the difference between these two operators. Let's take an example parsing inputs like "AA,BB,CC,DD" into vector of strings.

namespace qi = boost::spirit::qi;
class my_grammar : public qi::grammar<string::const_iterator, string()>
{
public:
  my_grammar() : base_type(start) {
    using qi::_1;
    using qi::char_;
    start = *(char_ - qi::lit(','));
  }
  qi::rule<string::const_iterator, string()> start;
};

As far as I know, the a %= b is equivalent to a = b[_val = _1]. That's clear. But on the other hand, the parser *(char_ - qi::lit(',')) has a synthesised attribute of type std::string to which the matched sequence will be assigned. The result of using start = *(char_ - qi::lit(',')) is the same. So what's the case for using operator %=?

Talipes answered 8/2, 2016 at 21:18 Comment(3)
It's a faq stackoverflow.com/… - see also boost-spirit.com/home/2010/01/15/…, boost-spirit.com/home/articles/attribute_handling/… :)Nicolella
@Nicolella -- how would one proceed to find the matching answer in the FAQ?Silverman
@FrankPuck I stated the question is frequently asked. I didn't mean to imply there's an organized "FAQ" (unless you count this site)Nicolella
T
7

Ok, I've found it in boost documentation under Auto Rules:

 Note
 r %= p and r = p are equivalent if there are no semantic actions associated with p. 

So if the start rule contained semantic action ex.

*(char_[boost::phoenix::ref(my_string) = _1] - qi::lit(','))`

then changing the operator to %= would enable automatic attribute propagation, which would otherwise be inhibited by the presence of the semantic action.

Talipes answered 8/2, 2016 at 21:42 Comment(6)
Well done. It doesn't hurt documenting it once more in a (hopefully) searchable Q&ANicolella
I also read this and I'm still curious what the difference would be. Thanks for this void of information!Silverman
@FrankPuck I fixed the documentation link to be much more precise. I usually paraphrase as "semantic actions inhibit automatic attribute propagation (with %= initialization to override that" but apparently the documentation likes to come from the other end - emphasizing that %=-initialization enables automatic attribute propagation (and absense of semantic actions makes it the default). They're equivalent in the end.Nicolella
@FrankPuck Did that information help in any way? I'm asking because I'm answering a lot of your questions of late, but I never hear back unless it's complaints. I'm wondering if I'm doing the right things/things that are useful for you.Nicolella
@sehe: So the %= operator cancels the cancelation of default semantic actions. In above case qi::_val would contain a series of characters and my_string would contain the last character of the series?Silverman
@FrankPuck Exactly. I haven't tested this particular example, but it's the exact behaviour I expect to seeNicolella

© 2022 - 2024 — McMap. All rights reserved.