Boost Spirit x3如果为空,则使用跳过成员将其解析为结构

时间:2018-10-11 01:03:58

标签: c++ boost-spirit boost-spirit-x3

我正在尝试找出解析以下文本的方式

function() {body ...}
function(args_) {body...}

我应该对两个变体使用相同的结构,还是只使用一个结构

struct function
{
    std::string name_;
    std::vector<std::string> args_;
    statement_list body_;
};

我现在解析它的方式(如果没有参数,如何跳过参数):

auto const identifier_def = raw[lexeme[(alpha | '_') >> *(alnum | '_')]];
auto const function_def  =
        lexeme["function" >> !(alnum | '_')] >> identifier
     >> '(' >> ((identifier % ',') )>> ')'
     >> '{' >> statement  >> '}'
        ;

我可以解析带有参数的变体,但不能解析没有参数的那个!

我正在尝试使用类似OR运算符的方法,但是没有成功。

谢谢!

1 个答案:

答案 0 :(得分:2)

作为一个简短的提示,通常可以正常工作:

 >> '(' >> -(identifier % ',') >> ')'

根据特定类型(尤其是identifier的声明),您可能会进行如下调整:

 >> '(' >> (-identifier % ',') >> ')'

强迫它的想法:

 x3::rule<struct arglist_, std::vector<std::string> > { "arglist" }
         = '(' >> (
                       identifier % ','
                     | x3::attr(std::vector<std::string> ())
                   )
         >> ')';
相关问题