如何将代码放入 MyFile.tab.cc?

How can I put code in MyFile.tab.cc?

我正在尝试遵循 'info bison' 中 C++ 示例的基本建议,所以我有一个 Driver class 和一个 Test.yy 文件:

%skeleton "lalr1.cc"

%{
class Driver;
#include "Expression.hpp"
#define YYSTYPE Expression
%}

%parse-param { Driver& driver }
%lex-param { Driver& driver }
%defines
%locations

%{
#include "Driver.H"
%}

%%
input: {};

当我使用 bison 那个文件时,#include "Driver.H"yy::parser 定义之前的 Test.tab.hh 中结束。那太早了,因为我想在 Driver.H.

中使用 yy::parser::token_type 等等

如果我的 #include 出现在 %union 声明之后,它会根据需要在 Test.tab.cc 中结束。但是,如果我想使用 YYSTYPE 而不是 %union 怎么办?究竟是什么决定了 %{ 块是在 header 还是解析器源代码中结束?

bison manual 中所述,序言(%{ 块)的位置取决于它是在 %union 声明之前还是之后:

This distinction in functionality between the two Prologue sections is established by the appearance of the %union between them. This behavior raises a few questions. First, why should the position of a %union affect definitions related to YYLTYPE and yytokentype? Second, what if there is no %union? In that case, the second kind of Prologue section is not available. This behavior is not intuitive.

幸运的是,您可以使用 %code 声明来显式声明您希望代码块在生成的代码中出现的位置。通常,您会使用 %code requires(在声明 YYSTYPE 之前)和 %code provides(在声明之后)。如果您根本不希望代码出现在 header 中,您也可以使用 %code top。各种 %code 部分的精确语义总结为 here