【发布时间】:2014-05-09 08:30:43
【问题描述】:
我正在使用 spirit::qi 语法,它构造并返回非平凡对象作为它们的综合属性。问题是我希望语法递归地相互依赖。使用递归规则很简单,但我想要递归语法。
这是一些示例代码。注意说 CIRCULAR REFERENCE 的 cmets。显然,如果我取消注释这些行,这将无法编译,因为 FooGrammar 和 BarGrammar 对象相互包含。
我可以想到两种方法来达到预期的效果,但我似乎无法让它们与 qi 一起工作:
使 BarGrammar 持有指向 FooGrammar 的(智能)指针。它需要将 FooGrammar 构建为 lit("start_bar") 上的语义操作。但是我不知道 qi 内部结构是否安全——我需要维护自己的显式 FooGrammars 堆栈吗?什么时候可以安全销毁?
BarGrammar 可以将 FooGrammar 作为其 qi::locals 之一。但是由于某种原因,如果我尝试将 qi::locals 中的语法传递给继承属性,我将无法编译它。
是否有任何规范的方法来制作递归语法?
.
#include <boost/fusion/include/std_pair.hpp>
#include <boost/optional.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/spirit/include/phoenix_bind.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/variant.hpp>
namespace phoenix = boost::phoenix;
namespace spirit = boost::spirit;
namespace ascii = spirit::ascii;
namespace qi = spirit::qi;
using ascii::space_type;
using phoenix::ref;
using qi::grammar;
using qi::lit;
using qi::_r1;
using qi::_val;
using qi::lit;
using qi::omit;
using qi::rule;
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
typedef int Reffy;
struct Foo {
int foo;
};
struct Bar {
int bar;
};
template <typename Iterator>
struct BarGrammar;
template <typename Iterator>
struct FooGrammar : grammar<Iterator, Foo(Reffy&), space_type> {
FooGrammar() : FooGrammar::base_type(foo_) {
foo_ = lit("start_foo")[_val = phoenix::construct<Foo>()]
> -bar_(_r1)
> lit("end_foo");
;
}
BarGrammar<Iterator> bar_;
rule<Iterator, Foo(Reffy&), space_type> foo_;
};
template <typename Iterator>
struct BarGrammar : grammar<Iterator, Bar(Reffy&), space_type> {
BarGrammar() : BarGrammar::base_type(bar_) {
bar_ = lit("start_bar")[_val = phoenix::construct<Bar>()]
//> -foo_(_r1) // CIRCULAR REFERENCE
> lit("end_bar");
}
//FooGrammar<Iterator> foo_; // CIRCULAR REFERENCE
rule<Iterator, Bar(Reffy&), space_type> bar_;
};
int main(int argc, char *argv[]) {
Reffy reffy(0);
FooGrammar<string::iterator> foog;
rule<string::iterator, space_type> top_rule = omit[ foog(ref(reffy)) ];
string input("start_foo start_bar end_bar end_foo");
string::iterator begin = input.begin();
string::iterator end = input.end();
if(qi::phrase_parse(begin, end, top_rule, ascii::space)) {
cout << "passed" << endl;
} else {
cout << "failed" << endl;
}
return 0;
}
提前致谢!!
【问题讨论】:
标签: c++ boost-spirit-qi