简体   繁体   English

确定字符串是否符合ANTLR4语法

[英]Determining whether string complies with ANTLR4 grammar

How can I test a string against my grammar just to see whether it's valid (ie that no errors were found, and no error recovery was necessary)? 如何根据我的语法测试一个字符串,看它是否有效(即没有发现错误,并且不需要进行错误恢复)?

I've tried this as well as a custom error strategy but I'm still getting messages like 我已经尝试过这个以及自定义错误策略,但我仍然会收到类似的消息

line 1:2 token recognition error at: 'x' 第1:2行令牌识别错误:'x'

on the console. 在控制台上。 So I need either a way to ensure all errors result in exceptions, or a way to validate input that doesn't rely on exceptions. 所以我需要一种方法来确保所有错误导致异常,或者一种方法来验证不依赖于异常的输入。

Edit: What you are seeing is a lexer error, not a parser error. 编辑:您看到的是词法分析器错误,而不是解析器错误。 You need to update your lexer to ensure the lexer is incapable of failing to match an input character by adding the following as the last rule of your lexer. 您需要更新词法分析器以确保词法分析器无法通过添加以下作为词法分析器的最后一个规则来匹配输入字符。 This will pass the erroneous character on to the parser for handling (reporting, recovery, etc.). 这会将错误的字符传递给解析器进行处理(报告,恢复等)。

ERR_CHAR : . ;

In addition to this, you need to perform the general steps below which apply to configuring the parser for simple string recognition. 除此之外,您还需要执行以下常规步骤,这些步骤适用于配置解析器以进行简单的字符串识别。


You need to do two things for this to work properly: 您需要做两件事才能使其正常工作:

First, disable the default error reporting mechanism(s). 首先,禁用默认错误报告机制。

parser.removeErrorListeners();

Second, disable the default error recovery mechanism(s). 其次,禁用默认的错误恢复机制。

parser.setErrorStrategy(new BailErrorStrategy());

You'll get a ParseCancellationException , and no other reporting, if your string does not match. 如果您的字符串不匹配,您将获得ParseCancellationException ,而不会收到其他报告。

If you aren't using the output from the parse operation, you may also wish to improve the efficiency of the recognition process by disabling parse tree construction. 如果您没有使用解析操作的输出,您可能还希望通过禁用解析树构造来提高识别过程的效率。

parser.setBuildParseTree(false);

A quick and dirty solution... 快速而肮脏的解决方案......

Parser p = new MyParser(myTokenStream);
p.rootRule();

if (p.getNumberOfSyntaxErrors() > 0) {
    throw new RuntimeException("Syntax error!");
}

This won't help you if there are lexical errors which don't cause the parser to get confused (eg extraneous input) because the number of syntax errors will still be zero. 如果存在不会导致解析器混淆的词法错误(例如无关输入),这将无法帮助您,因为语法错误的数量仍然为零。

This is a good solution if you don't want to mess around with the ErrorListeners and you don't care about certain lexer errors which the parser can get around. 如果您不想使用ErrorListener并且不关心解析器可以解决的某些词法错误,那么这是一个很好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM