Simple string passing through nodes in Bison/Yacc

会有一股神秘感。 提交于 2020-01-05 09:12:11

问题


I have to concatenate strings in semantic rules of my yacc file:

%union {
  stringstream sstream;
}
%type<sstream> node1 node2

---

node1
: node2 { $$ << $1 << " goodbye" }

node2
: final { $$ << "hello" }

However, as stringstream or even string are not allowed in unions, I don't find any easy way to mix char *, int, and make nodes transport a string that I can manipulate everywhere. How should I do it ?


回答1:


I don't remember bison/yacc details, but you sure can use pointer and new it. Just remember to delete if bison/yacc gives you the opportunity.




回答2:


Its actually not all that hard to keep track of the pointers. For example:

%union {
  stringstream *sstream;
}
%type<sstream> pair node1 node2 final

---

pair
: node1 ',' node1 { *($$ = $1) << ',' << *$3;  delete $3; }

node1
: node2 { *($$ = $1) << " goodbye" }

node2
: final { *($$ = $1) << "hello" }

final
: TOKEN { *($$ = new stringstream) << "TOKEN"; }

The one major issue is that this will leak if there are syntax errors in your input that cause values to be thrown away without running your actions. You can get around that problem by using bison's %destructor extension. In this case you need only add:

%destructor { delete $$; } <sstream>


来源:https://stackoverflow.com/questions/8932298/simple-string-passing-through-nodes-in-bison-yacc

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