考虑精神规则的共同部分

时间:2012-11-14 22:08:01

标签: c++ boost-spirit

我有很多具有共同前缀和后缀的规则:

rule = begin_stuff >> some >> other >> stuff >> end_stuff.

(其中begin_stuffend_stuff由文字组成)

我希望能够说出

 rule = wrapped(some >> other >> stuff);

我尝试了一些

的内容
  template<typename Rule> Rule wrapped(Rule inside) 
  {
    Rule result;
    result = begin_stuff >> inside >> end_stuff;
    return result;
  }

但我得到的是Qi的许多编译时断言。

我怎样才能以这种方式重构精神规则?

2 个答案:

答案 0 :(得分:2)

我认为你正在寻找'subrules'(精神V1 /古典曾经有过)。现在已经过时了。

看看

  • c ++ 11 autoBOOST_AUTO

    auto subexpression = int_ >> ',' >> double_;
    qi::rule<It> rule  = "A:" >> subexpression >> "Rest:" >> (subexpression % eol);
    

    以前在精神规则上使用auto时遇到了问题(尤其是MSVC)(请参阅Zero to 60 MPH in 2 seconds!和评论),但我已经(很快)is no longer an issue了解了我:

    Yep. Anyway,FYI, it's fixed in Spirit-3. You can 
    use auto all you want. 
    
    Regards, 
    -- 
    Joel de Guzman
    
  • qi::lazy

  • inherited arguments - 在Mini XML - ASTs教程
  • 中介绍

这是一个概念证明,它将一个共同的子规则传递给不同的“复合”规则,以允许包裹在()[]{}中:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;

typedef std::string::const_iterator It;

template <typename R>
    void test(const std::string& input, R const& rule)
{
    It f(input.begin()), l(input.end());
    bool ok = qi::phrase_parse(f,l,rule,qi::space);
    std::cout << "'" << input << "'\tparse " << (ok?"success":"failure") << "\n";
}

int main()
{
    typedef qi::rule<It,                    qi::space_type> common_rule;
    typedef qi::rule<It, void(common_rule), qi::space_type> compound_rule;

    common_rule common = qi::int_;

    compound_rule 
        in_parens   = qi::lit('(') >> qi::_r1 >> ')',
        in_brackets = qi::lit('[') >> qi::_r1 >> ']',
        in_braces   = qi::lit('{') >> qi::_r1 >> '}';

    test("{ 231 }"  , in_braces  (phx::ref(common )) );
    test("{ hello }", in_braces  (phx::val("hello")) );

    test("( 231 )"  , in_parens  (phx::ref(common )) );
    test("( hello )", in_parens  (phx::val("hello")) );

    test("[ 231 ]"  , in_brackets(phx::ref(common )) );
    test("[ hello ]", in_brackets(phx::val("hello")) );
}

输出:

'{ 231 }'   parse success
'{ hello }' parse success
'( 231 )'   parse success
'( hello )' parse success
'[ 231 ]'   parse success
'[ hello ]' parse success

PS。请注意,上面的 不是 是典型的Spirit语法。当“共同”规则暴露不同的属性时,这种方式不会很好。

答案 1 :(得分:1)

我认为您需要使用Qi Confix Parser Derective中的Spirit Repository。这正是你所需要的。