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

前端 未结 2 1303
暗喜
暗喜 2021-01-03 10:27

With Bison, I figured out how to get everything into one long string as follows:

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


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 11:21

    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($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; }
    

提交回复
热议问题