简体   繁体   English

如何使用Bison / Yacc和递归规则构建数组

[英]How to build an Array with Bison/Yacc and a Recursive Rule

With Bison, I figured out how to get everything into one long string as follows: 有了Bison,我想出了如何将所有内容整合成一个长字符串,如下所示:

arg_list:
    WORD arg_list { strcat( $1, "IFS" ); $$ = strcat($1, $2); }  |
    WORD
    ;

and: 和:

WORD arg_list { printf("%s, %s\n", $1, $2); }

But the problem is that I will then have to split up $2 in the second rule again to parse it. 但问题是,我将不得不再次在第二条规则中拆分2美元来解析它。 Is there a way to populate an array instead of just using concatenation? 有没有办法填充数组而不只是使用连接? Am I going about this the wrong way? 我是以错误的方式来做这件事的吗?

If I need to build something like a linked list that could make sense, just not sure what would be the proper way to bind to arg_list, and then clean up the memory. 如果我需要构建像链接列表那样有意义的东西,只是不确定绑定到arg_list的正确方法是什么,然后清理内存。

If you have an array type with a push_front operation, this is trivially: 如果你有一个带有push_front操作的数组类型,这很简单:

arg_list:
    WORD arg_list { $$ = $2.push_front($1); }
    WORD { $$ = new Array<string>($1); }

without that, it requires more work. 没有它,它需要更多的工作。 You can use a vector and add the strings on the end (which will be in the reversed order). 您可以使用向量并在末尾添加字符串(将按相反的顺序)。 Or you can use a linked list (which is easier if you're using straight C): 或者您可以使用链接列表(如果您使用直接C,则更容易):

arg_list:
    WORD arg_list { $$ = malloc(sizeof(struct list_elem));
                    $$->next = $2;
                    $$->val = $1; }
    WORD          { $$ = malloc(sizeof(struct list_elem));
                    $$->next = 0;
                    $$->val = $1; }
%union {
  char *char_ptr;
}
%token STRING
%type <char_ptr> STRING string
%%
...
string:
    STRING        /* Lexic analyzer return STRING and set yylval = yytext; */
  | string STRING
    { char *str = (char*) malloc(strlen($1) + strlen($2) + 1);
      strcpy(str, $1);
      strcat(str, $2);
      free($2);
      free($1);
      $$ = str;
    }
  ;
%%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM