所以我在boost::spirit
解析器中有这个相当丑陋的规则;
qi::rule<Iterator, bool()> empty_brackets;
...
empty_brackets = (qi::token(LEFT_BRACKET) >> qi::token(RIGHT_BRACKET))
[ qi::_val = true ]
;
该规则用作;
array_typeexp = (primitive_typeexp >> +(empty_brackets))
所以我真正想要的是,对于第二个参数(qi::_2
),不是std::vector<bool>
,而是unsigned int
,描述了'empty_brackets'
的次数匹配。
我将如何实现这一目标?
答案 0 :(得分:2)
我真的不确定你需要什么,但是,嘿:/
我建议
empty_brackets = lit('(') >> lit(')');
n_empty_brackets = eps [ _val = 0 ] >> +empty_brackets [ ++_val ];
array_typeexp = primitive_typeexp >> n_empty_brackets;
为简单起见,我已将primitive_typeexp
设为“无操作”,因此最简单的规则会在此简单设置中返回 unsigned
值:
qi::rule<It, unsigned(), Skipper> array_typeexp, n_empty_brackets;
qi::rule<It, Skipper> empty_brackets, primitive_typeexp;
查看完整示例 Live on Coliru
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
template <typename It, typename Skipper = qi::space_type>
struct parser : qi::grammar<It, unsigned(), Skipper>
{
parser() : parser::base_type(array_typeexp)
{
using namespace qi;
empty_brackets = lit('(') >> lit(')');
n_empty_brackets = eps [ _val = 0 ] >> +empty_brackets [ ++_val ];
array_typeexp = primitive_typeexp >> n_empty_brackets;
// TODO
primitive_typeexp = eps;
BOOST_SPIRIT_DEBUG_NODES((array_typeexp)(n_empty_brackets)(empty_brackets)(primitive_typeexp));
}
private:
qi::rule<It, unsigned(), Skipper> array_typeexp, n_empty_brackets;
qi::rule<It, Skipper> empty_brackets, primitive_typeexp;
};
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;
unsigned 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("() () ( ) ()");
doParse("()");
}