尝试使用Boost :: Spirit解析表达式时遇到段错误。
我将代码简化为只是一个操作的int表达式类型。示例中的括号使代码段错误。
我最初处理了括号,但我逐步删除了代码以获得最简单的示例。是不是语法应该处理未知的括号而只是解析失败?
#include <string>
#include <iostream>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/qi.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
namespace ascii = boost::spirit::ascii;
namespace qi = boost::spirit::qi;
using std::string;
namespace ast {
struct operation;
using expression = boost::variant<int, boost::recursive_wrapper<operation>>;
struct operation {
expression lhs_;
string operator_;
expression rhs_;
};
}
BOOST_FUSION_ADAPT_STRUCT(ast::operation, (ast::expression, lhs_),
(string, operator_), (ast::expression, rhs_))
namespace parser {
template <typename Iterator>
struct language_grammar
: qi::grammar<Iterator, ast::expression(), ascii::space_type> {
language_grammar() : language_grammar::base_type(expression) {
expression = qi::int_ | operation;
operation = expression >> operator_ >> expression;
operator_ = "+";
}
qi::rule<Iterator, ast::expression(), ascii::space_type> expression;
qi::rule<Iterator, string()> operator_;
qi::rule<Iterator, ast::operation(), ascii::space_type> operation;
};
}
int main() {
string to_parse = "(1 + 2)";
ast::expression expr;
parser::language_grammar<string::const_iterator> grammar;
string::const_iterator iter = to_parse.begin();
string::const_iterator end = to_parse.end();
ascii::space_type space;
bool r = phrase_parse(iter, end, grammar, space, expr);
std::cout << r << std::endl;
return 0;
}