我想解析一个布尔表达式(在C++中).输入表格:
a and b xor (c and d or a and b);
Run Code Online (Sandbox Code Playgroud)
我只想将这个表达式解析为树,知道优先级规则(不是,和,xor,或).所以上面的表达式应该类似于:
(a and b) xor ((c and d) or (a and b));
Run Code Online (Sandbox Code Playgroud)
到解析器.
树将是以下形式:
a
and
b
or
c
and
d
xor
a
and
b
Run Code Online (Sandbox Code Playgroud)
输入将通过命令行或以字符串的形式.我只需要解析器.
有没有可以帮助我做到这一点的消息来源?
我的boost :: spirit解析器还有另外一个问题.
template<typename Iterator>
struct expression: qi::grammar<Iterator, ast::expression(), ascii::space_type> {
expression() :
expression::base_type(expr) {
number %= lexeme[double_];
varname %= lexeme[alpha >> *(alnum | '_')];
binop = (expr >> '+' >> expr)[_val = construct<ast::binary_op<ast::add>>(_1,_2)]
| (expr >> '-' >> expr)[_val = construct<ast::binary_op<ast::sub>>(_1,_2)]
| (expr >> '*' >> expr)[_val = construct<ast::binary_op<ast::mul>>(_1,_2)]
| (expr >> '/' >> expr)[_val = construct<ast::binary_op<ast::div>>(_1,_2)] ;
expr %= number | varname | binop;
}
qi::rule<Iterator, ast::expression(), ascii::space_type> expr;
qi::rule<Iterator, ast::expression(), ascii::space_type> binop;
qi::rule<Iterator, std::string(), ascii::space_type> varname;
qi::rule<Iterator, …Run Code Online (Sandbox Code Playgroud)