Boolean Expression Grammar Parser in C
Problem:
Parse a boolean expression given as a string and construct a tree representing the expression's syntax tree. The tree should follow the precedence rules (NOT, AND, XOR, OR).
Answer:
Using Boost Spirit:
Define a recursive variant type (expr) to represent the tree nodes:
Example Usage:
using namespace qi; using namespace phoenix; typedef std::string var; template <typename tag> struct binop; template <typename tag> struct unop; typedef boost::variant<var, boost::recursive_wrapper<unop<op_not>>, boost::recursive_wrapper<binop<op_and>>, boost::recursive_wrapper<binop<op_xor>>, boost::recursive_wrapper<binop<op_or>>> expr; struct parser : grammar<It, expr(), Skipper> { parser() : parser::base_type(expr_) { not_ = ... or_ = ... xor_ = ... and_ = ... simple = '(' > expr_ > ')' | var_; var_ = lexeme[+alpha]; } qi::rule<It, var(), Skipper> var_; qi::rule<It, expr(), Skipper> not_, and_, xor_, or_, simple, expr_; }; int main() { std::string input = "(a and b) xor ((c and d) or (a and b));"; const char *f = input.c_str(), *l = f + input.size(); expr result; bool ok = phrase_parse(f, l, parser() > ';', qi::space, result); if (ok) { std::cout << result << '\n'; } }
Result:
((a and b) xor ((c and d) or (a and b)))
The above is the detailed content of How to Parse Boolean Expressions and Construct Syntax Trees in C using Boost Spirit?. For more information, please follow other related articles on the PHP Chinese website!