如何使用单独的访问者类制作递归Spirit X3解析器

时间:2019-06-21 13:52:54

标签: gcc boost c++17 boost-spirit boost-spirit-x3

我正在处理递归规则调用的解析器应用程序。除了查看Boost Spirit X3的递归AST教程示例外,还可以在这里找到: https://www.boost.org/doc/libs/develop/libs/spirit/doc/x3/html/index.html,我正在寻找一种带有某些类型的std :: variant以及相同类型的std :: vector的解决方案 变体类型。

在标题为Recursive rule in Spirit.X3的StackOverflow帖子中,我从sehe的答案中发现了代码,这是解析器的一个不错的起点。

我在这里重复了代码,但是我限制了要测试的输入字符串。因为原始文档的完整列表与此处的问题无关。

//#define BOOST_SPIRIT_X3_DEBUG
#include <iostream>
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>
#include <string>
#include <vector>
#include <variant>

struct value: std::variant<int,float,std::vector<value>>
{
    using base_type = std::variant<int,float,std::vector<value>>;
    using base_type::variant;

    friend std::ostream& operator<<(std::ostream& os, base_type const& v) {
        struct {
            std::ostream& operator()(float const& f) const { return _os << "float:" << f; }
            std::ostream& operator()(int const& i)   const { return _os << "int:" << i; }
            std::ostream& operator()(std::vector<value> const& v) const {
                _os << "tuple: [";
                for (auto& el : v) _os << el << ",";
                return _os << ']';
            }
            std::ostream& _os;
        } vis { os };

        return std::visit(vis, v);
    }
};

namespace parser {
    namespace x3 = boost::spirit::x3;

    x3::rule<struct value_class, value> const value_ = "value";
    x3::rule<struct o_tuple_class, std::vector<value> > o_tuple_ = "tuple";

    x3::real_parser<float, x3::strict_real_policies<float> > float_;

    const auto o_tuple__def = "tuple" >> x3::lit(':') >> ("[" >> value_ % "," >> "]");

    const auto value__def
        = "float" >> (':' >> float_)
        | "int" >> (':' >> x3::int_)
        | o_tuple_
        ;

    BOOST_SPIRIT_DEFINE(value_, o_tuple_)

    const auto entry_point = x3::skip(x3::space) [ value_ ];
}

int main()
{
    for (std::string const str : {
            "float: 3.14",
            "int: 3",
            "tuple: [float: 3.14,int: 3]",
            "tuple: [float: 3.14,int: 3,tuple: [float: 4.14,int: 4]]"
    }) {
        std::cout << "============ '" << str << "'\n";

        //using boost::spirit::x3::parse;
        auto first = str.begin(), last = str.end();
        value val;

        if (parse(first, last, parser::entry_point, val))
            std::cout << "Parsed '" << val << "'\n";
        else
            std::cout << "Parse failed\n";

        if (first != last)
            std::cout << "Remaining input: '" << std::string(first, last) << "'\n";
    }
}

但是,我想使用传统的访问者类,而不是让ostream在变体类中成为朋友。您只知道一个结构体/类,对于在变体中遇到的每种类型,它都有一堆函数对象,对于每个调用std :: visit的向量,它的向量都为“ for循环” 元素。

对于传统的访问者类,我的目标是能够在打印期间维护状态机。

我自己编写此访问者类的尝试失败了,因为我遇到了GCC 8.1编译器的问题。在编译期间使用GCC的std :: variant碰巧是std :: variant_size,我收到以下错误:

error: incomplete type 'std::variant_size' used in nested name specifier

有关此的更多信息: Using std::visit on a class inheriting from std::variant - libstdc++ vs libc++

是否可以对GCC施加这种约束,以便为我包含的代码示例编写一个访问者类,以便可以删除ostream内容?

1 个答案:

答案 0 :(得分:2)

  

是否可以对GCC施加这种约束,以便为我包含的代码示例编写一个访问者类,以便可以删除ostream内容?

好的。基本上,我看到三种方法:

1。添加模板机器

您可以专门设置GCC意外要求的实施细节:

struct value: std::variant<int,float,std::vector<value>> {
    using base_type = std::variant<int,float,std::vector<value>>;
    using base_type::variant;
};

namespace std {
    template <> struct variant_size<value> :
std::variant_size<value::base_type> {};
    template <size_t I> struct variant_alternative<I, value> :
std::variant_alternative<I, value::base_type> {};
}

查看 live on Wandbox (GCC 8.1)

2。不要(再次 live

扩展std名称空间很麻烦(尽管我认为这对于合法 用户定义的类型)。因此,您可以采用我最喜欢的图案并隐藏 e std::visit在函数对象本身中调度:

template <typename... El>
    void operator()(std::variant<El...> const& v) const { std::visit(*this, v); }

现在您可以简单地调用函子,它将自动分派 在您自己的变量派生类型上,因为operator()重载确实 没有GCC stdlib所具有的问题:

    if (parse(first, last, parser::entry_point, val))
    {
        display_visitor display { std::cout };

        std::cout << "Parsed '";
        display(val);
        std::cout << "'\n";
    }

3。使事情明确

我至少喜欢这个,但它确实有优点:没有魔术,也没有 技巧:

struct value: std::variant<int,float,std::vector<value>> {
    using base_type = std::variant<int,float,std::vector<value>>;
    using base_type::variant;

    base_type const& as_variant() const { return *this; }
    base_type&       as_variant() { return *this; }
};

struct display_visitor {
    void operator()(value const& v) const { std::visit(*this, v.as_variant()); }
     // ...

再次 live

摘要

考虑了更多之后,由于相对简单,我建议使用最后一种方法。聪明常常是代码气味:)

供将来访问者使用的完整列表:

//#define BOOST_SPIRIT_X3_DEBUG
#include <iostream>
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>
#include <string>
#include <vector>
#include <variant>

struct value: std::variant<int,float,std::vector<value>> { 
    using base_type = std::variant<int,float,std::vector<value>>;
    using base_type::variant;

    base_type const& as_variant() const { return *this; }
    base_type&       as_variant() { return *this; }
};

struct display_visitor {
    std::ostream& _os;
    void operator()(value const& v) const { std::visit(*this, v.as_variant()); }
    void operator()(float const& f) const { _os << "float:" << f; }
    void operator()(int const& i)   const { _os << "int:" << i; }
    void operator()(std::vector<value> const& v) const { 
        _os << "tuple: [";
        for (auto& el : v) {
            operator()(el);
            _os << ",";
        }
        _os << ']';
    }
};

namespace parser {
    namespace x3 = boost::spirit::x3;

    x3::rule<struct value_class, value> const value_ = "value";
    x3::rule<struct o_tuple_class, std::vector<value> > o_tuple_ = "tuple";

    x3::real_parser<float, x3::strict_real_policies<float> > float_;

    const auto o_tuple__def = "tuple" >> x3::lit(':') >> ("[" >> value_ % "," >> "]");

    const auto value__def
        = "float" >> (':' >> float_)
        | "int" >> (':' >> x3::int_)
        | o_tuple_
        ;

    BOOST_SPIRIT_DEFINE(value_, o_tuple_)

    const auto entry_point = x3::skip(x3::space) [ value_ ];
}

int main()
{
    for (std::string const str : {
        "float: 3.14",
        "int: 3",
        "tuple: [float: 3.14,int: 3]",
        "tuple: [float: 3.14,int: 3,tuple: [float: 4.14,int: 4]]"
    }) {
        std::cout << "============ '" << str << "'\n";

        //using boost::spirit::x3::parse;
        auto first = str.begin(), last = str.end();
        value val;

        if (parse(first, last, parser::entry_point, val))
        {
            display_visitor display { std::cout };

            std::cout << "Parsed '";
            display(val);
            std::cout << "'\n";
        }
        else
            std::cout << "Parse failed\n";

        if (first != last)
            std::cout << "Remaining input: '" << std::string(first, last) << "'\n";
    }
}