[antlr-interest] Please help a newbie!

Peter Ashford kaffiene at xtra.co.nz
Mon Aug 2 18:53:39 PDT 2004


Hi All,

I'm a newbie to ANTLR, although I've used Flex and Bison on several 
occassions.  I'm trying to write a parser for a simple scripting 
language which can handle basic functions (I'm going to add variables 
and built in functions, but that's about it)

I've implemented a treeparser for the AST stuff, but I'm not sure how 
the normal parser and the tree parser should interact.  When I run the 
parser with the input "result = 12 * 3" I get the following error:

line 1:1: unexpected token: result
 ( * 3 )
<AST>: unexpected AST node: <ASTNULL>

I'm hoping someone can explain what I'm doing wrong (is using a tree 
parser what I want to be doing at all???)
TIA,

Peter.


Here is the entire grammar:


//-------------------------------------------------------------------------------------------------------
options {
    language="Cpp";    
}

//=======================================================================
class MyParser extends Parser;

options {
    buildAST=true;
}

script : (line)+
       ;
      
line   : EOL  
       | RESULT EQ expr EOL
       ;

expr   : mexpr ((PLUS^|MINUS^) mexpr)*
       ;

mexpr  : atom ((MULT^|DIV^) atom)*
       ;

atom   : NUMBER
       | LPAREN! expr RPAREN!
       ;


//============================================================
class MyTreeParser extends TreeParser;

options {
    importVocab=MyParser;
}

expr returns [float r=0]
{ float a,b; }
    :   #(PLUS  a=expr b=expr)  {r = a+b;}
    |   #(MINUS a=expr b=expr)  {r = a-b;}   
    |   #(MULT  a=expr b=expr)  {r = a*b;}
    |   #(DIV   a=expr b=expr)  {r = a/b;}
    |   n:NUMBER                {r = (float) atof(n->getText().c_str());}
    ;

 
//=======================================================================
class MyLexer extends Lexer;

options {
    k=2; // needed for newline junk
    charVocabulary='\u0000'..'\u007F'; // allow ascii
}

LPAREN : '(' ;
RPAREN : ')' ;
PLUS   : '+' ;
MINUS  : '-' ;
MULT   : '*' ;
DIV    : '/' ;
EQ     : '=' ;

RESULT : "result";

protected
DIGIT  : ('0'..'9');

protected
ALPHA  : ('a'..'z' 'A'..'Z');

NUMBER : (DIGIT)+ ( | ('.' (DIGIT)*));

ID     : (ALPHA) (ALPHA|DIGIT)*;

STRING : '"'! (~'"') '"'!;

COMMENT: "//" (~'\n')* '\n' {_ttype = 
ANTLR_USE_NAMESPACE(antlr)Token::SKIP;}
         ;

WS     : ( ' '
         | '\r' '\n'
         | '\n'
         | '\t'
         )
         {_ttype = ANTLR_USE_NAMESPACE(antlr)Token::SKIP;}
         ;    




 
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