Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeking very simple ANTLR error handling example when generating C code

Tags:

antlr

antlr3

I want to generate C code. I will not be reading from an input file, one line at a time (as, for instance, a compiler might). Rather, I will be parsing user input as it arrives, one line at a time.

I would prefer to detect and handle bad input in the lexer/parser, e.g

/* lexer tokens */
foo : "FOO";
bar : "BAR";
baz : "BAZ";
/* grammar*/
grammar : foo "=" BAZ 
        | foo "=" BAR 
        | <some non-existent Antrl-else> :  {printf(stderr, "bad input\n");}
        ;

OK, if I can't catch it in the lexer/parser, it seems like I need to use displayRecognitionError() but how??

Can anyone point me at a very simple example which generates C code and shows some error handling of invalid input?

Thanks!


Ok, bounty, yippee!

But only for a real, working answer, with real, working code. No "use method X()" without an wxample.

like image 820
Mawg says reinstate Monica Avatar asked Jan 05 '10 01:01

Mawg says reinstate Monica


2 Answers

What you are most likely looking for is the displayRecognitionError() function. This function is called in the cases that you are interested in, and is part of the C runtime.

If you want to see an example of how to use this function, look at this mailing list post. Although this code mixes C and C++, you should be able to work out what you need from it.

like image 144
a_m0d Avatar answered Nov 13 '22 02:11

a_m0d


Handling a recognition exception in Java would go like this:

grammar X;

// ...

@rulecatch{
  catch(RecognitionException rex) {
    // do something
  }
}

// parser rules

// lexer rules 

In other words, simply add some custom C code inside the @rulecatch{ ... } block.

like image 28
Bart Kiers Avatar answered Nov 13 '22 03:11

Bart Kiers