gpt4 book ai didi

c++ - 在 bison/flex 中使用左递归时如何声明持久变量?

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:40 27 4
gpt4 key购买 nike

这是我正在谈论的部分:

block       : statement 
{
NBlock* myBlock = new NBlock();
myBlock->AddStatement($1);
}
| block statement
{
std::cout << "More than one statement" << std::endl;
myBlock->AddStatement($2);
}
;

以下是此作业说明的摘录:

The majority of grammar actions will only require setting $$ to a new instance of the node, as with NRotate. But there are a couple of special cases to watch out for.

The main_loop action simply needs to grab the block it has and set the global g_MainBlock pointer to it. This global block should then also have SetMainBlock called on it.

The other special case is the actions for block. When the first statement is matched, you want to construct a new NBlock, and add the statement to this new NBlock’s list of statements. But when subsequent statements are matched, rather than creating a new NBlock, you should simply add the new statement to the already existing NBlock.

我如何实现这一目标?

预计到达时间:

/* Add one union member for each Node* type */
%union {
Node* node;
NBlock* block;
NStatement* statement;
NNumeric* numeric;
NBoolean* boolean;
std::string* string;
int token;
}

%error-verbose

/* Terminal symbols */
%token <string> TINTEGER
%token <token> TLBRACE TRBRACE TSEMI TLPAREN TRPAREN
%token <token> TMAIN TROTATE TFORWARD TISHUMAN TATTACK TISPASSABLE TISRANDOM TISZOMBIE TRANGED
%token <token> TIF TELSE

/* Statements */
%type <block> main_loop block
%type <statement> statement rotate forward is_human is_passable is_random is_zombie ranged

/* Expressions */
%type <numeric> numeric

最佳答案

您应该能够简单地找到 $1 中的原始对象,并将其移动到 $$ 中,而不是创建一个新对象。

第一个语句将 $$ 设置为 myBlock。递归语句从 $1 中获取它,并将其设置为 $$

附言您应该使用智能指针,即 std::shared_ptr,以避免由于解析失败而导致内存泄漏。

关于c++ - 在 bison/flex 中使用左递归时如何声明持久变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671605/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com