简体   繁体   English

类似于函数的宏的问题

[英]Issue with Function-like Macro

I'm trying to shorten some repetitive code in my bison parser, here's an excerpt of one of the rules: 我试图在我的野牛解析器中缩短一些重复的代码,这是其中一个规则的摘录:

expression : OBJECTID ASSIGN expression { $$ = std::make_shared<Assign>($1, $3); $$->setloc(@3.first_line, curr_filename); }
            | expression '.' OBJECTID '(' method_expr_list ')' { $$ = std::make_shared<DynamicDispatch>($1, $3, $5); 
                                                                 $$->setloc(@1.first_line, curr_filename); }

I was thinking of something along the lines of: 我在想一些类似的事情:

expression : OBJECTID ASSIGN expression { $$ = std::make_shared<Assign>($1, $3); SETLOC(@1); }
            | expression '.' OBJECTID '(' method_expr_list ')' { $$ = std::make_shared<DynamicDispatch>($1, $3, $5); 
                                                                 SETLOC(@1); }

I can't think of any other way to achieve this other than to use a macro to do it. 除了使用宏来实现之外,我没有其他方法可以实现此目的。 This is what I came up with: 这是我想出的:

#define SETLOC(node) $$->setloc((node).first_line, curr_filename)

Unfortunately, I get a compile error saying that $$ is not defined, which makes sense since it's a function-like macro. 不幸的是,我收到一个编译错误,说没有定义$$,这是有道理的,因为它是一个类似于函数的宏。 I would like to know if there's a way to achieve the code in the 2nd snippet? 我想知道是否有一种方法可以实现第二个代码段中的代码?

This is because $$ is a special sequence that Bison recognizes and uses, it's not in the actual generated C code. 这是因为$$是Bison识别和使用的特殊序列,它不在实际生成的C代码中。 You have to pass it in as an argument to the macro instead: 您必须将其作为参数传递给宏:

#define SETLOC(parent, node) parent->setloc((node).first_line, curr_filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM