使用 Antlr V3 树解析器生成 if-then-else 计算器
我正在为一个简单的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会将逻辑与树语法分开,并创建负责评估输入的自定义节点类。如果你把它全部保留在语法中,它很快就会变成一大堆意大利面条,在我看来,这很难维护。尤其是当你扩展语言时。
有关如何执行此操作的示例,请参阅之前的问答: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: