WiP
[oweals/gnunet.git] / src / monkey / seaspider / C.jj
1 /*
2
3   C grammar defintion for use with JavaCC
4   Contributed by Doug South (dsouth@squirrel.com.au) 21/3/97
5
6   This parser assumes that the C source file has been preprocessed : all
7   #includes have been included and all macros have been expanded. I accomplish
8   this with "gcc -P -E <source file> > <output file>".
9
10   There is a problem with compiler specific types, such as __signed, __const,
11   __inline__, etc. These types can be added as typedef types before the parser
12   is run on a file. See main() for an example. I have also found a strange little
13   compiler specific "type" if you can call it that. It is __attribute__, but it
14   does not seem to be used as a type. I found that just deleting the __attribute__
15   and the following "offensive" code works.
16
17   This grammar also prints out all the types defined while parsing the file. This
18   is done via a call to printTypes() when the parser is complete. If you do not want
19   this, just comment out the printTypes() method call in the production rule
20   TranslationUnit(), which BTW is the root node for parsing a C source file.
21
22   I have not in anyway extensively tested this grammar, in fact it is barely tested,
23   but I imagine it is better to have a starting point for a C grammar other than from
24   scratch. It has not been optimized in anyway, my main aim was to get a parser that
25   works. Lookahead may not be optimum at choice points and may even be insufficient at
26   times. I choose to err on the side of not optimum if I made a choice at all.
27
28   If you use this grammar, I would appreciate hearing from you. I will try to maintain
29   this grammar to the best of my ability, but at this point in time, this is only a side
30   hobby (unless someone wants to pay me for doing JavaCC work!). In that regards, I am
31   interested in hearing bugs and comments.
32
33   TODO:
34
35     Insert the appropriate code to enable C source trees from this grammar.
36
37 =============================================
38 3/2/06: Modified by Tom Copeland
39 - STRING_LITERAL now handles embedded escaped newlines, thanks to J.Chris Findlay for the patch
40 - Works with JavaCC 4.0
41 - Preprocessor directives are now simply SKIP'd, so no need to run C files through GCC first
42
43 31/8/10: Modified heavily by Christian Grothoff
44 - No more tracking of type names (so we can run without preprocessing)
45 - Support certain gcc-isms (unsigned long long, 33LL, etc.)
46 - No support for certain older C constructs
47 - Support for magic "GNUNET_PACKED" construct (extra "IDENTIFIER" in struct)
48
49 8/11/10: Modified some more by Christian Grothoff
50 - support for arguments without variable names (in particular, just 'void')
51 - support for string concatenations
52 */
53
54 PARSER_BEGIN(CParser)
55
56 import java.util.*;
57
58   public class CParser{
59
60     // Run the parser
61     public static void main ( String args [ ] ) {
62       CParser parser ;
63
64       if(args.length == 0){
65         System.out.println("C Parser Version 0.1Alpha:  Reading from standard input . . .");
66         parser = new CParser(System.in);
67       }
68       else if(args.length == 1){
69         System.out.println("C Parser Version 0.1Alpha:  Reading from file " + args[0] + " . . ." );
70       try {
71         parser = new CParser(new java.io.FileInputStream(args[0]));
72       }
73       catch(java.io.FileNotFoundException e){
74         System.out.println("C Parser Version 0.1:  File " + args[0] + " not found.");
75         return ;
76         }
77       }
78       else {
79         System.out.println("C Parser Version 0.1Alpha:  Usage is one of:");
80         System.out.println("         java CParser < inputfile");
81         System.out.println("OR");
82         System.out.println("         java CParser inputfile");
83         return ;
84       }
85       try {
86         parser.TranslationUnit();
87         System.out.println("C Parser Version 0.1Alpha:  Java program parsed successfully.");
88       }
89       catch(ParseException e){
90         System.out.println("C Parser Version 0.1Alpha:  Encountered errors during parse.");
91         e.printStackTrace();
92       }
93     }
94   }
95
96 PARSER_END(CParser)
97
98 SKIP : {
99  " "
100 |  "\t"
101 |  "\n"
102 |  "\r"
103 |  <"//" (~["\n","\r"])* ("\n" | "\r" | "\r\n")>
104 |  <"/*" (~["*"])* "*" ("*" | ~["*","/"] (~["*"])* "*")* "/">
105 | "#" : PREPROCESSOR_OUTPUT
106 }
107
108 <PREPROCESSOR_OUTPUT> SKIP:
109 {
110      "\n" : DEFAULT
111 }
112
113 <PREPROCESSOR_OUTPUT> MORE:
114 {
115  "\\\n"
116  |
117  "\\\r\n"
118  |
119  < ~[] >
120 }
121
122
123 TOKEN : {
124  <INTEGER_LITERAL: <DECIMAL_LITERAL> (["l","L"])? (["l","L"])? | <HEX_LITERAL> (["l","L"])? (["l","L"])? | <OCTAL_LITERAL> (["l","L"])? (["l","L"])?>
125 |  <#DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* >
126 |  <#HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+>
127 |  <#OCTAL_LITERAL: "0" (["0"-"7"])*>
128 |  <FLOATING_POINT_LITERAL: (["0"-"9"])+ "." (["0"-"9"])* (<EXPONENT>)? (["f","F","d","D"])? | "." (["0"-"9"])+ (<EXPONENT>)? (["f","F","d","D"])? | (["0"-"9"])+ <EXPONENT> (["f","F","d","D"])? | (["0"-"9"])+ (<EXPONENT>)? ["f","F","d","D"]>
129 |  <#EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+>
130 |
131   < CHARACTER_LITERAL:
132       "'"
133       (   (~["'","\\","\n","\r"])
134         | ("\\"
135             ( ["n","t","b","r","f","\\","'","\""]
136             | ["0"-"7"] ( ["0"-"7"] )?
137             | ["0"-"3"] ["0"-"7"] ["0"-"7"]
138             )
139           )
140       )
141       "'"
142   >
143 |   < STRING_LITERAL:
144       ("\""
145       (   (~["\"","\\","\n","\r"])
146         | ("\\"
147             ( ["n","t","b","r","f","\\","'","\""]
148             | ["0"-"7"] ( ["0"-"7"] )?
149             | ["0"-"3"] ["0"-"7"] ["0"-"7"]
150             )
151           )
152       )*
153       "\"")+
154   >
155 }
156
157 TOKEN : {
158         <CONTINUE: "continue"> |
159         <VOLATILE: "volatile"> |
160         <REGISTER: "register"> |
161         <UNSIGNED: "unsigned"> |
162         <TYPEDEF: "typedef"> |
163         <DFLT: "default"> |
164         <DOUBLE: "double"> |
165         <SIZEOF: "sizeof"> |
166         <SWITCH: "switch"> |
167         <RETURN: "return"> |
168         <EXTERN: "extern"> |
169         <STRUCT: "struct"> |
170         <STATIC: "static"> |
171         <SIGNED: "signed"> |
172         <WHILE: "while"> |
173         <BREAK: "break"> |
174         <UNION: "union"> |
175         <CONST: "const"> |
176         <FLOAT: "float"> |
177         <SHORT: "short"> |
178         <ELSE: "else"> |
179         <CASE: "case"> |
180         <LONG: "long"> |
181         <ENUM: "enum"> |
182         <AUTO: "auto"> |
183         <VOID: "void"> |
184         <CHAR: "char"> |
185         <GOTO: "goto"> |
186         <FOR: "for"> |
187         <INT: "int"> |
188         <IF: "if"> |
189         <DO: "do">
190 }
191
192 TOKEN : {
193  <IDENTIFIER: <LETTER> (<LETTER> | <DIGIT>)*>
194 |  <#LETTER: ["$","A"-"Z","_","a"-"z"]>
195 |  <#DIGIT: ["0"-"9"]>
196 }
197
198 void TranslationUnit() : {}
199 {
200         (ExternalDeclaration())+
201         <EOF>
202 }
203
204 void ExternalDeclaration() : {}
205 {
206         (StorageClassSpecifier())*
207         (
208             LOOKAHEAD (FunctionDeclaration()) FunctionDeclaration() | 
209             LOOKAHEAD (StructOrUnionSpecifier() ";") StructOrUnionSpecifier() ";" |
210             LOOKAHEAD (EnumSpecifier() ";") EnumSpecifier() ";" |
211             LOOKAHEAD (VariableDeclaration()) VariableDeclaration() |
212             LOOKAHEAD (TypeDeclaration()) TypeDeclaration () 
213         ) 
214 }
215
216 void FunctionDeclaration() : {}
217 {
218         TypeSpecifier () 
219         <IDENTIFIER>
220         "(" [ ParameterList () ] ")"
221         ( ";" | CompoundStatement() )
222 }
223
224 void StorageClassSpecifier() : {}
225 {
226         ( <STATIC> | <EXTERN> )
227 }
228
229 void TypeDeclaration() : {}
230 {
231         <TYPEDEF> 
232         ( LOOKAHEAD (DataType() ";") DataType () | FunctionType() ) ";"
233 }
234
235 void DataType() : {}
236 {
237         StructOrUnionSpecifier () <IDENTIFIER>
238 }
239
240 void FunctionType() : {}
241 {
242         TypeSpecifier () "(" "*" <IDENTIFIER> ")" "(" [ ParameterList() ] ")"
243 }
244
245 void ParameterList() : {}
246 {
247         ParameterDeclaration() ( LOOKAHEAD (2) "," ParameterDeclaration() )* [ "," "..." ]
248 }
249
250 void ParameterDeclaration() : {}
251 {
252         TypeSpecifier() [<IDENTIFIER> [ Array () ]]
253 }
254
255 void VariableDeclaration() : {}
256 {
257         VariableClassSpecifier () 
258         TypeSpecifier () 
259         InitDeclaratorList() ";"
260 }
261
262 void LocalVariableDeclaration() : {}
263 {
264         [ <STATIC> ] VariableDeclaration () 
265 }
266
267 void VariableClassSpecifier() : {}
268 {
269         ( <AUTO> | <REGISTER> )*
270 }
271
272 void TypeSpecifier() : {}
273 {
274         [ <CONST> ]
275         ( <VOID> 
276           | <CHAR> 
277           | <SHORT> [ <INT> ]
278           | <INT> 
279           | <LONG> [ <LONG> ]  
280           | <FLOAT> | <DOUBLE> 
281           | (<SIGNED> | <UNSIGNED>) [ <CHAR> 
282                                     | <SHORT> [ <INT> ]
283                                     | <INT> 
284                                     | <LONG> [ <LONG> ] ]
285           | StructOrUnionSpecifier() 
286           | EnumSpecifier() 
287           | <IDENTIFIER> 
288         )
289         [ Pointer () ]
290         [ Array () ]
291 }
292
293 /* this is needed for 'va_arg' where a type is an argument
294    -- and we cannot disambiguate the use of 'FOO' 
295    after a 'typedef int FOO' from the variable 'FOO'; 
296    hence this hack */
297 void NoIdentifierTypeSpecifier() : {}
298 {
299         [ <CONST> ]
300         ( <VOID> 
301           | <CHAR> 
302           | <SHORT> [ <INT> ]
303           | <INT> 
304           | <LONG> [ <LONG> ]  
305           | <FLOAT> | <DOUBLE> 
306           | (<SIGNED> | <UNSIGNED>) [ <CHAR> 
307                                     | <SHORT> [ <INT> ]
308                                     | <INT> 
309                                     | <LONG> [ <LONG> ] ]
310           | StructOrUnionSpecifier() 
311           | EnumSpecifier() 
312         )
313         [ Pointer () ]
314         [ Array () ]
315 }
316
317 void StructOrUnionSpecifier() : {}
318 {
319         LOOKAHEAD (3)
320         StructOrUnion() [ <IDENTIFIER> ] "{" StructDeclarationList() "}"  |
321         StructOrUnion() <IDENTIFIER>  
322 }
323
324 void StructOrUnion() : {}
325 {
326         ( <STRUCT> | <UNION> )
327 }
328
329 void StructDeclarationList() : {}
330 {
331         (StructDeclaration())*
332 }
333
334 void InitDeclaratorList() : {}
335 {
336         InitDeclarator() ("," InitDeclarator())*
337 }
338
339 void InitDeclarator() : {}
340 {
341         <IDENTIFIER> [ Array () ] [ "=" Initializer() ]
342 }
343
344 void StructDeclaration() : {}
345 {
346         TypeSpecifier() <IDENTIFIER> [ Array() | ":" ConstantExpression() ] [ <IDENTIFIER> ] ";"
347 }
348
349 void EnumSpecifier() : {}
350 {
351         <ENUM> ( LOOKAHEAD(3) [ <IDENTIFIER> ] "{" EnumeratorList() "}" | <IDENTIFIER> )
352 }
353
354 void EnumeratorList() : {}
355 {
356         Enumerator() ("," Enumerator())*
357 }
358
359 void Enumerator() : {}
360 {
361         <IDENTIFIER> [ "=" ConstantExpression() ]
362 }
363
364 void Pointer() : {}
365 {
366         "*" [ <CONST> ] [ Pointer() ]
367 }
368
369 void Initializer() : {}
370 {
371         ( AssignmentExpression() |
372           "{" InitializerList() [","] "}" )
373 }
374
375 void InitializerList() : {}
376 {
377         Initializer() (LOOKAHEAD(2) "," Initializer())*
378 }
379
380
381 void Array() : {}
382 {
383    ("[" [ConstantExpression()] "]" )+
384 }
385
386 void Statement() : {}
387 {
388         ( LOOKAHEAD(2) LabeledStatement() |
389           ExpressionStatement() |
390           CompoundStatement() |
391           SelectionStatement() |
392           IterationStatement() |
393           JumpStatement() )
394 }
395
396 void LabeledStatement() : {}
397 {
398         ( <IDENTIFIER> ":" Statement() |
399           <CASE> ConstantExpression() ":" Statement() |
400           <DFLT> ":" Statement() )
401 }
402
403 void ExpressionStatement() : {}
404 {
405         [ Expression() ] ";"
406 }
407
408 void CompoundStatement() : {}
409 {
410         "{"   ( LOOKAHEAD (LocalVariableDeclaration()) LocalVariableDeclaration () |
411                 Statement() )*
412         "}"
413 }
414
415 void SelectionStatement() : {}
416 {
417         ( IfStatement() | SwitchStatement() )
418 }
419
420 void IfStatement() : {}
421 {
422          <IF> "(" Expression() ")" Statement() [ LOOKAHEAD(2) <ELSE> Statement() ] 
423 }
424
425 void SwitchStatement() : {}
426 {
427           <SWITCH> "(" Expression() ")" Statement() 
428 }
429
430 void IterationStatement() : {}
431 {
432         ( WhileStatement() | DoWhileStatement() | ForStatement() )
433 }
434 void WhileStatement() : {}
435 {
436         <WHILE> "(" Expression() ")" Statement() 
437 }
438 void DoWhileStatement() : {}
439 {
440           <DO> Statement() <WHILE> "(" Expression() ")" ";" 
441 }
442 void ForStatement() : {}
443 {
444           <FOR> "(" [ Expression() ] ";" [ Expression() ] ";" [ Expression() ] ")" Statement() 
445 }
446
447 void JumpStatement() : {}
448 {
449         ( <GOTO> <IDENTIFIER> ";" |
450           <CONTINUE> ";" |
451           <BREAK> ";" |
452           <RETURN> [ Expression() ] ";" )
453 }
454
455 void Expression() : {}
456 {
457          AssignmentExpression() ( "," AssignmentExpression() )*
458 }
459
460 void AssignmentExpression() : {}
461 {
462           LOOKAHEAD(UnaryExpression() AssignmentOperator()) UnaryExpression() AssignmentOperator() AssignmentExpression() |
463           LOOKAHEAD(3) ConditionalExpression()
464 }
465
466 void AssignmentOperator() : {}
467 {
468         ( "=" | "*=" | "/=" | "%=" | "+=" | "-=" | "<<=" | ">>=" | "&=" | "^=" | "|=" )
469 }
470
471 void ConditionalExpression() : {}
472 {
473         LogicalORExpression() [ "?" Expression() ":" ConditionalExpression() ]
474 }
475
476 void ConstantExpression() : {}
477 {
478         ConditionalExpression()
479 }
480
481 void LogicalORExpression() : {}
482 {
483         LogicalANDExpression() [ "||" LogicalORExpression() ]
484 }
485
486 void LogicalANDExpression() : {}
487 {
488         InclusiveORExpression() [ "&&" LogicalANDExpression() ]
489 }
490
491 void InclusiveORExpression() : {}
492 {
493         ExclusiveORExpression() [ "|" InclusiveORExpression() ]
494 }
495
496 void ExclusiveORExpression() : {}
497 {
498         ANDExpression() [ "^" ExclusiveORExpression() ]
499 }
500
501 void ANDExpression() : {}
502 {
503         EqualityExpression() [ "&" ANDExpression() ]
504 }
505
506 void EqualityExpression() : {}
507 {
508         RelationalExpression() [ ( "==" | "!=" ) EqualityExpression() ]
509 }
510
511 void RelationalExpression() : {}
512 {
513         ShiftExpression() [ ( "<" | ">" | "<=" | ">=" ) RelationalExpression() ]
514 }
515
516 void ShiftExpression() : {}
517 {
518         AdditiveExpression() [ ( "<<" | ">>" ) ShiftExpression() ]
519 }
520
521 void AdditiveExpression() : {}
522 {
523         MultiplicativeExpression() [ ( "+" | "-" ) AdditiveExpression() ]
524 }
525
526 void MultiplicativeExpression() : {}
527 {
528         CastExpression() [ ( "*" | "/" | "%" ) MultiplicativeExpression() ]
529 }
530
531 void CastExpression() : {}
532 {
533         ( LOOKAHEAD("(" TypeSpecifier() ")" CastExpression() ) "(" TypeSpecifier() ")" CastExpression() |
534           UnaryExpression() )
535 }
536
537 void UnaryExpression() : {}
538 {
539         ( LOOKAHEAD(3) PostfixExpression() |
540           "++" UnaryExpression() |
541           "--" UnaryExpression() |
542           UnaryOperator() CastExpression() |
543           <SIZEOF> ( LOOKAHEAD(UnaryExpression() ) UnaryExpression() | "(" TypeSpecifier() ")" ) )
544 }
545
546 void UnaryOperator() : {}
547 {
548         ( "&" | "*" | "+" | "-" | "~" | "!" )
549 }
550
551 void PostfixExpression() : {}
552 {
553         PrimaryExpression() ( "[" Expression() "]" |
554                               "(" [ LOOKAHEAD(ArgumentExpressionList() ) ArgumentExpressionList() ] ")" |
555                                                   "." <IDENTIFIER> |
556                                                   "->" <IDENTIFIER> |
557                                                   "++" |
558                                                   "--" )*
559 }
560
561 void PrimaryExpression() : {}
562 {
563          <IDENTIFIER> |
564           Constant() |
565           "(" Expression() ")" 
566 }
567
568 void ArgumentExpressionList() : {}
569 {
570         AssignmentOrTypeExpression() ( "," AssignmentOrTypeExpression() )*
571 }
572
573
574 void AssignmentOrTypeExpression() : {}
575 {
576         NoIdentifierTypeSpecifier() |
577         AssignmentExpression() 
578 }
579
580 void Constant() : {}
581 {
582   <INTEGER_LITERAL> |
583   <FLOATING_POINT_LITERAL> | 
584   <CHARACTER_LITERAL> | 
585   (<STRING_LITERAL>)+
586 }
587