【问题标题】:How do you implement a custom parser object with boost spirit x3 such that it plays nice with a skipper?您如何使用 boost spirit x3 实现自定义解析器对象,以便它与船长配合得很好?
【发布时间】:2020-01-28 16:21:41
【问题描述】:

我知道我可以通过使用适当的“解析”成员函数模板创建一个对象来实现自定义解析器,但我不知道我需要做什么才能使它使用上下文中的船长,这似乎需要做。也就是说,下面我预计两种情况都会成功,但第二种失败:

namespace x3 = boost::spirit::x3;

namespace parser {

    struct foobar : x3::parser<foobar> {

        using attribute_type = std::string;

        template<typename Iterator, typename Context, typename RContext, typename Attribute>
        bool parse(Iterator& first, Iterator const& last, Context const& context,
            RContext const& rcontext, Attribute& attr) const
        {
            static const std::string foobar_str = "foobar";
            auto i = first;
            auto j = foobar_str.begin();
            while (i != last && j != foobar_str.end()) {
                if (*i++ != *j++)
                    return false;
            }
            first = i;
            attr = foobar_str;
            return true;
        };
    };

    const auto foo = foobar();
}

int main()
{
    std::string input = "foobarfoobarfoobar";
    std::vector<std::string> strings;

    auto foobars = parser::foo >> parser::foo >> parser::foo;

    bool success = x3::phrase_parse(input.begin(), input.end(), foobars, x3::space, strings);
    if (success)
        std::cout << "yes\n";  // yes for this one
    else
        std::cout << "no\n";

    input = "foobar    foobar    foobar";
    success = x3::phrase_parse(input.begin(), input.end(), foobars, x3::space, strings);
    if (success) 
        std::cout << "yes\n"; 
    else 
        std::cout << "no\n";  // no because of the spaces
}

【问题讨论】:

    标签: boost boost-spirit boost-spirit-x3


    【解决方案1】:

    您可以通过从上下文中获取它来简单地应用船长。由您决定何时使用它(例如,后跳过是否是行为的一部分),但我想当有一个活跃的跳过者时,预跳过是隐含的。

    如果你从 x3::parser_base 继承,你可以简单地调用

     skip_over(f, l, ctx);
    

    完成这项工作。

    查看示例X3 parse rule doesn't compile

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多