[antlr-interest] Better Error Reporting in ANTLR

siemsen at ucar.edu siemsen at ucar.edu
Thu Apr 10 09:15:38 PDT 2008


I also report semantic errors with System.err.println().  Line and  
character information is in the token.  In your ifStatement rule, try  
this:

if (!($expression.value instanceof Boolean)) {
     System.err.println("(" + $expression.token.getLine() + ":" +
                        $expression.token.getCharPositionInLine() +  
"): " +
                        "if expression '" + $expression.text + "'does  
not evaluate to a boolean");
     return;
}

I would also like to do this the "right" way, with an exception.   
When I tried, the exception logic made it harder to understand, so I  
stuck with System.err.println().  I hope someone can suggest a better  
way.

-- Pete


On Apr 10, 2008, at 9:06 AM, Robert Stehwien wrote:

> 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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080410/0a169171/attachment.html 


More information about the antlr-interest mailing list