7

在我的boost::spirit语法中,我有以下片段;

implicit_method_declaration = (-(qi::token(ABSTRACT)) >> ...)

然而,我只使用这个构造来检查 abstract 关键字是否真的存在,也就是说,我宁愿拥有-(qi::token(ABSTRACT)带有value的类型。boost::optional<boost::iterator_range<std::string::iterator>>-(qi::token(ABSTRACT)boolboost::optional<...> operator bool() const

我将如何实现这一目标?

4

1 回答 1

6

我想你正在寻找qi::matches[]

implicit_method_declaration = 
     qi::matches[qi::token(ABSTRACT)] >> ...;

另一种方法是qi::attr()与替代品一起使用:

implicit_method_declaration = 
       (
           qi::token(ABSTRACT) >> qi::attr(true) 
         | qi::attr(false)
       ) >> ...;

再次快速演示: http: //coliru.stacked-crooked.com/a/ed8bbad53e8c1943

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

namespace qi    = boost::spirit::qi;

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

        implicit_method_declaration = matches["abstract"];

        BOOST_SPIRIT_DEBUG_NODES((implicit_method_declaration));
    }

  private:
    qi::rule<It, bool(), Skipper> implicit_method_declaration;
};

bool doParse(const std::string& input)
{
    typedef std::string::const_iterator It;
    auto f(begin(input)), l(end(input));

    parser<It, qi::space_type> p;
    bool data;

    try
    {
        bool ok = qi::phrase_parse(f,l,p,qi::space,data);
        if (ok)   
        {
            std::cout << "parse success\n";
            std::cout << "data: " << data << "\n";
        }
        else      std::cerr << "parse failed: '" << std::string(f,l) << "'\n";

        if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
        return ok;
    } catch(const qi::expectation_failure<It>& e)
    {
        std::string frag(e.first, e.last);
        std::cerr << e.what() << "'" << frag << "'\n";
    }

    return false;
}

int main()
{
    doParse("abstract");
    doParse("static final");
}

输出

parse success
data: 1
parse success
data: 0
trailing unparsed: 'static final' 
于 2013-09-10T09:14:52.590 回答