boost :: spirit :: qi为什么递归解析器没有按预期工作?

时间:2012-09-01 08:47:45

标签: boost-spirit boost-spirit-qi

我喜欢下面的语法来解析输入,例如

a_end
a_b_end
a_b_c_end

但它仅解析a_end并且对包含多个_的任何内容都失败。这是语法:

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;
    }
};

规则是不是设计为递归使用还是我遗漏了一些更明显的东西?

1 个答案:

答案 0 :(得分:3)

使用您的语法和输入字符串a_b_end,我们会进行以下解析:

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.

所以你的语法应该是:

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