Search code examples
boost-spiritboost-spirit-qi

boost::spirit::qi why doesn't recursive parser work as expected?


I'd like the grammar below to parse input such as

a_end
a_b_end
a_b_c_end

but it only parses a_end and fails on anything with more than one _. Here is the grammar:

template < typename Iterator >
struct recursive_parser : qi::grammar< Iterator >
{
    qi::rule< Iterator > start;
    qi::rule< Iterator > end;
    recursive_parser() : recursive_parser::base_type( start )
    {
        using namespace qi;
        end = string("_end") | start;
        start = +(char_ - '_') >> end;
    }
};

Are rules not designed to be used recursively or am I missing something more obvious?


Solution

  • With your grammar, and the input string a_b_end we have the following parsing occur:

    In Start: consume "a". Iterate into end.
    In End:   The next part of the string is not "_end", so the first alternative fails.
              Try the second alternative, which is to iterate into start.
    In Start: The next character is a "_", so start fails.
    

    So your grammar should be:

    end = string("end") | start;
    start = +(char_ - '_') >> '_' >> end;