我正在使用 flex 和 bison 编写一个语义分析器。在那里,我有一个矩阵文字,类似于 [1,2,3;3,4;5]。假设它们是整数。我有以下规则:
在 Flex 文件中:
int {yylval.type_id.Type=1;return tINTTYPE;}
在 Bison 文件中:
char m[80]; //to keep the value of matrix literal
%union semrec
{
struct
{
int Type;
char *id;
}type_id;
}
matrixLit : '[' row ';' rows ']'
row : value
| value ',' row
rows : row
| row ';' rows
value : tINT {$$.id=$1.id;}
| tREAL {$$.id=$1.id;}
| tIDENT {$$.id=$1.id;}
通过使用这些,我试图获取矩阵文字的值。例如,如果矩阵文字是 [1;2;3,4;5,6],我尝试获取 1;2;3,4;5,6。我尝试使用 $$.id=$1.id 和 strcat(m, $1.id)、strcpy(m,$1.id) 等进行一些操作,但无论我做什么,我都无法按此顺序获取值。我得到类似 4,2;1;3,5,6 的结果。谁能帮我这个?
谢谢
最佳答案
对于初学者,请始终在 bison 中使用左递归。 Bison 的解析器能够折叠树的左侧,从而创建更快、更高效的解析器。
我将假设矩阵文字为空是非法的。如果这不是您想要的行为,您将不得不尝试一下。
%type <list> rows row
%%
matrixLit : '[' rows ']'
rows : row { $$ = create_list(); $$->add($1); }
| rows ';' row { $$->add($3); }
;
row : value { $$ = create_list(); $$->add($1); }
| row ',' value { $$->add($3); }
;
您需要向您的 bison union 添加某种列表类型。 Rows 是行条目列表,row 是值条目列表。
关于compiler-construction - C-bison-flex 中的字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15956004/