summaryrefslogtreecommitdiffstats
path: root/src/java/com/sun/gluegen/cgram/HeaderParser.g
blob: f91f146f9823e5e04b7faa090a89f80c529f338d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/*
 * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
 * MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
 * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
 * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
 * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed or intended for use
 * in the design, construction, operation or maintenance of any nuclear
 * facility.
 * 
 * Sun gratefully acknowledges that this software was originally authored
 * and developed by Kenneth Bradley Russell and Christopher John Kline.
 */

header {
        package com.sun.gluegen.cgram;

        import java.io.*;
        import java.util.*;

        import antlr.CommonAST;
        import com.sun.gluegen.cgram.types.*;
}

class HeaderParser extends GnuCTreeParser;
options {
        k = 1;
}

{
    /** Name assigned to a anonymous EnumType (e.g., "enum { ... }"). */
    public static final String ANONYMOUS_ENUM_NAME = "<anonymous>";

    /** Set the dictionary mapping typedef names to types for this
        HeaderParser. Must be done before parsing. */
    public void setTypedefDictionary(TypeDictionary dict) {
        this.typedefDictionary = dict;
    }

    /** Returns the typedef dictionary this HeaderParser uses. */
    public TypeDictionary getTypedefDictionary() {
        return typedefDictionary;
    }    
    
    /** Set the dictionary mapping struct names (i.e., the "foo" in
        "struct foo { ... };") to types for this HeaderParser. Must be done
        before parsing. */
    public void setStructDictionary(TypeDictionary dict) {
        this.structDictionary = dict;
    }

    /** Returns the struct name dictionary this HeaderParser uses. */
    public TypeDictionary getStructDictionary() {
        return structDictionary;
    }    
    
    /** Get the canonicalization map, which is a regular HashMap
        mapping Type to Type and which is used for looking up the unique
        instances of e.g. pointer-to-structure types that have been typedefed
        and therefore have names. */
    public Map getCanonMap() {
        return canonMap;
    }

    /** Pre-define the list of EnumTypes for this HeaderParser. Must be
		done before parsing. */
    public void setEnums(List/*<EnumType>*/ enumTypes) {
        // FIXME: Need to take the input set of EnumTypes, extract all
        // the enumerates from each EnumType, and fill in the enumHash
        // so that each enumerate maps to the enumType to which it
        // belongs.
		throw new RuntimeException("setEnums is Unimplemented!");
    }

    /** Returns the EnumTypes this HeaderParser processed. */
    public List/*<EnumType>*/ getEnums() {
        return new ArrayList(enumHash.values());
    }    
    
    /** Clears the list of functions this HeaderParser has parsed.
        Useful when reusing the same HeaderParser for more than one
        header file. */
    public void clearParsedFunctions() {
        functions.clear();
    }

    /** Returns the list of FunctionSymbols this HeaderParser has parsed. */
    public List getParsedFunctions() {
        return functions;
    }

    private CompoundType lookupInStructDictionary(String typeName,
                                                  CompoundTypeKind kind,
                                                  int cvAttrs) {
        CompoundType t = (CompoundType) structDictionary.get(typeName);
        if (t == null) {
            t = new CompoundType(null, null, kind, cvAttrs);
            t.setStructName(typeName);
            structDictionary.put(typeName, t);
        }
        return t;
    }

    private Type lookupInTypedefDictionary(String typeName) {
        Type t = typedefDictionary.get(typeName);
        if (t == null) {
            throw new RuntimeException("Undefined reference to typedef name " + typeName);
        }
        return t;
    }

    static class ParameterDeclaration {
        private String id;
        private Type   type;

        ParameterDeclaration(String id, Type type) {
            this.id = id;
            this.type = type;
        }
        String id()             { return id; }
        Type   type()           { return type; }
    }

    // A box for a Type. Allows type to be passed down to be modified by recursive rules.
    static class TypeBox {
        private Type origType;
        private Type type;
        private boolean isTypedef;

        TypeBox(Type type) {
            this(type, false);
        }

        TypeBox(Type type, boolean isTypedef) {
            this.origType = type;
            this.isTypedef = isTypedef;
        }

        Type type() {
            if (type == null) {
                return origType;
            }
            return type;
        }
        void setType(Type type) {
            this.type = type;
        }
        void reset() {
            type = null;
        }

        boolean isTypedef()     { return isTypedef; }

	    // for easier debugging
	    public String toString() { 
	       String tStr = "Type=NULL_REF";
	       if (type == origType) {
			 tStr = "Type=ORIG_TYPE";
	  	   } else if (type != null) {
		     tStr = "Type: name=\"" + type.getCVAttributesString() + " " + 
                    type.getName() + "\"; signature=\"" + type + "\"; class " + 
					type.getClass().getName();
	       }
	       String oStr = "OrigType=NULL_REF";
	       if (origType != null) {
		     oStr = "OrigType: name=\"" + origType.getCVAttributesString() + " " + 
             origType.getName() + "\"; signature=\"" + origType + "\"; class " + 
			origType.getClass().getName();
	       }
	       return "<["+tStr + "] [" + oStr + "] " + " isTypedef=" + isTypedef+">"; 
	    }
    }

    private boolean doDeclaration;   // Used to only process function typedefs
    private String  declId;
    private List    parameters;
    private TypeDictionary typedefDictionary;
    private TypeDictionary structDictionary;
    private List/*<FunctionSymbol>*/ functions = new ArrayList();
    // hash from name of an enumerated value to the EnumType to which it belongs
    private HashMap/*<String,EnumType>*/ enumHash = new HashMap();

    // Storage class specifiers
    private static final int AUTO     = 1 << 0;
    private static final int REGISTER = 1 << 1;
    private static final int TYPEDEF  = 1 << 2;
    // Function storage class specifiers
    private static final int EXTERN   = 1 << 3;
    private static final int STATIC   = 1 << 4;
    private static final int INLINE   = 1 << 5;
    // Type qualifiers
    private static final int CONST    = 1 << 6;
    private static final int VOLATILE = 1 << 7;
    private static final int SIGNED   = 1 << 8;
    private static final int UNSIGNED = 1 << 9;

    private void initDeclaration() {
        doDeclaration = false;
        declId = null;
    }

    private void doDeclaration() {
        doDeclaration = true;
    }

    private void processDeclaration(Type returnType) {
        if (doDeclaration) {
            FunctionSymbol sym = new FunctionSymbol(declId, new FunctionType(null, null, returnType, 0));
	        if (parameters != null) { // handle funcs w/ empty parameter lists (e.g., "foo()")
                for (Iterator iter = parameters.iterator(); iter.hasNext(); ) {
                    ParameterDeclaration pd = (ParameterDeclaration) iter.next();
                    sym.addArgument(pd.type(), pd.id());
                }
	        }
            functions.add(sym);
        }
    }

    private int attrs2CVAttrs(int attrs) {
        int cvAttrs = 0;
        if ((attrs & CONST) != 0) {
            cvAttrs |= CVAttributes.CONST;
        }
        if ((attrs & VOLATILE) != 0) {
            cvAttrs |= CVAttributes.VOLATILE;
        }
        return cvAttrs;
    }

    /** Helper routine which handles creating a pointer or array type
        for [] expressions */
    private void handleArrayExpr(TypeBox tb, AST t) {
        if (t != null) {
            try {
                // FIXME: this doesn't take into account struct alignment, which may be necessary
                // See also FIXMEs in ArrayType.java
                int len = parseIntConstExpr(t);
                tb.setType(canonicalize(new ArrayType(tb.type(), SizeThunk.mul(SizeThunk.constant(len), tb.type().getSize()), len, 0)));
                return;
            } catch (RecognitionException e) {
                // Fall through
            }
        }
        tb.setType(canonicalize(new PointerType(SizeThunk.POINTER,
                                                tb.type(),
                                                0)));
    }

    private int parseIntConstExpr(AST t) throws RecognitionException {
        return intConstExpr(t);
    }

  /** Utility function: creates a new EnumType with the given name, or
	  returns an existing one if it has already been created. */
  private EnumType getEnumType(String enumTypeName) {
	EnumType enumType = null;
	Iterator it = enumHash.values().iterator(); 
	while (it.hasNext()) {
	  EnumType potentialMatch = (EnumType)it.next();
	  if (potentialMatch.getName().equals(enumTypeName)) {
		enumType = potentialMatch;
		break;	
	  }
	}
	
	if (enumType == null) {
      // This isn't quite correct. In theory the enum should expand to
      // the size of the largest element, so if there were a long long
      // entry the enum should expand to e.g. int64. However, using
      // "long" here (which is what used to be the case) was 
      // definitely incorrect and caused problems.
	  enumType = new EnumType(enumTypeName, SizeThunk.INT);
	}  
	
	return enumType;
  }	
  
  // Map used to canonicalize types. For example, we may typedef
  // struct foo { ... } *pfoo; subsequent references to struct foo* should
  // point to the same PointerType object that had its name set to "pfoo".
  private Map canonMap = new HashMap();
  private Type canonicalize(Type t) {
    Type res = (Type) canonMap.get(t);
    if (res != null) {
      return res;
    }
    canonMap.put(t, t);
    return t;
  }
}

declarator[TypeBox tb] returns [String s] {
    initDeclaration();
    s = null;
    List params = null;
    String funcPointerName = null;
    TypeBox dummyTypeBox = null;
}
        :   #( NDeclarator
                ( pointerGroup[tb] )?

                ( id:ID  { s = id.getText(); }
                | LPAREN funcPointerName = declarator[dummyTypeBox] RPAREN
                )

                (   #( NParameterTypeList
                      (
                        params = parameterTypeList
                        | (idList)?
                      ) 
                      RPAREN
                    )  {
                           if (id != null) {
                               declId = id.getText();
                               parameters = params; // FIXME: Ken, why are we setting this class member here? 
                               doDeclaration();
                           } else if ( funcPointerName != null ) {
                               /* TypeBox becomes function pointer in this case */
                               FunctionType ft = new FunctionType(null, null, tb.type(), 0);
                               if (params == null) {
			  	                   // If the function pointer has no declared parameters, it's a 
			                       // void function. I'm not sure if the parameter name is 
			                       // ever referenced anywhere when the type is VoidType, so
                                   // just in case I'll set it to a comment string so it will
			                       // still compile if written out to code anywhere.
			  	                   ft.addArgument(new VoidType(0), "/*unnamed-void*/");
			                   } else {
			  	                   for (Iterator iter = params.iterator(); iter.hasNext(); ) {
                                     ParameterDeclaration pd = (ParameterDeclaration) iter.next();
                                     ft.addArgument(pd.type(), pd.id());
				                   }
                               }
                               tb.setType(canonicalize(new PointerType(SizeThunk.POINTER,
                                                                       ft,
                                                                       0)));
                               s = funcPointerName;
                           }
                       }
                 | LBRACKET ( e:expr )? RBRACKET { handleArrayExpr(tb, e); }
                )*
             )
        ;

typelessDeclaration {
    TypeBox tb = null;
}
        :       #(NTypeMissing initDeclList[tb] SEMI)
        ;

declaration {
    TypeBox tb = null;
}
        :       #( NDeclaration
                    tb = declSpecifiers 
                    (
                        initDeclList[tb] 
                    )?
                    ( SEMI )+
                ) { processDeclaration(tb.type()); }
        ;

parameterTypeList returns [List l] { l = new ArrayList(); ParameterDeclaration decl = null; }
        :       ( decl = parameterDeclaration { if (decl != null) l.add(decl); } ( COMMA | SEMI )? )+ ( VARARGS )?
        ;

parameterDeclaration returns [ParameterDeclaration pd] {
    Type t = null;
    String decl = null;
    pd = null;
    TypeBox tb = null;
}
        :       #( NParameterDeclaration
                tb    = declSpecifiers
                (decl = declarator[tb] | nonemptyAbstractDeclarator[tb])?
                ) { pd = new ParameterDeclaration(decl, tb.type()); }
        ;

functionDef {
    TypeBox tb = null;
}
        :   #( NFunctionDef
                ( functionDeclSpecifiers)? 
                declarator[tb]
                (declaration | VARARGS)*
                compoundStatement
            )
        ;

declSpecifiers returns [TypeBox tb] {
    tb = null;
    Type t = null;
    int x = 0;
    int y = 0; 
}
        :       ( y = storageClassSpecifier { x |= y; } 
                | y = typeQualifier         { x |= y; }
                | t = typeSpecifier[x]
                )+
{
            if (t == null &&
                (x & (SIGNED | UNSIGNED)) != 0) {
                t = new IntType("int", SizeThunk.INT, ((x & UNSIGNED) != 0), attrs2CVAttrs(x));
            }
            tb = new TypeBox(t, ((x & TYPEDEF) != 0));
}
        ;

storageClassSpecifier returns [int x] { x = 0; }
        :       "auto"     { x |= AUTO;     }
        |       "register" { x |= REGISTER; }
        |       "typedef"  { x |= TYPEDEF;  }
        |       x = functionStorageClassSpecifier
        ;


functionStorageClassSpecifier returns [int x] { x = 0; }
        :       "extern" { x |= EXTERN; }
        |       "static" { x |= STATIC; }
        |       "inline" { x |= INLINE; }
        ;


typeQualifier returns [int x] { x = 0; }
        :       "const"    { x |= CONST; }
        |       "volatile" { x |= VOLATILE; }
        |       "signed"   { x |= SIGNED; }
        |       "unsigned" { x |= UNSIGNED; }
        ;

typeSpecifier[int attributes] returns [Type t] {
    t = null;
    int cvAttrs = attrs2CVAttrs(attributes);
    boolean unsigned = ((attributes & UNSIGNED) != 0);
}
        :       "void"     { t = new VoidType(cvAttrs); }
        |       "char"     { t = new IntType("char" , SizeThunk.CHAR,  unsigned, cvAttrs); }
        |       "short"    { t = new IntType("short", SizeThunk.SHORT, unsigned, cvAttrs); }
        |       "int"      { t = new IntType("int"  , SizeThunk.INT,   unsigned, cvAttrs); }
        |       "long"     { t = new IntType("long" , SizeThunk.LONG,  unsigned, cvAttrs); }
        |       "__int32"  { t = new IntType("__int32", SizeThunk.INT, unsigned, cvAttrs); }
        |       "__int64"  { t = new IntType("__int64", SizeThunk.INT64, unsigned, cvAttrs); }
        |       "float"    { t = new FloatType("float", SizeThunk.FLOAT, cvAttrs); }
        |       "double"   { t = new DoubleType("double", SizeThunk.DOUBLE, cvAttrs); }
        |       t = structSpecifier[cvAttrs] ( attributeDecl )*
        |       t = unionSpecifier [cvAttrs] ( attributeDecl )*
        |       t = enumSpecifier  [cvAttrs] 
        |       t = typedefName    [cvAttrs] 
        |       #("typeof" LPAREN
                    ( (typeName )=> typeName 
                    | expr
                    )
                    RPAREN
                )
        |       "__complex"
        ;

typedefName[int cvAttrs] returns [Type t] { t = null; }
        :       #(NTypedefName id : ID)
            { 
              t = canonicalize(lookupInTypedefDictionary(id.getText()).getCVVariant(cvAttrs));
            }
        ;

structSpecifier[int cvAttrs] returns [Type t] { t = null; }
        :   #( "struct" t = structOrUnionBody[CompoundTypeKind.STRUCT, cvAttrs] )
        ;

unionSpecifier[int cvAttrs] returns [Type t] { t = null; }
        :   #( "union" t = structOrUnionBody[CompoundTypeKind.UNION, cvAttrs] )
        ;
   
structOrUnionBody[CompoundTypeKind kind, int cvAttrs] returns [CompoundType t] {
    t = null;
}
        :       ( (ID LCURLY) => id:ID LCURLY {
                    t = (CompoundType) canonicalize(lookupInStructDictionary(id.getText(), kind, cvAttrs));
                  } ( structDeclarationList[t] )?
                    RCURLY { t.setBodyParsed(); }
                |   LCURLY { t = new CompoundType(null, null, kind, cvAttrs); }
                    ( structDeclarationList[t] )?
                    RCURLY { t.setBodyParsed(); }
                | id2:ID { t = (CompoundType) canonicalize(lookupInStructDictionary(id2.getText(), kind, cvAttrs)); }
                )
        ;

structDeclarationList[CompoundType t]
        :       ( structDeclaration[t] )+
        ;

structDeclaration[CompoundType containingType] {
    Type t = null;
    boolean addedAny = false;
}
        :       t = specifierQualifierList addedAny = structDeclaratorList[containingType, t] {
                    if (!addedAny) {
                        if (t != null) {
                            CompoundType ct = t.asCompound();
                            if (ct.isUnion()) {
                                // Anonymous union
                                containingType.addField(new Field(null, t, null));
                            }
                        }
                    }
                }
        ;

specifierQualifierList returns [Type t] {
    t = null; int x = 0; int y = 0;
}
        :       (
                t = typeSpecifier[x]
                | y = typeQualifier { x |= y; }
                )+ {
            if (t == null &&
                (x & (SIGNED | UNSIGNED)) != 0) {
                t = new IntType("int", SizeThunk.INT, ((x & UNSIGNED) != 0), attrs2CVAttrs(x));
            }
}
        ;

structDeclaratorList[CompoundType containingType, Type t] returns [boolean addedAny] {
    addedAny = false;
    boolean y = false;
}
        :       ( y = structDeclarator[containingType, t] { addedAny = y; })+
        ;

structDeclarator[CompoundType containingType, Type t] returns [boolean addedAny] {
    addedAny = false;
    String s = null;
    TypeBox tb = new TypeBox(t);
}
        :
        #( NStructDeclarator      
            ( s = declarator[tb] { containingType.addField(new Field(s, tb.type(), null)); addedAny = true; } )?
            ( COLON expr     { /* FIXME: bit types not handled yet */ }        ) ?
            ( attributeDecl )*
        )
        ;

// FIXME: this will not correctly set the name of the enumeration when
// encountering a declaration like this:
//
//     typedef enum {  } enumName;
//                
// In this case calling getName() on the EnumType return value will
// incorrectly return HeaderParser.ANONYMOUS_ENUM_NAME instead of
// "enumName"
//
// I haven't implemented it yet because I'm not sure how to get the
// "enumName" *before* executing the enumList rule.
enumSpecifier [int cvAttrs] returns [Type t] { 
	t = null; 
}
        :       #( "enum"
                   ( ( ID LCURLY )=> i:ID LCURLY enumList[(EnumType)(t = getEnumType(i.getText()))] RCURLY 
                     | LCURLY enumList[(EnumType)(t = getEnumType(ANONYMOUS_ENUM_NAME))] RCURLY 
                     | ID { t = getEnumType(i.getText()); }
                    )
                  )
        ;

enumList[EnumType enumeration] {
	long defaultEnumerantValue = 0;
}
      :       ( defaultEnumerantValue = enumerator[enumeration, defaultEnumerantValue] )+
      ;

enumerator[EnumType enumeration, long defaultValue] returns [long newDefaultValue] {
	newDefaultValue = defaultValue;
}
        :       eName:ID ( ASSIGN eVal:expr )? {
                    long value = 0;
                    if (eVal != null) {
                      String vTxt = eVal.getText();
                      if (enumHash.containsKey(vTxt)) {
                        EnumType oldEnumType = (EnumType) enumHash.get(vTxt);
                        value = oldEnumType.getEnumValue(vTxt);
                      } else {
                        try {
                          value = Long.decode(vTxt).longValue();
                        } catch (NumberFormatException e) {
                          System.err.println("NumberFormatException: " + enumerator_AST_in);
                          throw e;
                        }
                      }
                    } else {
                      value = defaultValue;
                    }

					newDefaultValue = value+1;
	  				String eTxt = eName.getText();
	  				if (enumHash.containsKey(eTxt)) {
						EnumType oldEnumType = (EnumType) enumHash.get(eTxt);
						long oldValue = oldEnumType.getEnumValue(eTxt);
	  					System.err.println("WARNING: redefinition of enumerated value '" + eTxt + "';" +
		  				   " existing definition is in enumeration '" + oldEnumType.getName() +
		  				   "' with value " + oldValue + " and new definition is in enumeration '" +
		  				   enumeration.getName() + "' with value " + value);
						// remove old definition
						oldEnumType.removeEnumerate(eTxt);
	  				}
	  				// insert new definition
	  				enumeration.addEnum(eTxt, value);
	  				enumHash.put(eTxt, enumeration);
					//System.err.println("ENUM [" + enumeration.getName() + "]: " + eTxt + " = " + enumeration.getEnumValue(eTxt) + 
				    //                   " (new default = " + newDefaultValue + ")");
				}
	    ;

initDeclList[TypeBox tb]
        :       ( initDecl[tb] )+
        ;

initDecl[TypeBox tb] {
    String declName = null;
}
        :       #( NInitDecl
                declName = declarator[tb] { 
					//System.err.println("GOT declName: " + declName + " TB=" + tb);
	  			}
                ( attributeDecl )*
                ( ASSIGN initializer
                | COLON expr
                )?
                )
{
    if ((declName != null) && (tb != null) && tb.isTypedef()) {
        Type t = tb.type();
		    //System.err.println("Adding typedef mapping: [" + declName + "] -> [" + t + "]");
        if (!t.hasTypedefName()) {
            t.setName(declName);
        }
        t = canonicalize(t);
        typedefDictionary.put(declName, t);
        // Clear out PointerGroup effects in case another typedef variant follows
        tb.reset();
    }
}
        ;

pointerGroup[TypeBox tb] { int x = 0; int y = 0; }
        :       #( NPointerGroup ( STAR { x = 0; y = 0; } ( y = typeQualifier { x |= y; } )*
                                    {
		  																	//System.err.println("IN PTR GROUP: TB=" + tb);
                                        if (tb != null) {
                                            tb.setType(canonicalize(new PointerType(SizeThunk.POINTER,
                                                                                    tb.type(),
                                                                                    attrs2CVAttrs(x))));
                                        }
                                    }
                                 )+ )
  ;
                                    

functionDeclSpecifiers
        :       
                ( functionStorageClassSpecifier
                | typeQualifier
                | typeSpecifier[0]
                )+
        ;

typeName {
    TypeBox tb = null;
}
        :       specifierQualifierList (nonemptyAbstractDeclarator[tb])?
        ;


/* FIXME: the handling of types in this rule has not been well thought
   out and is known to be incomplete. Currently it is only used to handle
   pointerGroups for unnamed parameters. */
nonemptyAbstractDeclarator[TypeBox tb]
        :   #( NNonemptyAbstractDeclarator
            (   pointerGroup[tb]
                (   (LPAREN  
                    (   nonemptyAbstractDeclarator[tb]
                        | parameterTypeList
                    )?
                    RPAREN)
                | (LBRACKET (e1:expr)? RBRACKET) { handleArrayExpr(tb, e1); }
                )*

            |  (   (LPAREN  
                    (   nonemptyAbstractDeclarator[tb]
                        | parameterTypeList
                    )?
                    RPAREN)
                | (LBRACKET (e2:expr)? RBRACKET) { handleArrayExpr(tb, e2); }
                )+
            )
            )
        ;

/* Helper routine for parsing expressions which evaluate to integer
   constants. Can be made more complicated as necessary. */
intConstExpr returns [int i] { i = -1; }
        : n:Number   { return Integer.parseInt(n.getText()); }
        ;