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

不问归期 提交于 2019-11-30 16:08:19

If you have an array type with a push_front operation, this is trivially:

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):

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;
    }
  ;
%%
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!