简体   繁体   English

处理Antlr语法错误或如何在意外令牌上提供更好的消息

[英]Handling Antlr Syntax Errors or how to give a better message on unexpected token

We have the following sub-part of an Antlr grammar: 我们有一个Antlr语法的以下子部分:

signed_int
        : SIGN? INT
    ;

INT : '0'..'9'+
        ;

When someone enters a numeric value everything is fine, but if they mistakenly type something like 1O (one and capital o) we get a cryptic error message like: 当有人输入一个数值时,一切都很好,但如果他们错误地输入类似1O(一个和大写o)的东西,我们会得到一个神秘的错误信息:

error 1 : Missing token  at offset 14
near [Index: 0 (Start: 0-Stop: 0) ='<missing COLON>'     type<24> Line: 26 LinePos:14]
 : syntax error...

What is a good way to handle this type of error? 处理此类错误的好方法是什么? I thought of defining catch-all SYMBOL token type but this lead to too many parser building errors. 我想过定义catch-all SYMBOL令牌类型,但这会导致解析器构建错误太多。 I will continue looking into Antlr error handling but I thought I would post this here to look for some insights. 我将继续研究Antlr错误处理,但我想我会在这里发布以寻找一些见解。

You should Override the reportError methods in lexer and parser. 您应该覆盖词法分析器和解析器中的reportError方法。 You can do it by adding this code to your lexer file: 您可以通过将此代码添加到词法分析器文件来完成此操作:

  @Override
public void reportError(RecognitionException e) {
    throw new RuntimeException(e);
}

And create a method matches in parser that checks if input string matches the specified grammar: 并在解析器中创建一个方法匹配,检查输入字符串是否与指定的语法匹配:

 public static boolean matches(String input) {
     try {
         regExLexer lexer = new regExLexer(new ANTLRStringStream(input));
         regExParser parser = new regExParser(new CommonTokenStream(lexer));
         parser.goal();
         return true;
     } catch (RuntimeException e) {
         return false;
     }
     catch (Exception e) {
         return false;
     }
     catch (OutOfMemoryError e) {
         return false;
     }

 }

 @Override
 public void reportError(RecognitionException e) {
     throw new RuntimeException(e);
 }

Then in your file use the Parser.matches(input); 然后在你的文件中使用Parser.matches(输入); to check if the given input matches the gramar. 检查给定输入是否与gramar匹配。 If it matches the method returns true, otherwise returns false, so when it returns false you can give any customized error message to users. 如果匹配,则该方法返回true,否则返回false,因此当它返回false时,您可以向用户提供任何自定义的错误消息。

你可以通过覆盖DefaultErrorStrategy一些消息来尝试使用ANTLRErrorStrategy

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

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