I'm trying to Parse a String with Boost::Spirit, but i just cannot get it to work. I have no experience with Boost::Spirit since today.
The string is composed of commands separated by an ';'. The commands are
"INC someInteger"
"BOMB firstInteger secondInteger"
"MOVE firstInteger secondInteger thirdInteger"
"MSG someString"
"WAIT"
I Managed to get this far:
#include <boost/spirit/include/qi.hpp>
#include <boost/phoenix/phoenix.hpp>
using namespace boost::spirit;
int main() {
std::string testInput = "MOVE 1 2 43;BOMB 0 3;INC 6;MOVE 2 3 99;MOVE 1 2 6";
typedef std::string::iterator iter;
using boost::phoenix::ref;
iter start = testInput.begin();
std::vector<int> IncCommands;
std::vector<std::pair<int, int>> BombCommands;
std::vector<std::tuple<int, int, int>> MoveCommands;
qi::rule<iter, std::vector<int>(), ascii::space_type> nextIncrease = ("INC " >> qi::int_);
//qi::rule<iter, std::vector<std::pair<int, int>>(), ascii::space_type> nextBomb = ("BOMB " >> qi::int_ >> qi::int_);
//qi::rule<iter, std::vector<int>(), ascii::space_type> nextMove = ("MOVE " >> qi::int_ >> qi::int_ >> qi::int_);
//qi::rule<iter, std::string, ascii::space_type> nextAction = (nextMove | nextBomb | nextIncrease) % ';';
bool match = qi::phrase_parse(
start,
testInput.end(),
nextIncrease,
ascii::space,
IncCommands
);
return 0;
}
The Problems that i have now:
I don't know how i can extract more than 1 integer
I don't know how i can merge everything into a proper grammar so that everything is parsed into several vectors.
I didn't consider MSG and WAIT yet.
I'd suggest starting out with the desired AST as always.
Spirit works well with static polymorphism, so I'd use a variant to represent commands:
Now, write the most straight-forward grammar to match it:
Add in some glue for debug (Fusion adaptation and output streaming), and we have a working sample:
Live On Coliru
Which prints:
And optionally the BOOST_SPIRIT_DEBUG output: