如何建立与野牛/ 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:
arg_list:
WORD arg_list { strcat( $1, "IFS" ); $$ = strcat($1, $2); } |
WORD
;
和
WORD arg_list { printf("%s, %s\n", $1, $2); }
但问题是,我便要再次分裂了$ 2中的第二条规则解析它。有没有一种方法来填充一个数组,而不是仅仅使用串联?我要对这个错误的方式?
But the problem is that I will then have to split up $2 in the second rule again to parse it. Is there a way to populate an array instead of just using concatenation? Am I going about this the wrong way?
如果我需要建立像一个链表,可能是有意义的,只是不知道什么是绑定到arg_list的正确方法,然后清理内存。
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.
推荐答案
如果你有一个push_front操作数组类型,这是平凡:
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); }
不说,它需要更多的工作。可以使用的载体,并添加在末端的字符串(这将是在相反的顺序)。或者你可以使用一个链表(这是比较容易,如果你使用直C):
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; }
这篇关于如何建立与野牛/ Yacc的和递归规则数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!