使用 Antlr V3 树解析器生成 if-then-else 计算器

发布于 2024-12-21 15:16:59 字数 466 浏览 2 评论 0原文

我正在为一个简单的 DSL 编写一个解释器,并想知道如何优雅地实现 if-then-else 评估器。我从antlr.org网上找到了一个例子,但它实际上使用了CommonTreeNodeStream中的getNodeIndex(),它是受保护的,所以没有用。我能做的最好的事情如下:

ifblock
@init
{
  int t = 0;
  int f = 0;
}
@after
{
  if(c)
    stream.push(t);
  else
    stream.push(f);
  statements(); // handle the statements in then or else branch
  stream.pop()
}
  : ^(IF c=condition {t = input.mark();}. {f = input.mark();}.)
;

这是有效的,但不知何故我并不是很满意。有更好的办法吗?

I'm writing an interpreter for a simple DSL and wondering how to implement if-then-else evaluator elegantly. I found one example online from antlr.org but it actually used getNodeIndex() from CommonTreeNodeStream, which is protected, so no use. The best I could do was the following:

ifblock
@init
{
  int t = 0;
  int f = 0;
}
@after
{
  if(c)
    stream.push(t);
  else
    stream.push(f);
  statements(); // handle the statements in then or else branch
  stream.pop()
}
  : ^(IF c=condition {t = input.mark();}. {f = input.mark();}.)
;

This is working, but I am not really satisfied somehow. Is there a better way?

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

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

发布评论

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

评论(1

烟雨扶苏 2024-12-28 15:16:59

我会将逻辑与树语法分开,并创建负责评估输入的自定义节点类。如果你把它全部保留在语法中,它很快就会变成一大堆意大利面条,在我看来,这很难维护。尤其是当你扩展语言时。

有关如何执行此操作的示例,请参阅之前的问答:if then else 条件评估< /a>

更多相关链接:

I would separate the logic from your tree grammar and create custom node-classes that are responsible for evaluating the input. If you keep it all inside the grammar, it will soon become a big pile of spaghetti, which is hard to maintain, IMO. Especially when you extend the language.

For an example of how to do this, see thie previous Q&A: if then else conditional evaluation

Some more related links:

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