ANTLR not throwing errors on invalid input

后端 未结 2 1845
暖寄归人
暖寄归人 2020-12-11 15:28

I\'m using ANTLR to parse logical expressions in a Java tool I\'m writing, and I\'m having issues because passing invalid input strings to the generated ANTLR lexer and pars

相关标签:
2条回答
  • 2020-12-11 15:39

    An easy fix would be to override your lexer's and parser's reportError(...) and throw an exception of your own instead of letting ANTLR trying to recover from the incorrect syntax/input:

    grammar YourGrammar;
    
    // options/header/tokens
    
    @parser::members {
      @Override
      public void reportError(RecognitionException e) {
        throw new RuntimeException("I quit!\n" + e.getMessage()); 
      }
    }
    
    @lexer::members {
      @Override
      public void reportError(RecognitionException e) {
        throw new RuntimeException("I quit!\n" + e.getMessage()); 
      }
    }
    
    // lexer & parser rules
    

    More on error reporting (and recovery): https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Error+reporting+and+recovery

    0 讨论(0)
  • 2020-12-11 15:40

    You should use an error listener as suggested in this answer

    However, for a quick migration from antlr3 to antlr4 / antlr v4, you could use this as your grammer:

    @parser::members 
    {
      private final Logger log = LogManager.getLogger(this.getClass().getName());
      public java.util.HashMap<String, Double> memory = new java.util.HashMap<String, Double>();
    
      @Override
      public void notifyErrorListeners(Token offendingToken, String msg, RecognitionException ex)
      {
        throw new RuntimeException(msg); 
      }
    }
    
    @lexer::members 
    {
      @Override
      public void recover(RecognitionException ex) 
      {
        throw new RuntimeException(ex.getMessage()); 
      }
    }
    
    0 讨论(0)
提交回复
热议问题