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

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

问题描述

我正在阅读权威Antlr 4参考",并获得有关侦听器和访客如何工作的想法.这本书很好地解释了侦听器与SAX解析器之间的关系,并在实现每个侦听器的方法被调用时变得显而易见.我还可以看到,侦听器非常适合将输入转换为输出,但是我希望能得到一个简短的解释/示例,说明何时使用侦听器以及何时使用访客(或者在某些情况下应同时使用它们?)./p>

我的主要目的是创建一个解释器(带有一些自定义调用的黄瓜样式/TinyBasic口译员),该命令将检查语法错误并停止执行自定义函数中的错误而不会恢复-希望看到完整的实现如果有人碰巧知道某事,这在antlr中就是这样.

预先感谢您的任何建议.

解决方案

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

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

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

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

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?).

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.

Thanks in advance for any advice.

解决方案

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天全站免登陆