Home | History | Annotate | Download | only in LL-star
      1 grammar SimpleC;
      2 options {
      3   language=ObjC;
      4 
      5 }
      6 
      7 program
      8     :   declaration+
      9     ;
     10 
     11 /** In this rule, the functionHeader left prefix on the last two
     12  *  alternatives is not LL(k) for a fixed k.  However, it is
     13  *  LL(*).  The LL(*) algorithm simply scans ahead until it sees
     14  *  either the ';' or the '{' of the block and then it picks
     15  *  the appropriate alternative.  Lookhead can be arbitrarily
     16  *  long in theory, but is <=10 in most cases.  Works great.
     17  *  Use ANTLRWorks to see the lookahead use (step by Location)
     18  *  and look for blue tokens in the input window pane. :)
     19  */
     20 declaration
     21     :   variable
     22     |   functionHeader ';'
     23 	{ NSLog(@"\%@ is a declaration\n", $functionHeader.name); }
     24     |   functionHeader block
     25 	{ NSLog(@"\%@ is a definition\n", $functionHeader.name); }
     26     ;
     27 
     28 variable
     29     :   type declarator ';'
     30     ;
     31 
     32 declarator
     33     :   ID 
     34     ;
     35 
     36 functionHeader returns [NSString *name]
     37 @init {
     38     name=nil; // for now you must init here rather than in 'returns'
     39 }
     40     :   type ID '(' ( formalParameter ( ',' formalParameter )* )? ')'
     41 	{$name = $ID.text;}
     42     ;
     43 
     44 formalParameter
     45     :   type declarator        
     46     ;
     47 
     48 type
     49     :   'int'   
     50     |   'char'  
     51     |   'void'
     52     |   ID        
     53     ;
     54 
     55 block
     56     :   '{'
     57             variable*
     58             stat*
     59         '}'
     60     ;
     61 
     62 stat: forStat
     63     | expr ';'      
     64     | block
     65     | assignStat ';'
     66     | ';'
     67     ;
     68 
     69 forStat
     70     :   'for' '(' assignStat ';' expr ';' assignStat ')' block        
     71     ;
     72 
     73 assignStat
     74     :   ID '=' expr        
     75     ;
     76 
     77 expr:   condExpr
     78     ;
     79 
     80 condExpr
     81     :   aexpr ( ('==' | '<') aexpr )?
     82     ;
     83 
     84 aexpr
     85     :   atom ( '+' atom )*
     86     ;
     87 
     88 atom
     89     : ID      
     90     | INT      
     91     | '(' expr ')'
     92     ; 
     93 
     94 ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
     95     ;
     96 
     97 INT :	('0'..'9')+
     98     ;
     99 
    100 WS  :   (   ' '
    101         |   '\t'
    102         |   '\r'
    103         |   '\n'
    104         )+
    105         { $channel=HIDDEN; }
    106     ;    
    107