[antlr-interest] Interpreter built-in functions: code in grammar or use function table?

cd.barth at t-online.de cd.barth at t-online.de
Tue Oct 30 01:13:43 PDT 2012


I'm using a ParserExtension for helper functions like 
      /*  @return true if LT(1) is key  
          anycase keyword like then / Then / tHeN are all possible
      */
	public boolean isKey(final String key) {
		return
input.LT(1).getText().toUpperCase().equals(key.toUpperCase());
	}
      /* print for test only  */
	public void pr(final String string) {
		System.out.println(string);
            // or any formatted output here..
	}

And use them in parser grammar see sample:
if_statement_part
  :  { isKey("if") }? ID   e=expression 
     { isKey("then") }? ID  unit 
     {pr("if condition: "+$e.text);}  
  ;

Therefore many reusable code can pulled out from grammar to java classes.
Can this be a way for you? 

Claus-Dieter


-----Ursprüngliche Nachricht-----
Von: Michael Cooper [mailto:tillerman35 at yahoo.com] 
Gesendet: Sonntag, 28. Oktober 2012 20:17
An: antlr-interest at antlr.org
Betreff: [antlr-interest] Interpreter built-in functions: code in grammar or
use function table?

I need the usual set of built-in functions for my (java-based) interpreter. 
Stuff like string manipulation functions, math functions, date functions,
etc.

I'm on a fence about how to implement them. 

On the one hand, I could do it with two simple grammar rules.  One for
method invocations and another for function calls.  Then all I would have to
do is maintain a function table with a list of built-in functions.  I
already maintain a function table for functions in the input, so it wouldn't
be much of a stretch to adapt that to built-in functions as well.

The other alternative is to define each built-in function in the grammar
itself.  E.g. a rule for "println" and another for "substr" and another for
"randbetween" etc. etc.
The advantage to that approach is that they appear in the railroad diagrams
in Eclipse.  Those are pretty handy for documentation.  I suppose I could
write a little helper function to output function definitions to
ANTLR-compatible grammar rules. 

Any thoughts?



More information about the antlr-interest mailing list