我有一个递归语法,并希望从它的不同规则开始解析。是不是可以多次重写相同的语法?
示例:我有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 value ,但有时我需要将其解析为json array 或json object 。我可以不重写相同的语法,而这些语法之间的唯一区别是入口点吗?
答案 0 :(得分:1)
我发现最接近的解决方案是将语法拆分为基类和派生类,并在派生类中使用不同的启动规则。它不会重复复制源代码,但仍然看起来像是超重解决方案。
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_) {}
};