compiler-construction - C-bison-flex 中的字符串连接

标签 compiler-construction bison flex-lexer

我正在使用 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/

相关文章:

android - Android 的 C 编译器如何工作。

macos - 如何在 mac os x 上安装旧版本的 TypeScript?

c++ - 如何在 Sublime Text 2、Windows 8 中构建和运行 C++ 程序?

使用 yacc 或 Bison 和 Flex 创建 foreach 关键字

c - 设置/获取可重入 Flex 扫描仪的列号

lex - yytext中的flex中仅匹配字符串的一部分

linux - 在 Linux 下从十六进制文件创建可执行文件

c - Bison 中缀计算器的计算结果始终为 0

c - Bison 多个具有属性的非终结符

在没有参数的情况下在 bison 中调用 yyrestart 函数导致 El Capitan 上出现 sigsegv