我有一个递归语法,想从不同的规则开始解析。是否可以不重写几次相同的语法?

示例:我有json解析器:

template <typename It, typename Skipper = qi::space_type>
struct grammar : qi::grammar<It, value (), Skipper>
{
  grammar () : grammar::base_type (value_)
  {
    using namespace qi;

    static auto const null_ = proto::deep_copy ("null" >> qi::attr (null {}));

    static auto const bool_ = proto::deep_copy (
      "true" >> qi::attr (true) | "false" >> qi::attr (false));

    static auto const text_ = proto::deep_copy (
      '"' >> qi::raw [*('\\' >> qi::char_ | ~qi::char_('"'))] >> '"');

    value_  = null_ | bool_ | text_ | double_ | object_ | array_;
    member_ = text_ >> ':' >> value_;
    object_ = '{' >> -(member_ % ',') >> '}';
    array_  = '[' >> -(value_ % ',') >> ']';

    BOOST_SPIRIT_DEBUG_NODES((value_)(member_)(object_)(array_))
  }

private:
  qi::rule<It, json:: value (), Skipper> value_;
  qi::rule<It, json::member (), Skipper> member_;
  qi::rule<It, json::object (), Skipper> object_;
  qi::rule<It, json:: array (), Skipper> array_;
};

通常,我需要将输入解析为json ,但有时我需要将其解析为json 数组或json 对象。我可以在不重写相同语法的情况下重复做这些语法之间唯一的区别是入口点吗?

最佳答案

我发现最接近的解决方案是将语法分为基类和派生类,并在派生类中使用不同的开始规则。它并没有大量复制源代码,但看起来仍然是超重解决方案。

template <typename It, typename Data, typename Skipper = qi::space_type>
struct base : qi::grammar<It, Data (), Skipper>
{
  using jbase_type = base;

  template <typename Member>
  base (Member& member) : base::base_type (member)
  {
    using namespace qi;
    using namespace Json;

    value_  = null_ | bool_ | text_ | double_ | object_ | array_;
    member_ = text_ >> ':' >> value_;
    object_ = '{' >> -(member_ % ',') >> '}';
    array_  = '[' >> -(value_ % ',') >> ']';

    BOOST_SPIRIT_DEBUG_NODES((value_)(member_)(object_)(array_))
  }

protected:
  escaped_string_grammar<It> text_;

  qi::rule<It, Json:: Value (), Skipper> value_;
  qi::rule<It, Json::Member (), Skipper> member_;
  qi::rule<It, Json::Object (), Skipper> object_;
  qi::rule<It, Json:: Array (), Skipper> array_;
};

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename It, typename Skipper = qi::space_type>
struct value : base<It, Json::Value, Skipper>
{
  value () : value::jbase_type (value::jbase_type::value_) {}
};

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename It, typename Skipper = qi::space_type>
struct array : base<It, Json::Array, Skipper>
{
  array () : array::jbase_type (array::jbase_type::array_) {}
};

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename It, typename Skipper = qi::space_type>
struct object : base<It, Json::Object, Skipper>
{
  object () : object::jbase_type (object::jbase_type::object_) {}
};

关于c++ - Boost.Spirit Qi:同一语法的不同切入点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31953100/

10-11 22:38
查看更多