• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1grammar SimpleC;
2options {
3  language=ObjC;
4
5}
6
7program
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 */
20declaration
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
28variable
29    :   type declarator ';'
30    ;
31
32declarator
33    :   ID
34    ;
35
36functionHeader 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
44formalParameter
45    :   type declarator
46    ;
47
48type
49    :   'int'
50    |   'char'
51    |   'void'
52    |   ID
53    ;
54
55block
56    :   '{'
57            variable*
58            stat*
59        '}'
60    ;
61
62stat: forStat
63    | expr ';'
64    | block
65    | assignStat ';'
66    | ';'
67    ;
68
69forStat
70    :   'for' '(' assignStat ';' expr ';' assignStat ')' block
71    ;
72
73assignStat
74    :   ID '=' expr
75    ;
76
77expr:   condExpr
78    ;
79
80condExpr
81    :   aexpr ( ('==' | '<') aexpr )?
82    ;
83
84aexpr
85    :   atom ( '+' atom )*
86    ;
87
88atom
89    : ID
90    | INT
91    | '(' expr ')'
92    ;
93
94ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
95    ;
96
97INT :	('0'..'9')+
98    ;
99
100WS  :   (   ' '
101        |   '\t'
102        |   '\r'
103        |   '\n'
104        )+
105        { $channel=HIDDEN; }
106    ;
107