[antlr-interest] Another newbie question

derek_kusiak derek_kusiak at yahoo.com
Fri Dec 3 15:07:36 PST 2004



I'm writing a toy application to learn Antlr.  It reads a
set of math instructions from a text file that might look
like this:

  realfunc 3.1415
  realfunc 42
  realfunc -1e-34
  intfunc  99
  intfunc  -1

My C++ program reads the input, computes the result of
each operation, and prints it to the screen.  realfunc()
can accept any number, real or integer, but intfunc() can
ONLY take integers.  I started by writing a lexer that
returns an INTEGER or FLOAT (real) token, though I'm not
sure I went about it the simplest way:

  class L extends Lexer;

  protected DIGIT    : '0'..'9' ;
  protected INT      : ('+' | '-')? (DIGIT)+ ;
  protected EXPONENT : ('e' | 'E') INT ;
  protected DOT      : '.' ;

  NUMBER
  : DOT INT                        { _ttype = FLOAT; }
  | (INT EXPONENT) => INT EXPONENT { _ttype = FLOAT; }
  | (INT DOT INT) => INT DOT INT   { _ttype = FLOAT; }
  | (INT DOT) => IT DOT            { _ttype = FLOAT; }
  | INT                            { _ttype = INTEGER; }
  ;

Implementing intfunc() in my parser is simple, but I'm not
sure what to do about realfunc():

  class P extends Parser;

  start : (command)+ EOF ;

  command
  : INTFUNC i:INTEGER // So far so good
    {
      cout << "result = "
           << intfunc(atoi(i->getText().c_str()))
           << endl;
    }
  |
    REALFUNC f:(FLOAT | INTEGER) // Not allowed
    {
      cout << "result = "
           << realfunc(atof(f->getText().c_str()))
           << endl;
    }
  ;

How do I write a rule for realfunc() that accepts a FLOAT
or INTEGER and extracts the value?  In my real program
realfunc() takes several parameters, so I can't just
write explicit rules for every permutation.  Thanks.





 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
    antlr-interest-unsubscribe at yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 





More information about the antlr-interest mailing list