我的语法是这样的
decl:
attributes; {/*create an object here with the attributes $$?*/ }
attributes:
|
att1 attributes {$$ = $1;}
|
att2 attributes {$$ = $1;}
|
attn attributes {$$ = $1;};
我想获取用户输入的所有属性,有些是可选的,顺序无所谓,类型不同
最佳答案
您需要在您的$$
变量中返回一个结构;根据需要分配给其成员。这是我手头的一些代码的示例:
struct value_list {
char *value;
struct value_list *next;
};
# ...
valuelist: TOK_VALUE
{
struct value_list *new = calloc(1, sizeof(struct value_list));
if (!new)
yyerror(_("Memory allocation error."));
PDEBUG("Matched: value (%s)\n", $1);
new->value = $1;
new->next = NULL;
$$ = new;
}
valuelist: valuelist TOK_VALUE
{
struct value_list *new = calloc(1, sizeof(struct value_list));
if (!new)
yyerror(_("Memory allocation error."));
PDEBUG("Matched: value (%s)\n", $1);
new->value = $2;
new->next = $1;
$$ = new;
}
来自同一解析器的另一个示例,它比上述更简单的规则更努力地根据条目自定义 struct
;缺点是这变得相当复杂,但优点是这是对单个对象属性的更好演示:
/* from a header file */
struct codomain {
char *namespace;
char *name; /* codomain name */
char *attachment;
struct alt_name *altnames;
void *xmatch;
size_t xmatch_size;
int xmatch_len;
/* ... and it goes on like this ... */
}
# from the grammar:
profile_base: TOK_ID opt_id flags TOK_OPEN rules TOK_CLOSE
{
struct codomain *cod = $5;
if (!cod) {
yyerror(_("Memory allocation error."));
}
cod->name = $1;
cod->attachment = $2;
if ($2 && $2[0] != '/')
/* we don't support variables as part of the profile
* name or attachment atm
*/
yyerror(_("Profile attachment must begin with a '/'."));
cod->flags = $3;
if (force_complain)
cod->flags.complain = 1;
post_process_nt_entries(cod);
PDEBUG("%s: flags='%s%s'\n",
$3,
cod->flags.complain ? "complain, " : "",
cod->flags.audit ? "audit" : "");
$$ = cod;
};
关于c++ - 如何在 Bison 解析器上返回多个标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923858/