ANTLR 4什么时候需要EOF? [英] When is EOF needed in ANTLR 4?

查看:824
本文介绍了ANTLR 4什么时候需要EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ANTLRWorks2中的 TestDriver 似乎有点挑剔,它何时会接受不带显式EOF的语法,何时不接受. ANTLR4入门中的 Hello 语法《入门指南》 不在任何地方使用EOF,因此我推断最好避免使用显式的EOF.

The TestDriver in ANTLRWorks2 seems kind of finicky about when it'll accept a grammer without and explicit EOF and when it will not. The Hello grammar in the ANTLR4 Getting Started Guide doesn't use EOF anywhere, so I inferred that it's better to avoid explicit EOF if possible.

使用EOF的最佳实践是什么?您何时真正需要它?

What is the best practice for using EOF? When do you actually need it?

推荐答案

在您尝试解析整个输入文件时,应在输入规则的末尾添加一个显式的EOF.如果不包括EOF,则表示您不尝试解析整个输入,并且如果可以避免语法错误,则可以仅解析一部分输入是可以接受的.

You should include an explicit EOF at the end of your entry rule any time you are trying to parse an entire input file. If you do not include the EOF, it means you are not trying to parse the entire input, and it's acceptable to parse only a portion of the input if it means avoiding a syntax error.

例如,考虑以下规则:

file : item*;

此规则的意思是解析尽可能多的item元素,然后停止."换句话说,此规则将从不尝试从语法错误中恢复,因为它会始终假定语法错误是某些语法构造的一部分,该构造超出了本章的范围. file规则.甚至不会报告语法错误,因为解析器只会停止.

This rule means "Parse as many item elements as possible, and then stop." In other words, this rule will never attempt to recover from a syntax error because it will always assume that the syntax error is part of some syntactic construct that's beyond the scope of the file rule. Syntax errors will not even be reported, because the parser will simply stop.

如果相反,我有以下规则:

If instead I had the following rule:

file : item* EOF;

In表示文件完全由零个或多个item元素序列组成."如果在解析item元素时遇到语法错误,此规则 将尝试从语法错误中恢复(并报告),并继续执行,因为需要EOF并且尚未达到EOF

In means "A file consists exactly of a sequence of zero-or-more item elements." If a syntax error is reached while parsing an item element, this rule will attempt to recover from (and report) the syntax error and continue because the EOF is required and has not yet been reached.

对于仅尝试解析一部分输入的规则,ANTLR 4通常有效,但并非总是如此.以下问题描述了一个技术问题,如果省略EOF,则ANTLR 4不会总是做出正确的决定.

For rules where you are only trying to parse a portion of the input, ANTLR 4 often works, but not always. The following issue describes a technical problem where ANTLR 4 does not always make the correct decision if the EOF is omitted.

https://github.com/antlr/antlr4/issues/118

不幸的是,此更改对性能的影响相当大,因此,在解决此问题之前,将出现一些边缘情况,其表现不如您预期.

Unfortunately the performance impact of this change is substantial, so until that is resolved there will be edge cases that do not behave as you expect.

这篇关于ANTLR 4什么时候需要EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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