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

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

问题描述

ANTLRWorks2 中的TestDriver 似乎有点挑剔,它何时接受没有显式EOF 的语法,何时不接受.ANTLR4 Getting中的Hello语法Started Guide 不会在任何地方使用 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.

如果我有以下规则:

file : item* EOF;

In 表示一个文件完全由零个或多个 item 元素序列组成."如果在解析 item 元素时遇到语法错误,此规则尝试从语法错误中恢复(并报告)并继续,因为 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天全站免登陆