Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c++ - boost::spirit::x3 attribute compatibility rules, intuition or code?

Is there a document somewhere which describes how various spirit::x3 rule definition operations affect attribute compatibility?

I was surprised when:

x3::lexeme[ x3::alpha > *(x3::alnum | x3::char_('_')) ]

could not be moved into a fusion-adapted struct:

struct Name {
    std::string value;
};

For the time being, I got rid of the first mandatory alphabetical character, but I would still like to express a rule which defines that the name string must begin with a letter. Is this one of those situations where I need to try adding eps around until it works, or is there a stated reason why the above couldn't work?

I apologize if this has been written down somewhere, I couldn't find it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're not on the develop branch you don't have the fix for that single-element sequence adaptiation bug, so yeah it's probably that.

Due to the genericity of attribute transformation/propagation, there's a lot of wiggle room, but of course it's just documented and ultimately in the code. In other words: there's no magic.

In the Qi days I'd have "fixed" this by just spelling out the desired transform with qi::as<> or qi::attr_cast<>. X3 doesn't have it (yet), but you can use a rule to mimick it very easily:

Live On Coliru

#include <iostream>
#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/home/x3.hpp>

namespace x3 = boost::spirit::x3;

struct Name {
    std::string value;
};

BOOST_FUSION_ADAPT_STRUCT(Name, value)

int main() {

    std::string const input = "Halleo123_1";
    Name out;

    bool ok = x3::parse(input.begin(), input.end(),
            x3::rule<struct _, std::string>{} =
            x3::alpha >> *(x3::alnum | x3::char_('_')),
            out);

    if (ok)
        std::cout << "Parsed: " << out.value << "
";
    else
        std::cout << "Parse failed
";
}

Prints:

Parsed: Halleo123_1

Automate it

Because X3 works so nicely with c++14 core language features, it's not hard to reduce typing:

Understanding the List Operator (%) in Boost.Spirit


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...