I've been implementing boost::spirit into a project and one of my challenges is to parse directly into a container of the type:
map<string, string>
I'm almost there. The issue I've run up against is assigning the key value of the std::pair automatically. That is, each token in my input string has a pre-determined key, and I want that to be automatically inserted ito the pair when the token is parsed.
I think I'm close, but maybe not... Here's the (truncated) grammar:
command =
string( "select" )
;
key = string( "command" ) | qi::attr( std::string("command") );
command_pair = key >> ' ' >> command;
start =
command_pair >> *command_pair
;
qi::rule<Iterator, std::string()> command;
qi::rule<Iterator, std::pair<std::string, std::string>()> command_pair;
qi::rule<Iterator,parserMap()> start;
The end result is to type on the command line:
select
and have the parser insert "command" as the key, as though I'd typed:
command select
thus, accessing the map["command"] element will return a value of "select".
The problem is, I can't get qi::attr() to do the job. That is, it works if I type "command select", but not just "select".
It would appear I was making it more difficult than need be.
The solution lay in a part of the code I hadn't quoted. I was calling my grammar using parse and not phrase_parse(). Enabling automatic space-skipping.