Bison/Yacc 中通过节点的简单字符串

发布于 2024-12-27 22:28:27 字数 375 浏览 4 评论 0原文

我必须在 yacc 文件的语义规则中连接字符串:

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

---

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

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

但是,由于联合中不允许使用 stringstream 甚至 string,我找不到任何简单的方法来混合char *int,并使节点传输我可以在任何地方操作的字符串。 我该怎么办呢?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不回头走下去 2025-01-03 22:28:27

我不记得 bison/yacc 详细信息,但您肯定可以使用指针并new 它。如果 bison/yacc 给您机会,请记住删除

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.

楠木可依 2025-01-03 22:28:27

事实上,跟踪指针并不那么困难。例如:

%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"; }

一个主要问题是,如果您的输入中存在语法错误,导致值在不运行操作的情况下被丢弃,则会泄漏。您可以使用 bison 的 %destructor 扩展来解决这个问题。在这种情况下,您只需要添加:

%destructor { delete $; } <sstream>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文