问题
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