[antlr-interest] Re: How to throw an exception from the lexer to the caller rule
lemoine at multimania.com
lemoine at multimania.com
Mon Oct 29 01:35:56 PST 2001
You're wright.
The exception was not generated by the lexer rule.
It's generated by the parser in the uri grammar rule
(NoViableAltException).
Following is the code generated for the uri rule in the P.java file :
switch ( LA(1)) {
case STATS:
case DSINFOS:
case PINFOS:
case HELP:
{
command();
break;
}
case STRING_LITERAL:
case PNAME:
case DSN:
case USER:
case PWD:
{
queries();
break;
}
default:
{
throw new NoViableAltException(LT(1), getFilename());
}
}
But that's not what I want to do. I want to handle my own exception
for the command in the command rule and for queries in the
queries rule.
The only way I found is to check for two tokens and to replace the
rule
uri : command
| queries
by the rule
uri :
{
// it's a query option
if(LT(2).getText().equals("=")) {
queries() ;
} else {
// it's a command
command() ;
}
}
;
command : s:STATS
{ _commandName = s.getText() ; }
| d:DSINFOS
{ _commandName = d.getText() ; }
| p:PINFOS
{ _commandName = p.getText() ; }
| h:HELP
{ _commandName = h.getText() ; }
{
_requestIsQuery = false ;
System.out.println("command is "+_commandName) ;
}
;
exception // for command
catch [RecognitionException e] {
String token = getToken(e.getMessage()) ;
throw new RecognitionException("Unknown
command"+" "+token);
}
queries : query (SEMI query)*
;
exception // for queries
catch [RecognitionException e] {
String token = getToken(e.getMessage()) ;
throw new RecognitionException("Unknown
option"+" "+token);
}
I don't known if this solution is very clean ... but it works.
If you have a another way, it would be greatly apprecied.
Thanks
Hervé
--- In antlr-interest at y..., Terence Parr <parrt at j...> wrote:
>
> On Wednesday, October 17, 2001, at 05:46 AM, lemoine at m...
> wrote:
>
> > Hi,
> > I had specified the testLiterals option to true for the IDENT
rule in
> > the Lexer to test each token against the literals table.
> > But when the literal does not match with the lexer IDENT rule, it
> > generates an Exception and exits of the lexer.
> > I want to catch the exception in the caller rule of the parser to
> > specify my own error message.
>
> It should not be generating an exception if it's not a literal...it
> should simply return as IDENT. Are you sure that is what is
happening?
>
> Ter
> --
> Chief Scientist & Co-founder, http://www.jguru.com
> Creator, ANTLR Parser Generator: http://www.antlr.org
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list