Antlr4 侦听器和访问者 - 要实现哪个? [英] Antlr4 Listeners and Visitors - which to implement?

查看:30
本文介绍了Antlr4 侦听器和访问者 - 要实现哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读权威 Antlr 4 参考"并了解有关侦听器和访问者如何工作的想法.这本书特别好地解释了侦听器如何与 SAX 解析器相关联,并在每个方法的实现期间将调用方法的时间一目了然.我还可以看到,侦听器非常适合将输入转换为输出,但我希望能得到有关何时使用侦听器和何时使用访问器的简短解释/示例(或者在某些情况下是否应该同时使用它们?).

I'm reading "The Definitive Antlr 4 Reference" and get the idea in relation to how Listeners and Visitors work. The book explains particularly well how Listeners relate to SAX parsers and makes it obvious when methods are going to be called during the implementation of each. I can see also that listeners are quite good for transforming input to output but I would appreciate a short explanation/example as to when to use a Listener and when to use a Visitor (or should they both be used in certain cases?).

我的特别意图是创建一个解释器(带有一些自定义调用的 Cucumber-style/TinyBasic Interpreter),它将检查语法错误并停止执行来自自定义函数的错误而不恢复 - 希望看到完整的实现在 antlr 中有这样的事情 - 如果有人碰巧知道的话.

My particular intention is to create an interpreter (Cucumber-style / TinyBasic Interpreter with some custom calls) that will check for syntax errors and stop executing on an error from a custom function without recovering - would love to see a complete implementation of such a thing in antlr - if anyone happens to know of one.

提前感谢您的建议.

推荐答案

如果你打算直接使用解析器输出进行解释,访问者是一个不错的选择.您可以完全控制遍历,因此在条件语句中只访问一个分支,循环可以访问 n 次,依此类推.

If you plan to directly use the parser output for interpretation, the visitor is a good choice. You have full control of the traversal, so in conditionals only one branch is visited, loops can be visited n times and so on.

如果您将输入转换为较低级别,例如虚拟机指令,两种模式都可能有用.

If you translate the input to a lower level, e.g. virtual machine instructions, both patterns may be useful.

您可以查看语言实现模式",其中涵盖了基本的解释器实现.

You might take a look at "Language Implementation Patterns", which covers the basic interpreter implementations.

我主要使用访问者模式,因为它更灵活.

I mostly use the visitor pattern, as it's more flexible.

这篇关于Antlr4 侦听器和访问者 - 要实现哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆