我目前正在学习如何使用x3。正如标题所述,我已经成功地用一些简单的规则创建了语法,但是当将其中的两个规则合并为一个时,代码就不再编译了。下面是AST部分的代码:
namespace x3 = boost::spirit::x3;
struct Expression;
struct FunctionExpression {
std::string functionName;
std::vector<x3::forward_ast<Expression>> inputs;
};
struct Expression: x3::variant<int, double, bool, FunctionExpression> {
using base_type::base_type;
using base_type::operator=;
};
我创建的规则,解析输入格式为{rangeMin, rangeMax}
rule<struct basic_exp_class, ast::Expression> const
basic_exp = "basic_exp";
rule<struct exp_pair_class, std::vector<ast::Expression>> const
exp_pair = "exp_pair";
rule<struct range_class, ast::FunctionExpression> const
range = "range";
auto const basic_exp_def = double_ | int_ | bool_;
auto const exp_pair_def = basic_expr >> ',' >> basic_expr;
auto const range_def = attr("computeRange") >> '{' >> exp_pair >> '}';
BOOST_SPIRIT_DEFINE(basic_expr, exp_pair_def, range_def);
这段代码编译得很好。但是,如果我试图将exp_pair
规则内联到range_def
规则中,如下所示:
rule<struct basic_exp_class, ast::Expression> const
basic_exp = "basic_exp";
rule<struct range_class, ast::FunctionExpression> const
range = "range";
auto const basic_exp_def = double_ | int_ | bool_;
auto const range_def = attr("computeRange") >> '{' >> (
basic_exp >> ',' >> basic_exp
) >> '}';
BOOST_SPIRIT_DEFINE(basic_expr, range_def);
代码无法编译一个很长的模板错误,以行结尾:
spirit/include/boost/spirit/home/x3/operator/detail/sequence.hpp:149:9: error: static assertion failed: Size of the passed attribute is less than expected.
static_assert(
^~~~~~~~~~~~~
头文件还包括static_assert
上面的这个注释
// If you got an error here, then you are trying to pass
// a fusion sequence with the wrong number of elements
// as that expected by the (sequence) parser.
但我不明白为什么代码会失败。根据x3的复合属性规则,括号中的内联部分应该具有vector<ast::Expression>
类型的属性,从而使总体规则具有tuple<string, vector<ast::Expression>
类型,以便与ast::FunctionExpression
兼容。同样的逻辑也适用于更冗长的三条规则版本,唯一的区别是我专门为内部部分声明了一个规则,并具体说明了它的属性需要类型为vector<ast::Expression>
。
发布于 2018-11-23 00:26:59
灵性x3可能将内联规则的结果看作是两个单独的ast::Expression
,而不是ast::FunctionExpression
结构所需的std::vector<ast::Expression>
。
为了解决这个问题,我们可以使用另一个as
中提到的帮助器回答 lambda来指定子规则的返回类型。
修改后的range_def将变成:
auto const range_def = attr("computeRange") >> '{' >> as<std::vector<ast::Expression>>(basic_exp >> ',' >> basic_exp) >> '}';
https://stackoverflow.com/questions/53425339
复制相似问题