summaryrefslogtreecommitdiffstats
path: root/src/antlr/com/jogamp/gluegen/cgram/HeaderParser.g
blob: 595d7703778dfe4fff9663fc1a35114a6718c69b (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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
/*
 * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
 * Copyright (c) 2010 JogAmp Community. 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.jogamp.gluegen.cgram;

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

        import antlr.CommonAST;
        import com.jogamp.gluegen.ASTLocusTag;
        import com.jogamp.gluegen.GlueGenException;
        import com.jogamp.gluegen.JavaConfiguration;
        import com.jogamp.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>";

    boolean debug = false;

    public boolean getDebug() {
        return debug;
    }

    public void setDebug(boolean debug) {
        this.debug = debug;
    }

    /** Set the configuration for this
        HeaderParser. Must be done before parsing. */
    public void setJavaConfiguration(JavaConfiguration cfg) {
        this.cfg = cfg;
    }

    /** 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<EnumType>(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<FunctionSymbol> getParsedFunctions() {
        return functions;
    }

    private CompoundType lookupInStructDictionary(String structName,
                                                  CompoundTypeKind kind,
                                                  int cvAttrs, final ASTLocusTag locusTag) 
    {
        CompoundType t = (CompoundType) structDictionary.get(structName);
        if (t == null) {
            t = CompoundType.create(structName, null, kind, cvAttrs, locusTag);
            structDictionary.put(structName, t);
        }
        return t;
    }

    private Type lookupInTypedefDictionary(final AST _t, String typeName) {
        Type t = typedefDictionary.get(typeName);
        if (t == null) {
            throwGlueGenException(_t,
                 "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; }
        void setType(final Type t) { type = t; }
        public String toString() { return "ParamDecl["+id+": "+type.getDebugString()+"]"; }
    }
    Type resolveAnonCompound(Type type) { 
        int mode = 0;
        debugPrint("resolveAnonCompound: "+type.getDebugString());
        if( !type.hasName() ) {
            if( type.isCompound() ) {
              final CompoundType ct = type.asCompound();
              // return a copy w/ resolved name
              type = ((CompoundType) ct.clone()).evalStructTypeName();
              mode = 1;
            } else if( type.isPointer() ) {
              // non typedefed PointerType and base-elem w/o name
              final PointerType pt = type.asPointer();
              final Type b = pt.getBaseElementType();
              if( b != null && b.isCompound() && !b.hasName() ) {
                  // return same w/ resolved name
                  b.asCompound().evalStructTypeName();
                  mode = 2;
              }
            }
        }
        debugPrintln(" -> "+type.getDebugString()+" - MODE "+mode);
        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 String getDebugTypeString(Type t) {
      if(debug) {
        return getTypeString(t);
      } else {
        return null;
      }
    }
    private String getTypeString(Type t) {
      StringBuilder sb = new StringBuilder();
      sb.append("[");
      if(null!=t) {
        sb.append(t.getDebugString());
        sb.append(", opaque ").append(isOpaque(t)).append("]");
      } else {
        sb.append("nil]");
      }
      return sb.toString();
    }
    private boolean isOpaque(final Type type) {
      return (cfg.typeInfo(type) != null);
    }

    private void debugPrintln(String msg) {
        if(debug) {
            System.err.println(msg);
        }
    }

    private void debugPrint(String msg) {
        if(debug) {
            System.err.print(msg);
        }
    }

    private JavaConfiguration cfg;
    private TypeDictionary typedefDictionary;
    private TypeDictionary structDictionary;
    private List<FunctionSymbol> functions = new ArrayList<FunctionSymbol>();
    // hash from name of an enumerated value to the EnumType to which it belongs
    private HashMap<String, EnumType> enumHash = new HashMap<String, EnumType>();
    private HashMap<String, EnumType> enumMap = new HashMap<String, EnumType>();

    // 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 boolean isFuncDeclaration;   // Used to only process function typedefs
    private String  funcDeclName;
    private List<ParameterDeclaration> funcDeclParams;
    private ASTLocusTag funcLocusTag;

    private void resetFuncDeclaration() {
        isFuncDeclaration = false;
        funcDeclName = null;
        funcDeclParams = null;
        funcLocusTag = null;
    }
    private void setFuncDeclaration(final String name, final List<ParameterDeclaration> p, final ASTLocusTag locusTag) {
        isFuncDeclaration = true;
        funcDeclName = name;
        funcDeclParams = p;
        funcLocusTag = locusTag;
    }

    private void processDeclaration(Type returnType) {
        if (isFuncDeclaration) {
            final FunctionSymbol sym = new FunctionSymbol(funcDeclName, 
                                                          new FunctionType(null, null, resolveAnonCompound(returnType), 0, funcLocusTag),
                                                          funcLocusTag);
            debugPrintln("Function ... "+sym.toString()+" @ "+funcLocusTag);
            if (funcDeclParams != null) { // handle funcs w/ empty parameter lists (e.g., "foo()")
                for (Iterator<ParameterDeclaration> iter = funcDeclParams.iterator(); iter.hasNext(); ) {
                    ParameterDeclaration pd = iter.next();
                    pd.setType(resolveAnonCompound(pd.type()));
                    debugPrintln(" add "+pd.toString());
                    sym.addArgument(pd.type(), pd.id());
                }
            }
            debugPrintln("Function Added "+sym.toString());
            functions.add(sym);
            resetFuncDeclaration();
        }
    }

    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, ASTLocusTag locusTag) {
        if (t != null) {
            try {
                final int len = parseIntConstExpr(t);
                tb.setType(canonicalize(new ArrayType(tb.type(), SizeThunk.mul(SizeThunk.constant(len), tb.type().getSize()), len, 0, locusTag)));
                return;
            } catch (RecognitionException e) {
                // Fall through
            }
        }
        tb.setType(canonicalize(new PointerType(SizeThunk.POINTER,
                                                tb.type(), 0, locusTag)));
    }

    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, ASTLocusTag locusTag) {
        EnumType enumType = null;
        Iterator<EnumType> it = enumHash.values().iterator(); 
        while (it.hasNext()) {
          EnumType potentialMatch = 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.INT32, locusTag);
        }  
        
        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".
  // Opaque canonical types are excluded.
  private Map<Type, Type> canonMap = new HashMap<Type, Type>();
  private Type canonicalize(Type t) {
    Type res = (Type) canonMap.get(t);
    if (res != null) {
      return res;
    } else {
      canonMap.put(t, t);
      return t;
    }
  }

  private void throwGlueGenException(final AST t, final String message) throws GlueGenException {
    // dumpASTTree("XXX", t);
    throw new GlueGenException(message, findASTLocusTag(t));
  }

  /**
   * Return ASTLocusTag in tree, or null if not found.
   */
  private ASTLocusTag findASTLocusTag(final AST astIn) {
    AST ast = astIn;
    while(null != ast) {
        if( ast instanceof TNode ) {
            final TNode tn = (TNode) ast;
            final ASTLocusTag tag = tn.getASTLocusTag();
            if( null != tag ) {
                return tag;
            }
        }
        ast = ast.getFirstChild();
    }
    return null;
  }
  private void dumpASTTree(final String pre, final AST t) {
    int i=0;
    AST it = t;
    while( null != it ) {
        it = dumpAST(pre+"."+i, it);
        i++;
    }
  }
  private AST dumpAST(final String pre, final AST ast) {
    if( null == ast ) {
        System.err.println(pre+".0: AST NULL");
        return null;
    } else {
        System.err.println(pre+".0: AST Type: "+ast.getClass().getName());
        System.err.println(pre+".1: line:col "+ast.getLine()+":"+ast.getColumn()+" -> "+ast.getText());
        if( ast instanceof TNode ) {
            final TNode tn = (TNode) ast;
            final ASTLocusTag tag = tn.getASTLocusTag();
            System.err.println(pre+".TN.1: "+tag);
            final Hashtable<String, Object> attributes = tn.getAttributesTable();
            System.err.println(pre+".TN.2: "+attributes);
        }
        return ast.getFirstChild();
    }
  }
}

declarator[TypeBox tb] returns [String s] {
    resetFuncDeclaration();
    s = null;
    List<ParameterDeclaration> params = null;
    String funcPointerName = null;
    TypeBox dummyTypeBox = null;
    final ASTLocusTag locusTag = findASTLocusTag(declarator_AST_in);
}
        :   #( NDeclarator
                ( pointerGroup[tb] )?

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

                (   #( NParameterTypeList
                      (
                        params = parameterTypeList
                        | (idList)?
                      ) 
                      RPAREN
                    )  {
                           if (id != null) {
                               setFuncDeclaration(id.getText(), params, locusTag);
                           } else if ( funcPointerName != null ) {
                               /* TypeBox becomes function pointer in this case */
                               final FunctionType ft = new FunctionType(null, null, tb.type(), 0, locusTag);
                               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, locusTag), "/*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, locusTag)));
                               s = funcPointerName;
                           }
                       }
                 | LBRACKET ( e:expr )? RBRACKET { handleArrayExpr(tb, e, locusTag); }
                )*
             )
        ;

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

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

parameterTypeList returns [List<ParameterDeclaration> l] { l = new ArrayList<ParameterDeclaration>(); 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.INTxx, 
                                ((x & UNSIGNED) != 0), 
                                attrs2CVAttrs(x),
                                findASTLocusTag(declSpecifiers_AST_in));
            }
            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 unsig = ((attributes & UNSIGNED) != 0);
    final ASTLocusTag locusTag = findASTLocusTag(typeSpecifier_AST_in);
}
        //
        //                                                                                    TYPEDEF
        //                                                                    UNSIGNED        |
        //      TOKEN                 TYPE    NAME         SIZE               |      ATTRIBS  |      LOCUS
        :       "void"      { t = new VoidType(                                      cvAttrs,        locusTag); }
        |       "char"      { t = new IntType("char" ,     SizeThunk.INT8,    unsig, cvAttrs, false, locusTag); }
        |       "short"     { t = new IntType("short",     SizeThunk.INT16,   unsig, cvAttrs, false, locusTag); }
        |       "int"       { t = new IntType("int"  ,     SizeThunk.INTxx,   unsig, cvAttrs, false, locusTag); }
        |       "long"      { t = new IntType("long" ,     SizeThunk.LONG,    unsig, cvAttrs, false, locusTag); }
        |       "float"     { t = new FloatType("float",   SizeThunk.FLOAT,          cvAttrs,        locusTag); }
        |       "double"    { t = new DoubleType("double", SizeThunk.DOUBLE,         cvAttrs,        locusTag); }
        |       "__int32"   { t = new IntType("__int32",   SizeThunk.INT32,   unsig, cvAttrs, false, locusTag); }
        |       "__int64"   { t = new IntType("__int64",   SizeThunk.INT64,   unsig, cvAttrs, false, locusTag); }
        |       "int8_t"    { t = new IntType("int8_t",    SizeThunk.INT8,    false, cvAttrs, true,  locusTag); }  /* TS: always signed */
        |       "uint8_t"   { t = new IntType("uint8_t",   SizeThunk.INT8,    true,  cvAttrs, true,  locusTag); }  /* TS: always unsigned */
        |       "int16_t"   { t = new IntType("int16_t",   SizeThunk.INT16,   false, cvAttrs, true,  locusTag); }  /* TS: always signed */
        |       "uint16_t"  { t = new IntType("uint16_t",  SizeThunk.INT16,   true,  cvAttrs, true,  locusTag); }  /* TS: always unsigned */
        |       "int32_t"   { t = new IntType("int32_t",   SizeThunk.INT32,   false, cvAttrs, true,  locusTag); }  /* TS: always signed */
        |       "wchar_t"   { t = new IntType("wchar_t",   SizeThunk.INT32,   false, cvAttrs, true,  locusTag); }  /* TS: always signed */
        |       "uint32_t"  { t = new IntType("uint32_t",  SizeThunk.INT32,   true,  cvAttrs, true,  locusTag); }  /* TS: always unsigned */
        |       "int64_t"   { t = new IntType("int64_t",   SizeThunk.INT64,   false, cvAttrs, true,  locusTag); }  /* TS: always signed */
        |       "uint64_t"  { t = new IntType("uint64_t",  SizeThunk.INT64,   true,  cvAttrs, true,  locusTag); }  /* TS: always unsigned */
        |       "ptrdiff_t" { t = new IntType("ptrdiff_t", SizeThunk.POINTER, false, cvAttrs, true,  locusTag); }  /* TS: always signed */
        |       "intptr_t"  { t = new IntType("intptr_t",  SizeThunk.POINTER, false, cvAttrs, true,  locusTag); }  /* TS: always signed */
        |       "size_t"    { t = new IntType("size_t",    SizeThunk.POINTER, true,  cvAttrs, true,  locusTag); }  /* TS: always unsigned */
        |       "uintptr_t" { t = new IntType("uintptr_t", SizeThunk.POINTER, true,  cvAttrs, true,  locusTag); }  /* TS: always unsigned */
        |       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)
            {
              final Type t0 = lookupInTypedefDictionary(typedefName_AST_in, id.getText());
              debugPrint("Adding typedef lookup: [" + id.getText() + "] -> "+getDebugTypeString(t0));
              final Type t1 = t0.getCVVariant(cvAttrs);
              debugPrintln(" - cvvar -> "+getDebugTypeString(t1));
              t = canonicalize(t1);
              debugPrintln(" - canon -> "+getDebugTypeString(t));
            }
        ;

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;
    boolean addedAny = false;
    final ASTLocusTag locusTag = findASTLocusTag(structOrUnionBody_AST_in);
}
        :       ( (ID LCURLY) => id:ID LCURLY {
                    // fully declared struct, i.e. not anonymous
                    t = (CompoundType) canonicalize(lookupInStructDictionary(id.getText(), kind, cvAttrs, locusTag));
                  } ( addedAny = structDeclarationList[t] )?
                    RCURLY { t.setBodyParsed(addedAny); }
                |   LCURLY { 
                      // anonymous declared struct
                      t = CompoundType.create(null, null, kind, cvAttrs, locusTag); 
                    } ( structDeclarationList[t] )?
                    RCURLY { t.setBodyParsed(false); }
                | id2:ID { 
                      // anonymous struct
                      t = (CompoundType) canonicalize(lookupInStructDictionary(id2.getText(), kind, cvAttrs, locusTag)); 
                    }
                )
        ;

structDeclarationList[CompoundType t] returns [boolean addedAny] {
    addedAny = false;
    boolean addedOne = false;
}
        :       ( addedOne = structDeclaration[t] { addedAny |= addedOne; } )+
        ;

structDeclaration[CompoundType containingType] returns [boolean addedAny] {
    addedAny = false;
    Type t = null;
}
        :       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.INTxx, ((x & UNSIGNED) != 0), attrs2CVAttrs(x), 
                                findASTLocusTag(specifierQualifierList_AST_in));
            }
}
        ;

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; 
        EnumType e = null;
        ASTLocusTag locusTag = findASTLocusTag(enumSpecifier_AST_in);
}
        :       #( "enum"
                   ( ( ID LCURLY )=> i:ID LCURLY enumList[(EnumType)(e = getEnumType(i.getText(), locusTag))] RCURLY 
                     | LCURLY enumList[(EnumType)(e = getEnumType(ANONYMOUS_ENUM_NAME, locusTag))] RCURLY 
                     | ID { e = getEnumType(i.getText(), locusTag); }
                   ) {
                     debugPrintln("Adding enum mapping: "+getDebugTypeString(e));
                     if( null != e ) {
                        final String eName = e.getName();
                        if( null != eName && !eName.equals(ANONYMOUS_ENUM_NAME) ) { // validate only non-anonymous enum
                            final EnumType dupE = enumMap.get(eName);
                            if( null != dupE && !dupE.equalSemantics(e) ) {
                                throwGlueGenException(enumSpecifier_AST_in,
                                    String.format("Duplicate enum w/ incompatible type:%n  have '%s',%n  this '%s'",
                                        getTypeString(dupE), getTypeString(e)));
                            }
                            enumMap.put(eName, (EnumType)e.clone());
                        }
                     }
                     t = e; // return val
                   }
                 )
        ;

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 )? {
                    final long newValue;
                    if (eVal != null) {
                      String vTxt = eVal.getAllChildrenText();
                      if (enumHash.containsKey(vTxt)) {
                        EnumType oldEnumType = enumHash.get(vTxt);
                        newValue = oldEnumType.getEnumValue(vTxt);
                      } else {
                        try {
                          newValue = Long.decode(vTxt).longValue();
                        } catch (NumberFormatException e) {
                          System.err.println("NumberFormatException: ID[" + eName.getText() + "], VALUE=[" + vTxt + "]");
                          throw e;
                        }
                      }
                    } else {
                      newValue = defaultValue;
                    }

                    newDefaultValue = newValue+1;
                    String eTxt = eName.getText();
                    if (enumHash.containsKey(eTxt)) {
                        EnumType oldEnumType = enumHash.get(eTxt);
                        final long oldValue = oldEnumType.getEnumValue(eTxt);
                        if( oldValue != newValue ) {
                            throwGlueGenException(enumerator_AST_in,
                                 String.format("Duplicate enum value '%s.%s' w/ diff value:%n  have %d,%n  this %d",
                                     oldEnumType.getName(), eTxt, oldValue, newValue));
                        }
                        // remove old definition
                        oldEnumType.removeEnumerate(eTxt);
                    }
                    // insert new definition
                    enumeration.addEnum(eTxt, newValue);
                    enumHash.put(eTxt, enumeration);
                    debugPrintln("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] { 
                    debugPrintln("GOT declName: " + declName + " TB=" + tb);
                  }
                ( attributeDecl )*
                ( ASSIGN initializer
                | COLON expr
                )?
                )
{
    if ((declName != null) && (tb != null) && tb.isTypedef()) {
        Type t = tb.type();
        debugPrint("Adding typedef mapping: [" + declName + "] -> "+getDebugTypeString(t));
        if (!t.isTypedef()) {
            if( t.isCompound() ) {
                // Allow redefinition of newly defined struct, i.e. use same instance.
                // This aliases '_a' -> 'A' for 'typedef struct _a { } A, *B;', where '*B' will become also '*A'.
                t.setTypedefName(declName);
                debugPrint(" - redefine -> "+getDebugTypeString(t));
            } else {
                // Use new typedef, using a copy to preserve canonicalized base type
                t = (Type) t.clone();
                t.setTypedefName(declName);
                debugPrint(" - newdefine -> "+getDebugTypeString(t));
            }
        } else {
            // Adds typeInfo alias w/ t's typeInfo, if exists
            cfg.addTypeInfo(declName, t);
            final Type alias;
            if( t.isCompound() ) {
                // Attempt to find a previous declared compound typedef
                // This aliases 'D' -> 'A' for 'typedef struct _a { } A, D;'
                alias = typedefDictionary.getEqualSemantics1(t, cfg, true);
            } else {
                alias = null;
            }
            if( null != alias ) {
                // use previous typedef
                t = alias;
                debugPrint(" - alias -> "+getDebugTypeString(t));
            } else {
                // copy to preserve canonicalized base type
                t = (Type) t.clone();
                t.setTypedefName(declName);
                debugPrint(" - copy -> "+getDebugTypeString(t));
            }
        }
        final Type dupT = typedefDictionary.get(declName);
        if( null != dupT && !dupT.equalSemantics(t) ) {
            throwGlueGenException(initDecl_AST_in,
                  String.format("Duplicate typedef w/ incompatible type:%n  have '%s',%n  this '%s'", 
                     getTypeString(dupT), getTypeString(t)));
        }
        t = canonicalize(t);
        debugPrintln(" - canon -> "+getDebugTypeString(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; } )*
                                    {
                                        debugPrintln("IN PTR GROUP: TB=" + tb);
                                        if (tb != null) {
                                            tb.setType(canonicalize(new PointerType(SizeThunk.POINTER,
                                                                                    tb.type(),
                                                                                    attrs2CVAttrs(x), 
                                                                                    findASTLocusTag(pointerGroup_AST_in))));
                                        }
                                    }
                                 )+ )
  ;
                                    

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] {
    final ASTLocusTag locusTag = findASTLocusTag(nonemptyAbstractDeclarator_AST_in);
}
        :   #( NNonemptyAbstractDeclarator
            (   pointerGroup[tb]
                (   (LPAREN  
                    (   nonemptyAbstractDeclarator[tb]
                        | parameterTypeList
                    )?
                    RPAREN)
                | (LBRACKET (e1:expr)? RBRACKET) { handleArrayExpr(tb, e1, locusTag); }
                )*

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

/* 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()); }
        | e:ID {
            final String enumName = e.getText();
            final EnumType enumType = enumHash.get(enumName);
            if( null == enumType ) {
               throwGlueGenException(intConstExpr_AST_in,
                     "Error: intConstExpr ID "+enumName+" recognized, but no containing enum-type found");
            }
            final long enumValue = enumType.getEnumValue(enumName);
            System.err.println("INFO: intConstExpr: enum[Type "+enumType.getName()+", name "+enumName+", value "+enumValue+"]");
            if( (long)Integer.MIN_VALUE > enumValue || (long)Integer.MAX_VALUE < enumValue ) {
               throwGlueGenException(intConstExpr_AST_in,
                     "Error: intConstExpr ID "+enumName+" enum-value "+enumValue+" out of int range");
            }
            return (int)enumValue;
          }
        ;