如何在 .y 文件中定义 YYERROR_VERBOSE

Jen*_*ene 3 bison

我正在使用野牛解析器。

要在错误消息中获取预期和意外的令牌名称,YYERROR_VERBOSE需要在生成的 y.go 文件中设置变量。如何从 .y 文件中设置它?

LMG*_*LMG 5

这是语法的一个片段

\n\n
%{\n    #include <stdio.h>\n    #include <stdlib.h>\n    #include <stdarg.h>\n    #include <strings.h>\n    #include "calc.h"\n\n    int yylex(void);    \n    void yyerror(char *s);\n    symrec * symTable;\n    /**\n        temporary variable declarations\n    */\n    linkedList * temp_list = NULL;\n    linkedList * programRoutineList = NULL;\n    linkedList * argList = NULL;\n    program * prg;\n\n%}\n%error-verbose\n\n%union {\n    int iValue;                 \n    symrec * sRec;\n    nodeType *nPtr;\n\n    basicType basic;  \n    parameter *parameter;\n    routine * routine;\n    linkedList *list;       \n};                          \n\n%token <iValue> INTEGER         \n%token <sRec> VARIABLE\n%token WHILE IF PRINT FOR TO\n%nonassoc IFX\n%nonassoc ELSE\n\xe2\x80\xa6\n\xe2\x80\xa6\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是 yacc 文件的开头。作为 yacc 源文件的一部分,它是声明部分,正如您所读到的,用户可以定义几乎任何类型的有用内容(兼容 C)。

\n\n

作为指令的一部分,您可以看到%error-verbose由 yacc 解释为指令的指令,以便在发出错误信号时对“用户”错误更加友好。有关此类指令的更详细信息,请参阅error-verbose the bison 手册(记住使用 google:它知道很多东西;))

\n\n

有关完整的示例,请查看此错误跟踪器示例。您需要 error_tracker_lexer.l 和 error_tracker.y 才能使其正常工作。您可以在同一目录中找到它们。\n编译后,您可以将其用作 my_exec < input_error_tracker\xe2\x80\xa6\n预期输出为

\n\n
at line 2 follows detail on columns--> 2.3-2.4: division by zero\nreturning 1 as default action\n
Run Code Online (Sandbox Code Playgroud)\n\n

好处是,您可以构建自己的文件,其中包含例如:89 + ad

\n\n

输出将是

\n\n
syntax error, unexpected \'\\n\', expecting NUM or \'-\' or \'(\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

希望这会有所帮助..

\n