Question

I have the following code:

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/spirit/include/qi.hpp>

#include <iostream>
#include <string>

struct function
{
  std::string ret_type;
  std::string name;
};

BOOST_FUSION_ADAPT_STRUCT(
  ::function,
  (std::string, ret_type)
  (std::string, name)
)

template <typename Iterator>
struct function_parser : boost::spirit::qi::grammar<Iterator, function(), boost::spirit::qi::ascii::space_type>
{
  function_parser() : function_parser::base_type(start)
  {
    using boost::spirit::qi::ascii::char_;
    using boost::spirit::qi::int_;

    start %= +char_ >> +char_;
  }

  boost::spirit::qi::rule<Iterator, function(), boost::spirit::qi::ascii::space_type> start;
};

int main()
{
  std::string input_data("void foo");

  function fn;
  auto itr = input_data.begin();
  auto end = input_data.end();
  function_parser<decltype(itr)> g;
  bool res = boost::spirit::qi::phrase_parse(itr, end, g, boost::spirit::ascii::space, fn);
  if (res && itr == end)
  {
    std::cout << boost::fusion::tuple_open('[');
    std::cout << boost::fusion::tuple_close(']');
    std::cout << boost::fusion::tuple_delimiter(", ");

    std::cout << "Parsing succeeded\n";
    std::cout << "got: " << boost::fusion::as_vector(fn) << std::endl;
  }
  else
  {
    std::cout << "Parsing failed \n";
  }
}

Output

Parsing failed

What am I doing wrong? How can I fix it?

Was it helpful?

Solution

+char_

eats all input! Now, the next

+char_

requires at least a single character, which isn't there (the first kleen plus ate it) so the parse fails.

I suggest instead:

    using namespace boost::spirit::qi;

    start = lexeme[+graph] >> lexeme[+graph];

The documentation should be able to tell you what that does (I hope. No time to elaborate)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top