c - 如何为 lex 和 yacc 中的文字指定索引值?

标签 c yacc lex

假设我的语法如下:

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; }
    ; 

http://dinosaur.compilertools.net/bison/bison_6.html#SEC53

关于c - 如何为 lex 和 yacc 中的文字指定索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27904015/

相关文章:

c - 管道 - 与多个 fork 的子进程通信

c - 如何将 getaddrinfo 中的 IPv6 地址存储到字符数组中?

c++ - 将 char 数组输入到 stdin

ubuntu - LEX 和 YACC : grammar implementation in NLP

C 编程 - 如何将 char 写入 char*

c - 从不断更新的文件中读取

c++ - 如何通过套接字将文本文件的内容从服务器发送到客户端?

c - 如何为 lex 和 yacc 指定输入缓冲区?

python - PLY Lex 和 Yacc 问题

parsing - 匹配 Flex 中的尾随上下文