【问题标题】:Boost Spirit x3: parse into structsBoost Spirit x3:解析为结构
【发布时间】:2017-08-14 11:20:55
【问题描述】:

来自 Boost Spirit X3 教程:

首先,让我们创建一个代表员工的结构:

namespace client { namespace ast
{
   struct employee
   {
       int age;
       std::string surname;
       std::string forename;
       double salary;
   };
}}

然后,我们需要告诉 Boost.Fusion 我们的员工结构,使其成为 语法可以利用的一等融合公民。

BOOST_FUSION_ADAPT_STRUCT(
    client::ast::employee,
    (int, age)
    (std::string, surname)
    (std::string, forename)
    (double, salary)
)`

[...] 在 fusion 看来,结构只是元组的一种形式。你可以适应任何 struct 是一个完全符合的融合元组。 [...] 应用我们上面的折叠规则,RHS 具有以下属性: fusion::vector<int, std::string, std::string, double> 结构员工兼容 融合::向量。 所以,start 的 RHS 就地使用 start 的属性(一个结构雇员) 当它工作时。

如果我很好理解的话,这个逻辑很大程度上依赖于属性的顺序。

现在,我需要解析类似的东西

Layer "L1" {
    number = 23
    color = green
    visible = true
}

进入结构

struct LayerInfo
{
    std::string layerName;
    int layerNumber;
    std::string color;
    bool visible;
}

问题是,图层属性的顺序可以改变,这与上面看到的逻辑相反。

解析成这样的结构的正确方法是什么? 我是否需要使用语义操作?

【问题讨论】:

  • I've tried 使用 fusion::map approach 来解决这个问题,这似乎是 Qi 排列解析器的替代方案。遗憾的是,我不得不对您的示例进行一些更改以使其工作:我'已经将可以在嵌套结构中重新排序的属性分组(我认为这是这种方法所必需的),并且我在每个属性之后添加了;(这绝对不是必需的,但简化了使用哪个船长)。如果您有兴趣,我可以将其作为答案。
  • @llonesmiz 确定!谢谢
  • @llonesmiz 非常流畅。我已经尝试过用更有活力的方式与事物作斗争。 IMO,目前这两种方法都有弱点。

标签: c++ boost boost-spirit boost-fusion boost-spirit-x3


【解决方案1】:

我喜欢@llonesmiz 在评论中的做法。

不过,我“不得不”尝试我最喜欢的 X3 使用函数组合的方法。这是解析和传播值的方法的草图。

缺少对属性存在/唯一性的检查。 (我认为使用基本上包含std::set<V T::*>x3::with<> 上下文添加是可行的。当然这样的事情需要(依赖于实现?)强制转换或擦除包装器)。

目前,不加评论地呈现:

Live On Coliru

#include <iostream>
//#define BOOST_SPIRIT_X3_DEBUG
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

struct LayerInfo
{
    std::string layerName;
    int layerNumber = 0;
    std::string color;
    bool visible = false;
};

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

    // custom type parsers
    auto quoted = rule<std::string>("quoted", x3::lexeme [ '"' >> *('\\' >> x3::char_ | ~x3::char_('"')) >> '"' ]);
    struct colors_type : x3::symbols<char> {
        colors_type() {
            this->add("red")("blue")("green")("black");
        }
    } static const colors;

    namespace detail {
        template <typename T> auto propagate(T member) {
            return [=](auto& ctx){ x3::traits::move_to(x3::_attr(ctx), x3::_val(ctx).*member); };
        }

        template <typename T> auto make_member_parser(int T::* const member) { return x3::int_ [propagate(member)]; }
        template <typename T> auto make_member_parser(bool T::* const member) { return x3::bool_ [propagate(member)]; }
        template <typename T> auto make_member_parser(std::string T::* const member) { return x3::raw[colors] [propagate(member)]; }

        template <typename T = LayerInfo, typename P>
            auto rule(const char* debug, P p) { return x3::rule<struct _, T> {debug} = x3::skip(x3::space)[p]; };

        auto property = [](auto label, auto member) {
            return rule(label, x3::as_parser(label) >> '=' >> make_member_parser(member));
        };
    }

    using detail::rule;
    using detail::propagate;
    using detail::property;

    auto name       = rule("name", "Layer" >> quoted [propagate(&LayerInfo::layerName)]);

    auto number     = property("number", &LayerInfo::layerNumber);
    auto color      = property("color", &LayerInfo::color);
    auto visible    = property("visible", &LayerInfo::visible);

    auto layer_info = name >> '{' >> +(number | color | visible) >> '}';

    auto grammar    = rule("layer_info", layer_info);
}

std::ostream& operator<<(std::ostream& os, LayerInfo const& li) {
    return os << "LayerInfo \"" << li.layerName << "\"{"
        << "number="  << li.layerNumber   << " "
        << "color="   << li.color         << " "
        << "visible=" << std::boolalpha << li.visible 
        << "}\n";
}

int main() {
    std::string const sample = R"(Layer "L1" {
    number = 23
    color = green
    visible = true
})";

    LayerInfo v;
    auto f = sample.begin(), l = sample.end();
    bool ok = parse(f, l, Parser::grammar, v);


    if (ok)
        std::cout << "Parsed: " << v << "\n";
    else
        std::cout << "Parse failed\n";

    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}

打印

Parsed: LayerInfo "L1"{number=23 color=green visible=true}

Wit 调试信息:Live On Coliru

<layer_info>
  <try>Layer "L1" {\n    num</try>
  <name>
    <try>Layer "L1" {\n    num</try>
    <quoted>
      <try> "L1" {\n    number =</try>
      <success> {\n    number = 23\n </success>
      <attributes>[L, 1]</attributes>
    </quoted>
    <success> {\n    number = 23\n </success>
    <attributes>LayerInfo "L1"{number=0 color= visible=false}
</attributes>
  </name>
  <number>
    <try>\n    number = 23\n   </try>
    <success>\n    color = green\n </success>
    <attributes>LayerInfo "L1"{number=23 color= visible=false}
</attributes>
  </number>
  <number>
    <try>\n    color = green\n </try>
    <fail/>
  </number>
  <color>
    <try>\n    color = green\n </try>
    <success>\n    visible = true\n</success>
    <attributes>LayerInfo "L1"{number=23 color=green visible=false}
</attributes>
  </color>
  <number>
    <try>\n    visible = true\n</try>
    <fail/>
  </number>
  <color>
    <try>\n    visible = true\n</try>
    <fail/>
  </color>
  <visible>
    <try>\n    visible = true\n</try>
    <success>\n}</success>
    <attributes>LayerInfo "L1"{number=23 color=green visible=true}
</attributes>
  </visible>
  <number>
    <try>\n}</try>
    <fail/>
  </number>
  <color>
    <try>\n}</try>
    <fail/>
  </color>
  <visible>
    <try>\n}</try>
    <fail/>
  </visible>
  <success></success>
  <attributes>LayerInfo "L1"{number=23 color=green visible=true}
</attributes>
</layer_info>

【讨论】:

  • 我正在尝试编译您在 VS2017 上提供的确切代码,但出现“属性没有预期大小”错误。在 Coliru 上一切正常,代码可以编译。这个错误的可能原因是什么?
  • 编译器 - 它不在 Spirit X3、AFAIK 的支持集中。 X3 仍处于试验阶段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多