[antlr-interest] Better Error Reporting in ANTLR

Robert Stehwien rstehwien at gmail.com
Thu Apr 10 08:06:08 PDT 2008


I have a simple grammar where there can be semantic errors.  Right now
I'm using System.err.println() to report those errors.  What I'd like
to do is create and throw an exception that takes just an error string
and have the same line and character information reported that ANTLR
errors report.  Any good suggestions on how I can do that?

Here are examples of the errors in my grammar:
--------------------
ifStatement     : ^(IF expression s+=.+)
  {
    if (!($expression.value instanceof Boolean)) {
      System.err.println("if expression '" + $expression.text + "'
does not evaluate to a boolean");
      return;
    }
    if (((Boolean)$expression.value).booleanValue()) {
      runStatement((CommonTree)$s.get(0));
    }
    else if ($s.size() > 1) {
      runStatement((CommonTree)$s.get(1));
    }
  }
  ;
--------------------
@members {
    private Map<String, Object> variables = new HashMap<String, Object>();

    private void defineInt(String name) {
        if (variables.containsKey(name)) {
            System.err.println("variable '" + name + "' already defined");
        }
        variables.put(name, BigInteger.ZERO);
    }
}
--------------------

Thanks,
Robert


More information about the antlr-interest mailing list