假设我的语法如下:
dish: fruit type ';';
fruit: "apple" | "strawberry" | "pear";
type: "pie" | "cheesecake" | "flan";
...我有一个功能来存储这些菜肴:
bool storeDish(int fruit, int type);
如何有效地告诉 lex 或 yacc(我不知道是哪一个)我希望“apple”的值为 0,“strawberry”的值为 1,“pear”的值为 2,““pie”的值为 0,“cheesecake”的值为 1,“flan”的值为 2?
最佳答案
您可以在 %union
中定义数字类型,将非终结符定义为该数字类型,存储每个水果和类型的值,然后通过索引在菜肴规则中访问它们。最好使用枚举,但这里有一个示例。
/* Define types, you will need to define one for each type of nonterminal */
%union
{
int numeric;
}
/* Specify the type of the nonterminal */
%type<numeric> fruit type
...
%%
...
/* Fruits value accessible by $1 and type by $2 */
dish
: fruit type ';';
{ storeDish($1, $2); }
;
/* Assign each fruit and type a numeric value */
fruit
: "apple"
{ $$ = 0; }
| "strawberry"
{ $$ = 1; }
| "pear"
{ $$ = 2; }
;
type
: "pie"
{ $$ = 0; }
| "cheesecake"
{ $$ = 1; }
| "flan"
{ $$ = 2; }
;
关于c - 如何为 lex 和 yacc 中的文字指定索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27904015/