How to parse a string in spirit and use it as return value

91 Views Asked by At

I need to parse a key value pair, where key itself is a fixed string lke 'cmd' in the example. Unfortunately qi::lit has no synthesized attribute and qi::char_ parses no fixed string. Following code does not compile. I would need that result.name == cmd after execution.

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <iomanip>
#include <string>

namespace qi = boost::spirit::qi;
namespace px = boost::phoenix;

struct CommandRuleType
{
  std::string name;
  int arg;
};

BOOST_FUSION_ADAPT_STRUCT(CommandRuleType, name, arg)

int main() {
    qi::rule<std::string::const_iterator, CommandRuleType(), qi::space_type> rule = qi::lit("cmd") >> "=" >> qi::int_;

    for (std::string const s : {"cmd = 1" }) {
        std::cout << std::quoted(s) << " -> ";
        CommandRuleType result;
        if (qi::phrase_parse(s.begin(), s.end(), rule, qi::space, result)) {
            std::cout << "result: " << result.name << "=" << result.arg << "\n";
        } else {
            std::cout << "parse failed\n";
        }
    }
}
1

There are 1 best solutions below

1
On

qi::lit does not expose an attribute. qi::string does:

    rule = qi::string("cmd") >> "=" >> qi::int_;

Live On Coliru

#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iomanip>
#include <string>

namespace qi = boost::spirit::qi;
namespace px = boost::phoenix;

struct CommandRuleType {
    std::string name;
    int arg;
};

BOOST_FUSION_ADAPT_STRUCT(CommandRuleType, name, arg)

int main() {
    qi::rule<std::string::const_iterator, CommandRuleType(), qi::space_type>
        rule = qi::string("cmd") >> "=" >> qi::int_;

    for (std::string const s : { "cmd = 1" }) {
        std::cout << std::quoted(s) << " -> ";
        CommandRuleType result;
        if (qi::phrase_parse(s.begin(), s.end(), rule, qi::space, result)) {
            std::cout << "result: " << result.name << "=" << result.arg << "\n";
        } else {
            std::cout << "parse failed\n";
        }
    }
}

Prints

"cmd = 1" -> result: cmd=1