ANTLR not throwing errors on invalid input

杀马特。学长 韩版系。学妹 提交于 2019-11-28 13:19:15
Bart Kiers

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

Scott Wardlaw

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()); 
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!