]> git.sur5r.net Git - cc65/blob - src/cc65/declare.c
Catch fastcall pointers to variadic functions.
[cc65] / src / cc65 / declare.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 declare.c                                 */
4 /*                                                                           */
5 /*                 Parse variable and function declarations                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2015, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <errno.h>
39
40 /* common */
41 #include "addrsize.h"
42 #include "mmodel.h"
43 #include "xmalloc.h"
44
45 /* cc65 */
46 #include "anonname.h"
47 #include "codegen.h"
48 #include "datatype.h"
49 #include "declare.h"
50 #include "declattr.h"
51 #include "error.h"
52 #include "expr.h"
53 #include "funcdesc.h"
54 #include "function.h"
55 #include "global.h"
56 #include "litpool.h"
57 #include "pragma.h"
58 #include "scanner.h"
59 #include "standard.h"
60 #include "symtab.h"
61 #include "typeconv.h"
62
63
64
65 /*****************************************************************************/
66 /*                                   Data                                    */
67 /*****************************************************************************/
68
69
70
71 typedef struct StructInitData StructInitData;
72 struct StructInitData {
73     unsigned    Size;                   /* Size of struct */
74     unsigned    Offs;                   /* Current offset in struct */
75     unsigned    BitVal;                 /* Summed up bit-field value */
76     unsigned    ValBits;                /* Valid bits in Val */
77 };
78
79
80
81 /*****************************************************************************/
82 /*                                 Forwards                                  */
83 /*****************************************************************************/
84
85
86
87 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers);
88 /* Parse a type specifier */
89
90 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers);
91 /* Parse initialization of variables. Return the number of data bytes. */
92
93
94
95 /*****************************************************************************/
96 /*                            Internal functions                             */
97 /*****************************************************************************/
98
99
100
101 static void DuplicateQualifier (const char* Name)
102 /* Print an error message */
103 {
104     Warning ("Duplicate qualifier: `%s'", Name);
105 }
106
107
108
109 static TypeCode OptionalQualifiers (TypeCode Allowed)
110 /* Read type qualifiers if we have any. Allowed specifies the allowed
111 ** qualifiers.
112 */
113 {
114     /* We start without any qualifiers */
115     TypeCode Q = T_QUAL_NONE;
116
117     /* Check for more qualifiers */
118     while (1) {
119
120         switch (CurTok.Tok) {
121
122             case TOK_CONST:
123                 if (Allowed & T_QUAL_CONST) {
124                     if (Q & T_QUAL_CONST) {
125                         DuplicateQualifier ("const");
126                     }
127                     Q |= T_QUAL_CONST;
128                 } else {
129                     goto Done;
130                 }
131                 break;
132
133             case TOK_VOLATILE:
134                 if (Allowed & T_QUAL_VOLATILE) {
135                     if (Q & T_QUAL_VOLATILE) {
136                         DuplicateQualifier ("volatile");
137                     }
138                     Q |= T_QUAL_VOLATILE;
139                 } else {
140                     goto Done;
141                 }
142                 break;
143
144             case TOK_RESTRICT:
145                 if (Allowed & T_QUAL_RESTRICT) {
146                     if (Q & T_QUAL_RESTRICT) {
147                         DuplicateQualifier ("restrict");
148                     }
149                     Q |= T_QUAL_RESTRICT;
150                 } else {
151                     goto Done;
152                 }
153                 break;
154
155             case TOK_NEAR:
156                 if (Allowed & T_QUAL_NEAR) {
157                     if (Q & T_QUAL_NEAR) {
158                         DuplicateQualifier ("near");
159                     }
160                     Q |= T_QUAL_NEAR;
161                 } else {
162                     goto Done;
163                 }
164                 break;
165
166             case TOK_FAR:
167                 if (Allowed & T_QUAL_FAR) {
168                     if (Q & T_QUAL_FAR) {
169                         DuplicateQualifier ("far");
170                     }
171                     Q |= T_QUAL_FAR;
172                 } else {
173                     goto Done;
174                 }
175                 break;
176
177             case TOK_FASTCALL:
178                 if (Allowed & T_QUAL_FASTCALL) {
179                     if (Q & T_QUAL_FASTCALL) {
180                         DuplicateQualifier ("fastcall");
181                     }
182                     Q |= T_QUAL_FASTCALL;
183                 } else {
184                     goto Done;
185                 }
186                 break;
187
188             case TOK_CDECL:
189                 if (Allowed & T_QUAL_CDECL) {
190                     if (Q & T_QUAL_CDECL) {
191                         DuplicateQualifier ("cdecl");
192                     }
193                     Q |= T_QUAL_CDECL;
194                 } else {
195                     goto Done;
196                 }
197                 break;
198
199             default:
200                 goto Done;
201
202         }
203
204         /* Skip the token */
205         NextToken ();
206     }
207
208 Done:
209     /* We cannot have more than one address size far qualifier */
210     switch (Q & T_QUAL_ADDRSIZE) {
211
212         case T_QUAL_NONE:
213         case T_QUAL_NEAR:
214         case T_QUAL_FAR:
215             break;
216
217         default:
218             Error ("Cannot specify more than one address size qualifier");
219             Q &= ~T_QUAL_ADDRSIZE;
220     }
221
222     /* We cannot have more than one calling convention specifier */
223     switch (Q & T_QUAL_CCONV) {
224
225         case T_QUAL_NONE:
226         case T_QUAL_FASTCALL:
227         case T_QUAL_CDECL:
228             break;
229
230         default:
231             Error ("Cannot specify more than one calling convention qualifier");
232             Q &= ~T_QUAL_CCONV;
233     }
234
235     /* Return the qualifiers read */
236     return Q;
237 }
238
239
240
241 static void OptionalInt (void)
242 /* Eat an optional "int" token */
243 {
244     if (CurTok.Tok == TOK_INT) {
245         /* Skip it */
246         NextToken ();
247     }
248 }
249
250
251
252 static void OptionalSigned (void)
253 /* Eat an optional "signed" token */
254 {
255     if (CurTok.Tok == TOK_SIGNED) {
256         /* Skip it */
257         NextToken ();
258     }
259 }
260
261
262
263 static void InitDeclSpec (DeclSpec* D)
264 /* Initialize the DeclSpec struct for use */
265 {
266     D->StorageClass     = 0;
267     D->Type[0].C        = T_END;
268     D->Flags            = 0;
269 }
270
271
272
273 static void InitDeclaration (Declaration* D)
274 /* Initialize the Declaration struct for use */
275 {
276     D->Ident[0]   = '\0';
277     D->Type[0].C  = T_END;
278     D->Index      = 0;
279     D->Attributes = 0;
280 }
281
282
283
284 static void NeedTypeSpace (Declaration* D, unsigned Count)
285 /* Check if there is enough space for Count type specifiers within D */
286 {
287     if (D->Index + Count >= MAXTYPELEN) {
288         /* We must call Fatal() here, since calling Error() will try to
289         ** continue, and the declaration type is not correctly terminated
290         ** in case we come here.
291         */
292         Fatal ("Too many type specifiers");
293     }
294 }
295
296
297
298 static void AddTypeToDeclaration (Declaration* D, TypeCode T)
299 /* Add a type specifier to the type of a declaration */
300 {
301     NeedTypeSpace (D, 1);
302     D->Type[D->Index++].C = T;
303 }
304
305
306
307 static void FixQualifiers (Type* DataType)
308 /* Apply several fixes to qualifiers */
309 {
310     Type*    T;
311     TypeCode Q;
312
313     /* Using typedefs, it is possible to generate declarations that have
314     ** type qualifiers attached to an array, not the element type. Go and
315     ** fix these here.
316     */
317     T = DataType;
318     Q = T_QUAL_NONE;
319     while (T->C != T_END) {
320         if (IsTypeArray (T)) {
321             /* Extract any type qualifiers */
322             Q |= GetQualifier (T);
323             T->C = UnqualifiedType (T->C);
324         } else {
325             /* Add extracted type qualifiers here */
326             T->C |= Q;
327             Q = T_QUAL_NONE;
328         }
329         ++T;
330     }
331     /* Q must be empty now */
332     CHECK (Q == T_QUAL_NONE);
333
334     /* Do some fixes on pointers and functions. */
335     T = DataType;
336     while (T->C != T_END) {
337         if (IsTypePtr (T)) {
338
339             /* Calling convention qualifier on the pointer? */
340             if (IsQualCConv (T)) {
341                 /* Pull the convention off of the pointer */
342                 Q = T[0].C & T_QUAL_CCONV;
343                 T[0].C &= ~T_QUAL_CCONV;
344                 /* Pointer to a function which doesn't have an explicit convention? */
345                 if (IsTypeFunc (T + 1)) {
346                     if (IsQualCConv (T + 1)) {
347                         if (T[1].C == Q) {
348                             /* TODO: The end of Declarator() catches this error.
349                             ** Try to make it let the error be caught here, instead.
350                             */
351                             Warning ("Pointer duplicates function's calling convention");
352                         } else {
353                             Error ("Mismatch between pointer's and function's calling conventions");
354                         }
355                     } else {
356                         if (Q == T_QUAL_FASTCALL && IsVariadicFunc (T + 1)) {
357                             Error ("Variadic-function pointers cannot be `__fastcall__'");
358                         } else {
359                             /* Move the qualifier from the pointer to the function. */
360                             T[1].C |= Q;
361                         }
362                     }
363                 } else {
364                     Error ("Not pointer to a function; can't use a calling convention");
365                 }
366             }
367
368             /* Apply the default far and near qualifiers if none are given */
369             Q = (T[0].C & T_QUAL_ADDRSIZE);
370             if (Q == T_QUAL_NONE) {
371                 /* No address size qualifiers specified */
372                 if (IsTypeFunc (T+1)) {
373                     /* Pointer to function. Use the qualifier from the function,
374                     ** or the default if the function doesn't have one.
375                     */
376                     Q = (T[1].C & T_QUAL_ADDRSIZE);
377                     if (Q == T_QUAL_NONE) {
378                         Q = CodeAddrSizeQualifier ();
379                     }
380                 } else {
381                     Q = DataAddrSizeQualifier ();
382                 }
383                 T[0].C |= Q;
384             } else {
385                 /* We have address size qualifiers. If followed by a function,
386                 ** apply them to the function also.
387                 */
388                 if (IsTypeFunc (T+1)) {
389                     TypeCode FQ = (T[1].C & T_QUAL_ADDRSIZE);
390                     if (FQ == T_QUAL_NONE) {
391                         T[1].C |= Q;
392                     } else if (FQ != Q) {
393                         Error ("Address size qualifier mismatch");
394                         T[1].C = (T[1].C & ~T_QUAL_ADDRSIZE) | Q;
395                     }
396                 }
397             }
398
399         } else if (IsTypeFunc (T)) {
400
401             /* Apply the default far and near qualifiers if none are given */
402             if ((T[0].C & T_QUAL_ADDRSIZE) == 0) {
403                 T[0].C |= CodeAddrSizeQualifier ();
404             }
405
406         }
407         ++T;
408     }
409 }
410
411
412
413 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
414 /* Parse a storage class */
415 {
416     /* Assume we're using an explicit storage class */
417     D->Flags &= ~DS_DEF_STORAGE;
418
419     /* Check the storage class given */
420     switch (CurTok.Tok) {
421
422         case TOK_EXTERN:
423             D->StorageClass = SC_EXTERN | SC_STATIC;
424             NextToken ();
425             break;
426
427         case TOK_STATIC:
428             D->StorageClass = SC_STATIC;
429             NextToken ();
430             break;
431
432         case TOK_REGISTER:
433             D->StorageClass = SC_REGISTER | SC_STATIC;
434             NextToken ();
435             break;
436
437         case TOK_AUTO:
438             D->StorageClass = SC_AUTO;
439             NextToken ();
440             break;
441
442         case TOK_TYPEDEF:
443             D->StorageClass = SC_TYPEDEF;
444             NextToken ();
445             break;
446
447         default:
448             /* No storage class given, use default */
449             D->Flags |= DS_DEF_STORAGE;
450             D->StorageClass = DefStorage;
451             break;
452     }
453 }
454
455
456
457 static void ParseEnumDecl (void)
458 /* Process an enum declaration . */
459 {
460     int EnumVal;
461     ident Ident;
462
463     /* Accept forward definitions */
464     if (CurTok.Tok != TOK_LCURLY) {
465         return;
466     }
467
468     /* Skip the opening curly brace */
469     NextToken ();
470
471     /* Read the enum tags */
472     EnumVal = 0;
473     while (CurTok.Tok != TOK_RCURLY) {
474
475         /* We expect an identifier */
476         if (CurTok.Tok != TOK_IDENT) {
477             Error ("Identifier expected");
478             continue;
479         }
480
481         /* Remember the identifier and skip it */
482         strcpy (Ident, CurTok.Ident);
483         NextToken ();
484
485         /* Check for an assigned value */
486         if (CurTok.Tok == TOK_ASSIGN) {
487             ExprDesc Expr;
488             NextToken ();
489             ConstAbsIntExpr (hie1, &Expr);
490             EnumVal = Expr.IVal;
491         }
492
493         /* Add an entry to the symbol table */
494         AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
495
496         /* Check for end of definition */
497         if (CurTok.Tok != TOK_COMMA)
498             break;
499         NextToken ();
500     }
501     ConsumeRCurly ();
502 }
503
504
505
506 static int ParseFieldWidth (Declaration* Decl)
507 /* Parse an optional field width. Returns -1 if no field width is specified,
508 ** otherwise the width of the field.
509 */
510 {
511     ExprDesc Expr;
512
513     if (CurTok.Tok != TOK_COLON) {
514         /* No bit-field declaration */
515         return -1;
516     }
517
518     /* Read the width */
519     NextToken ();
520     ConstAbsIntExpr (hie1, &Expr);
521     if (Expr.IVal < 0) {
522         Error ("Negative width in bit-field");
523         return -1;
524     }
525     if (Expr.IVal > (int) INT_BITS) {
526         Error ("Width of bit-field exceeds its type");
527         return -1;
528     }
529     if (Expr.IVal == 0 && Decl->Ident[0] != '\0') {
530         Error ("Zero width for named bit-field");
531         return -1;
532     }
533     if (!IsTypeInt (Decl->Type)) {
534         /* Only integer types may be used for bit-fields */
535         Error ("Bit-field has invalid type");
536         return -1;
537     }
538
539     /* Return the field width */
540     return (int) Expr.IVal;
541 }
542
543
544
545 static SymEntry* StructOrUnionForwardDecl (const char* Name, unsigned Type)
546 /* Handle a struct or union forward decl */
547 {
548     /* Try to find a struct/union with the given name. If there is none,
549     ** insert a forward declaration into the current lexical level.
550     */
551     SymEntry* Entry = FindTagSym (Name);
552     if (Entry == 0) {
553         Entry = AddStructSym (Name, Type, 0, 0);
554     } else if ((Entry->Flags & SC_TYPEMASK) != Type) {
555         /* Already defined, but no struct */
556         Error ("Symbol `%s' is already different kind", Name);
557     }
558     return Entry;
559 }
560
561
562
563 static unsigned CopyAnonStructFields (const Declaration* Decl, int Offs)
564 /* Copy fields from an anon union/struct into the current lexical level. The
565 ** function returns the size of the embedded struct/union.
566 */
567 {
568     /* Get the pointer to the symbol table entry of the anon struct */
569     SymEntry* Entry = GetSymEntry (Decl->Type);
570
571     /* Get the size of the anon struct */
572     unsigned Size = Entry->V.S.Size;
573
574     /* Get the symbol table containing the fields. If it is empty, there has
575     ** been an error before, so bail out.
576     */
577     SymTable* Tab = Entry->V.S.SymTab;
578     if (Tab == 0) {
579         /* Incomplete definition - has been flagged before */
580         return Size;
581     }
582
583     /* Get a pointer to the list of symbols. Then walk the list adding copies
584     ** of the embedded struct to the current level.
585     */
586     Entry = Tab->SymHead;
587     while (Entry) {
588
589         /* Enter a copy of this symbol adjusting the offset. We will just
590         ** reuse the type string here.
591         */
592         AddLocalSym (Entry->Name, Entry->Type, SC_STRUCTFIELD, Offs + Entry->V.Offs);
593
594         /* Currently, there can not be any attributes, but if there will be
595         ** some in the future, we want to know this.
596         */
597         CHECK (Entry->Attr == 0);
598
599         /* Next entry */
600         Entry = Entry->NextSym;
601     }
602
603     /* Return the size of the embedded struct */
604     return Size;
605 }
606
607
608
609 static SymEntry* ParseUnionDecl (const char* Name)
610 /* Parse a union declaration. */
611 {
612
613     unsigned  UnionSize;
614     unsigned  FieldSize;
615     int       FieldWidth;       /* Width in bits, -1 if not a bit-field */
616     SymTable* FieldTab;
617
618
619     if (CurTok.Tok != TOK_LCURLY) {
620         /* Just a forward declaration. */
621         return StructOrUnionForwardDecl (Name, SC_UNION);
622     }
623
624     /* Add a forward declaration for the struct in the current lexical level */
625     AddStructSym (Name, SC_UNION, 0, 0);
626
627     /* Skip the curly brace */
628     NextToken ();
629
630     /* Enter a new lexical level for the struct */
631     EnterStructLevel ();
632
633     /* Parse union fields */
634     UnionSize      = 0;
635     while (CurTok.Tok != TOK_RCURLY) {
636
637         /* Get the type of the entry */
638         DeclSpec Spec;
639         InitDeclSpec (&Spec);
640         ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
641
642         /* Read fields with this type */
643         while (1) {
644
645             Declaration Decl;
646
647             /* Get type and name of the struct field */
648             ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
649
650             /* Check for a bit-field declaration */
651             FieldWidth = ParseFieldWidth (&Decl);
652
653             /* Ignore zero sized bit fields in a union */
654             if (FieldWidth == 0) {
655                 goto NextMember;
656             }
657
658             /* Check for fields without a name */
659             if (Decl.Ident[0] == '\0') {
660                 /* In cc65 mode, we allow anonymous structs/unions within
661                 ** a struct.
662                 */
663                 if (IS_Get (&Standard) >= STD_CC65 && IsClassStruct (Decl.Type)) {
664                     /* This is an anonymous struct or union. Copy the fields
665                     ** into the current level.
666                     */
667                     CopyAnonStructFields (&Decl, 0);
668
669                 } else {
670                     /* A non bit-field without a name is legal but useless */
671                     Warning ("Declaration does not declare anything");
672                 }
673                 goto NextMember;
674             }
675
676             /* Handle sizes */
677             FieldSize = CheckedSizeOf (Decl.Type);
678             if (FieldSize > UnionSize) {
679                 UnionSize = FieldSize;
680             }
681
682             /* Add a field entry to the table. */
683             if (FieldWidth > 0) {
684                 AddBitField (Decl.Ident, 0, 0, FieldWidth);
685             } else {
686                 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, 0);
687             }
688
689 NextMember: if (CurTok.Tok != TOK_COMMA) {
690                 break;
691             }
692             NextToken ();
693         }
694         ConsumeSemi ();
695     }
696
697     /* Skip the closing brace */
698     NextToken ();
699
700     /* Remember the symbol table and leave the struct level */
701     FieldTab = GetSymTab ();
702     LeaveStructLevel ();
703
704     /* Make a real entry from the forward decl and return it */
705     return AddStructSym (Name, SC_UNION, UnionSize, FieldTab);
706 }
707
708
709
710 static SymEntry* ParseStructDecl (const char* Name)
711 /* Parse a struct declaration. */
712 {
713
714     unsigned  StructSize;
715     int       FlexibleMember;
716     int       BitOffs;          /* Bit offset for bit-fields */
717     int       FieldWidth;       /* Width in bits, -1 if not a bit-field */
718     SymTable* FieldTab;
719
720
721     if (CurTok.Tok != TOK_LCURLY) {
722         /* Just a forward declaration. */
723         return StructOrUnionForwardDecl (Name, SC_STRUCT);
724     }
725
726     /* Add a forward declaration for the struct in the current lexical level */
727     AddStructSym (Name, SC_STRUCT, 0, 0);
728
729     /* Skip the curly brace */
730     NextToken ();
731
732     /* Enter a new lexical level for the struct */
733     EnterStructLevel ();
734
735     /* Parse struct fields */
736     FlexibleMember = 0;
737     StructSize     = 0;
738     BitOffs        = 0;
739     while (CurTok.Tok != TOK_RCURLY) {
740
741         /* Get the type of the entry */
742         DeclSpec Spec;
743         InitDeclSpec (&Spec);
744         ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
745
746         /* Read fields with this type */
747         while (1) {
748
749             Declaration Decl;
750             ident       Ident;
751
752             /* If we had a flexible array member before, no other fields can
753             ** follow.
754             */
755             if (FlexibleMember) {
756                 Error ("Flexible array member must be last field");
757                 FlexibleMember = 0;     /* Avoid further errors */
758             }
759
760             /* Get type and name of the struct field */
761             ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
762
763             /* Check for a bit-field declaration */
764             FieldWidth = ParseFieldWidth (&Decl);
765
766             /* If this is not a bit field, or the bit field is too large for
767             ** the remainder of the current member, or we have a bit field
768             ** with width zero, align the struct to the next member by adding
769             ** a member with an anonymous name.
770             */
771             if (BitOffs > 0) {
772                 if (FieldWidth <= 0 || (BitOffs + FieldWidth) > (int) INT_BITS) {
773
774                     /* We need an anonymous name */
775                     AnonName (Ident, "bit-field");
776
777                     /* Add an anonymous bit-field that aligns to the next
778                     ** storage unit.
779                     */
780                     AddBitField (Ident, StructSize, BitOffs, INT_BITS - BitOffs);
781
782                     /* No bits left */
783                     StructSize += SIZEOF_INT;
784                     BitOffs = 0;
785                 }
786             }
787
788             /* Apart from the above, a bit field with width 0 is not processed
789             ** further.
790             */
791             if (FieldWidth == 0) {
792                 goto NextMember;
793             }
794
795             /* Check if this field is a flexible array member, and
796             ** calculate the size of the field.
797             */
798             if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
799                 /* Array with unspecified size */
800                 if (StructSize == 0) {
801                     Error ("Flexible array member cannot be first struct field");
802                 }
803                 FlexibleMember = 1;
804                 /* Assume zero for size calculations */
805                 SetElementCount (Decl.Type, FLEXIBLE);
806             }
807
808             /* Check for fields without names */
809             if (Decl.Ident[0] == '\0') {
810                 if (FieldWidth < 0) {
811                     /* In cc65 mode, we allow anonymous structs/unions within
812                     ** a struct.
813                     */
814                     if (IS_Get (&Standard) >= STD_CC65 && IsClassStruct (Decl.Type)) {
815
816                         /* This is an anonymous struct or union. Copy the
817                         ** fields into the current level.
818                         */
819                         StructSize += CopyAnonStructFields (&Decl, StructSize);
820
821                     } else {
822                         /* A non bit-field without a name is legal but useless */
823                         Warning ("Declaration does not declare anything");
824                     }
825                     goto NextMember;
826                 } else {
827                     /* A bit-field without a name will get an anonymous one */
828                     AnonName (Decl.Ident, "bit-field");
829                 }
830             }
831
832             /* Add a field entry to the table */
833             if (FieldWidth > 0) {
834                 /* Add full byte from the bit offset to the variable offset.
835                 ** This simplifies handling he bit-field as a char type
836                 ** in expressions.
837                 */
838                 unsigned Offs = StructSize + (BitOffs / CHAR_BITS);
839                 AddBitField (Decl.Ident, Offs, BitOffs % CHAR_BITS, FieldWidth);
840                 BitOffs += FieldWidth;
841                 CHECK (BitOffs <= (int) INT_BITS);
842                 if (BitOffs == INT_BITS) {
843                     StructSize += SIZEOF_INT;
844                     BitOffs = 0;
845                 }
846             } else {
847                 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, StructSize);
848                 if (!FlexibleMember) {
849                     StructSize += CheckedSizeOf (Decl.Type);
850                 }
851             }
852
853 NextMember: if (CurTok.Tok != TOK_COMMA) {
854                 break;
855             }
856             NextToken ();
857         }
858         ConsumeSemi ();
859     }
860
861     /* If we have bits from bit-fields left, add them to the size. */
862     if (BitOffs > 0) {
863         StructSize += ((BitOffs + CHAR_BITS - 1) / CHAR_BITS);
864     }
865
866     /* Skip the closing brace */
867     NextToken ();
868
869     /* Remember the symbol table and leave the struct level */
870     FieldTab = GetSymTab ();
871     LeaveStructLevel ();
872
873     /* Make a real entry from the forward decl and return it */
874     return AddStructSym (Name, SC_STRUCT, StructSize, FieldTab);
875 }
876
877
878
879 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
880 /* Parse a type specifier */
881 {
882     ident       Ident;
883     SymEntry*   Entry;
884
885     /* Assume we have an explicit type */
886     D->Flags &= ~DS_DEF_TYPE;
887
888     /* Read type qualifiers if we have any */
889     Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
890
891     /* Look at the data type */
892     switch (CurTok.Tok) {
893
894         case TOK_VOID:
895             NextToken ();
896             D->Type[0].C = T_VOID;
897             D->Type[1].C = T_END;
898             break;
899
900         case TOK_CHAR:
901             NextToken ();
902             D->Type[0].C = GetDefaultChar();
903             D->Type[1].C = T_END;
904             break;
905
906         case TOK_LONG:
907             NextToken ();
908             if (CurTok.Tok == TOK_UNSIGNED) {
909                 NextToken ();
910                 OptionalInt ();
911                 D->Type[0].C = T_ULONG;
912                 D->Type[1].C = T_END;
913             } else {
914                 OptionalSigned ();
915                 OptionalInt ();
916                 D->Type[0].C = T_LONG;
917                 D->Type[1].C = T_END;
918             }
919             break;
920
921         case TOK_SHORT:
922             NextToken ();
923             if (CurTok.Tok == TOK_UNSIGNED) {
924                 NextToken ();
925                 OptionalInt ();
926                 D->Type[0].C = T_USHORT;
927                 D->Type[1].C = T_END;
928             } else {
929                 OptionalSigned ();
930                 OptionalInt ();
931                 D->Type[0].C = T_SHORT;
932                 D->Type[1].C = T_END;
933             }
934             break;
935
936         case TOK_INT:
937             NextToken ();
938             D->Type[0].C = T_INT;
939             D->Type[1].C = T_END;
940             break;
941
942        case TOK_SIGNED:
943             NextToken ();
944             switch (CurTok.Tok) {
945
946                 case TOK_CHAR:
947                     NextToken ();
948                     D->Type[0].C = T_SCHAR;
949                     D->Type[1].C = T_END;
950                     break;
951
952                 case TOK_SHORT:
953                     NextToken ();
954                     OptionalInt ();
955                     D->Type[0].C = T_SHORT;
956                     D->Type[1].C = T_END;
957                     break;
958
959                 case TOK_LONG:
960                     NextToken ();
961                     OptionalInt ();
962                     D->Type[0].C = T_LONG;
963                     D->Type[1].C = T_END;
964                     break;
965
966                 case TOK_INT:
967                     NextToken ();
968                     /* FALL THROUGH */
969
970                 default:
971                     D->Type[0].C = T_INT;
972                     D->Type[1].C = T_END;
973                     break;
974             }
975             break;
976
977         case TOK_UNSIGNED:
978             NextToken ();
979             switch (CurTok.Tok) {
980
981                 case TOK_CHAR:
982                     NextToken ();
983                     D->Type[0].C = T_UCHAR;
984                     D->Type[1].C = T_END;
985                     break;
986
987                 case TOK_SHORT:
988                     NextToken ();
989                     OptionalInt ();
990                     D->Type[0].C = T_USHORT;
991                     D->Type[1].C = T_END;
992                     break;
993
994                 case TOK_LONG:
995                     NextToken ();
996                     OptionalInt ();
997                     D->Type[0].C = T_ULONG;
998                     D->Type[1].C = T_END;
999                     break;
1000
1001                 case TOK_INT:
1002                     NextToken ();
1003                     /* FALL THROUGH */
1004
1005                 default:
1006                     D->Type[0].C = T_UINT;
1007                     D->Type[1].C = T_END;
1008                     break;
1009             }
1010             break;
1011
1012         case TOK_FLOAT:
1013             NextToken ();
1014             D->Type[0].C = T_FLOAT;
1015             D->Type[1].C = T_END;
1016             break;
1017
1018         case TOK_DOUBLE:
1019             NextToken ();
1020             D->Type[0].C = T_DOUBLE;
1021             D->Type[1].C = T_END;
1022             break;
1023
1024         case TOK_UNION:
1025             NextToken ();
1026             /* */
1027             if (CurTok.Tok == TOK_IDENT) {
1028                 strcpy (Ident, CurTok.Ident);
1029                 NextToken ();
1030             } else {
1031                 AnonName (Ident, "union");
1032             }
1033             /* Remember we have an extra type decl */
1034             D->Flags |= DS_EXTRA_TYPE;
1035             /* Declare the union in the current scope */
1036             Entry = ParseUnionDecl (Ident);
1037             /* Encode the union entry into the type */
1038             D->Type[0].C = T_UNION;
1039             SetSymEntry (D->Type, Entry);
1040             D->Type[1].C = T_END;
1041             break;
1042
1043         case TOK_STRUCT:
1044             NextToken ();
1045             /* */
1046             if (CurTok.Tok == TOK_IDENT) {
1047                 strcpy (Ident, CurTok.Ident);
1048                 NextToken ();
1049             } else {
1050                 AnonName (Ident, "struct");
1051             }
1052             /* Remember we have an extra type decl */
1053             D->Flags |= DS_EXTRA_TYPE;
1054             /* Declare the struct in the current scope */
1055             Entry = ParseStructDecl (Ident);
1056             /* Encode the struct entry into the type */
1057             D->Type[0].C = T_STRUCT;
1058             SetSymEntry (D->Type, Entry);
1059             D->Type[1].C = T_END;
1060             break;
1061
1062         case TOK_ENUM:
1063             NextToken ();
1064             if (CurTok.Tok != TOK_LCURLY) {
1065                 /* Named enum */
1066                 if (CurTok.Tok == TOK_IDENT) {
1067                     /* Find an entry with this name */
1068                     Entry = FindTagSym (CurTok.Ident);
1069                     if (Entry) {
1070                         if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
1071                             Error ("Symbol `%s' is already different kind", Entry->Name);
1072                         }
1073                     } else {
1074                         /* Insert entry into table ### */
1075                     }
1076                     /* Skip the identifier */
1077                     NextToken ();
1078                 } else {
1079                     Error ("Identifier expected");
1080                 }
1081             }
1082             /* Remember we have an extra type decl */
1083             D->Flags |= DS_EXTRA_TYPE;
1084             /* Parse the enum decl */
1085             ParseEnumDecl ();
1086             D->Type[0].C = T_INT;
1087             D->Type[1].C = T_END;
1088             break;
1089
1090         case TOK_IDENT:
1091             Entry = FindSym (CurTok.Ident);
1092             if (Entry && SymIsTypeDef (Entry)) {
1093                 /* It's a typedef */
1094                 NextToken ();
1095                 TypeCopy (D->Type, Entry->Type);
1096                 break;
1097             }
1098             /* FALL THROUGH */
1099
1100         default:
1101             if (Default < 0) {
1102                 Error ("Type expected");
1103                 D->Type[0].C = T_INT;
1104                 D->Type[1].C = T_END;
1105             } else {
1106                 D->Flags |= DS_DEF_TYPE;
1107                 D->Type[0].C = (TypeCode) Default;
1108                 D->Type[1].C = T_END;
1109             }
1110             break;
1111     }
1112
1113     /* There may also be qualifiers *after* the initial type */
1114     D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
1115 }
1116
1117
1118
1119 static Type* ParamTypeCvt (Type* T)
1120 /* If T is an array, convert it to a pointer else do nothing. Return the
1121 ** resulting type.
1122 */
1123 {
1124     if (IsTypeArray (T)) {
1125         T->C = T_PTR;
1126     }
1127     return T;
1128 }
1129
1130
1131
1132 static void ParseOldStyleParamList (FuncDesc* F)
1133 /* Parse an old style (K&R) parameter list */
1134 {
1135     /* Some fix point tokens that are used for error recovery */
1136     static const token_t TokenList[] = { TOK_COMMA, TOK_RPAREN, TOK_SEMI };
1137
1138     /* Parse params */
1139     while (CurTok.Tok != TOK_RPAREN) {
1140
1141         /* List of identifiers expected */
1142         if (CurTok.Tok == TOK_IDENT) {
1143
1144             /* Create a symbol table entry with type int */
1145             AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1146
1147             /* Count arguments */
1148             ++F->ParamCount;
1149
1150             /* Skip the identifier */
1151             NextToken ();
1152
1153         } else {
1154             /* Not a parameter name */
1155             Error ("Identifier expected");
1156
1157             /* Try some smart error recovery */
1158             SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0]));
1159         }
1160
1161         /* Check for more parameters */
1162         if (CurTok.Tok == TOK_COMMA) {
1163             NextToken ();
1164         } else {
1165             break;
1166         }
1167     }
1168
1169     /* Skip right paren. We must explicitly check for one here, since some of
1170     ** the breaks above bail out without checking.
1171     */
1172     ConsumeRParen ();
1173
1174     /* An optional list of type specifications follows */
1175     while (CurTok.Tok != TOK_LCURLY) {
1176
1177         DeclSpec        Spec;
1178
1179         /* Read the declaration specifier */
1180         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1181
1182         /* We accept only auto and register as storage class specifiers, but
1183         ** we ignore all this, since we use auto anyway.
1184         */
1185         if ((Spec.StorageClass & SC_AUTO) == 0 &&
1186             (Spec.StorageClass & SC_REGISTER) == 0) {
1187             Error ("Illegal storage class");
1188         }
1189
1190         /* Parse a comma separated variable list */
1191         while (1) {
1192
1193             Declaration         Decl;
1194
1195             /* Read the parameter */
1196             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1197             if (Decl.Ident[0] != '\0') {
1198
1199                 /* We have a name given. Search for the symbol */
1200                 SymEntry* Sym = FindLocalSym (Decl.Ident);
1201                 if (Sym) {
1202                     /* Check if we already changed the type for this
1203                     ** parameter
1204                     */
1205                     if (Sym->Flags & SC_DEFTYPE) {
1206                         /* Found it, change the default type to the one given */
1207                         ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1208                         /* Reset the "default type" flag */
1209                         Sym->Flags &= ~SC_DEFTYPE;
1210                     } else {
1211                         /* Type has already been changed */
1212                         Error ("Redefinition for parameter `%s'", Sym->Name);
1213                     }
1214                 } else {
1215                     Error ("Unknown identifier: `%s'", Decl.Ident);
1216                 }
1217             }
1218
1219             if (CurTok.Tok == TOK_COMMA) {
1220                 NextToken ();
1221             } else {
1222                 break;
1223             }
1224
1225         }
1226
1227         /* Variable list must be semicolon terminated */
1228         ConsumeSemi ();
1229     }
1230 }
1231
1232
1233
1234 static void ParseAnsiParamList (FuncDesc* F)
1235 /* Parse a new style (ANSI) parameter list */
1236 {
1237     /* Parse params */
1238     while (CurTok.Tok != TOK_RPAREN) {
1239
1240         DeclSpec        Spec;
1241         Declaration     Decl;
1242         SymEntry*       Sym;
1243
1244         /* Allow an ellipsis as last parameter */
1245         if (CurTok.Tok == TOK_ELLIPSIS) {
1246             NextToken ();
1247             F->Flags |= FD_VARIADIC;
1248             break;
1249         }
1250
1251         /* Read the declaration specifier */
1252         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1253
1254         /* We accept only auto and register as storage class specifiers */
1255         if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1256             Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1257         } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1258             Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1259         } else {
1260             Error ("Illegal storage class");
1261             Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1262         }
1263
1264         /* Allow parameters without a name, but remember if we had some to
1265         ** eventually print an error message later.
1266         */
1267         ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1268         if (Decl.Ident[0] == '\0') {
1269
1270             /* Unnamed symbol. Generate a name that is not user accessible,
1271             ** then handle the symbol normal.
1272             */
1273             AnonName (Decl.Ident, "param");
1274             F->Flags |= FD_UNNAMED_PARAMS;
1275
1276             /* Clear defined bit on nonames */
1277             Decl.StorageClass &= ~SC_DEF;
1278         }
1279
1280         /* Parse attributes for this parameter */
1281         ParseAttribute (&Decl);
1282
1283         /* Create a symbol table entry */
1284         Sym = AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1285
1286         /* Add attributes if we have any */
1287         SymUseAttr (Sym, &Decl);
1288
1289         /* If the parameter is a struct or union, emit a warning */
1290         if (IsClassStruct (Decl.Type)) {
1291             if (IS_Get (&WarnStructParam)) {
1292                 Warning ("Passing struct by value for parameter `%s'", Decl.Ident);
1293             }
1294         }
1295
1296         /* Count arguments */
1297         ++F->ParamCount;
1298
1299         /* Check for more parameters */
1300         if (CurTok.Tok == TOK_COMMA) {
1301             NextToken ();
1302         } else {
1303             break;
1304         }
1305     }
1306
1307     /* Skip right paren. We must explicitly check for one here, since some of
1308     ** the breaks above bail out without checking.
1309     */
1310     ConsumeRParen ();
1311 }
1312
1313
1314
1315 static FuncDesc* ParseFuncDecl (void)
1316 /* Parse the argument list of a function. */
1317 {
1318     unsigned Offs;
1319     SymEntry* Sym;
1320
1321     /* Create a new function descriptor */
1322     FuncDesc* F = NewFuncDesc ();
1323
1324     /* Enter a new lexical level */
1325     EnterFunctionLevel ();
1326
1327     /* Check for several special parameter lists */
1328     if (CurTok.Tok == TOK_RPAREN) {
1329         /* Parameter list is empty */
1330         F->Flags |= (FD_EMPTY | FD_VARIADIC);
1331     } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1332         /* Parameter list declared as void */
1333         NextToken ();
1334         F->Flags |= FD_VOID_PARAM;
1335     } else if (CurTok.Tok == TOK_IDENT &&
1336                (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1337         /* If the identifier is a typedef, we have a new style parameter list,
1338         ** if it's some other identifier, it's an old style parameter list.
1339         */
1340         Sym = FindSym (CurTok.Ident);
1341         if (Sym == 0 || !SymIsTypeDef (Sym)) {
1342             /* Old style (K&R) function. */
1343             F->Flags |= FD_OLDSTYLE;
1344         }
1345     }
1346
1347     /* Parse params */
1348     if ((F->Flags & FD_OLDSTYLE) == 0) {
1349
1350         /* New style function */
1351         ParseAnsiParamList (F);
1352
1353     } else {
1354         /* Old style function */
1355         ParseOldStyleParamList (F);
1356     }
1357
1358     /* Remember the last function parameter. We need it later for several
1359     ** purposes, for example when passing stuff to fastcall functions. Since
1360     ** more symbols are added to the table, it is easier if we remember it
1361     ** now, since it is currently the last entry in the symbol table.
1362     */
1363     F->LastParam = GetSymTab()->SymTail;
1364
1365     /* Assign offsets. If the function has a variable parameter list,
1366     ** there's one additional byte (the arg size).
1367     */
1368     Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1369     Sym = F->LastParam;
1370     while (Sym) {
1371         unsigned Size = CheckedSizeOf (Sym->Type);
1372         if (SymIsRegVar (Sym)) {
1373             Sym->V.R.SaveOffs = Offs;
1374         } else {
1375             Sym->V.Offs = Offs;
1376         }
1377         Offs += Size;
1378         F->ParamSize += Size;
1379         Sym = Sym->PrevSym;
1380     }
1381
1382     /* Leave the lexical level remembering the symbol tables */
1383     RememberFunctionLevel (F);
1384
1385     /* Return the function descriptor */
1386     return F;
1387 }
1388
1389
1390
1391 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1392 /* Recursively process declarators. Build a type array in reverse order. */
1393 {
1394     /* Read optional function or pointer qualifiers. They modify the
1395     ** identifier or token to the right. For convenience, we allow a calling
1396     ** convention also for pointers here. If it's a pointer-to-function, the
1397     ** qualifier later will be transfered to the function itself. If it's a
1398     ** pointer to something else, it will be flagged as an error.
1399     */
1400     TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_CCONV);
1401
1402     /* Pointer to something */
1403     if (CurTok.Tok == TOK_STAR) {
1404
1405         /* Skip the star */
1406         NextToken ();
1407
1408         /* Allow const, restrict, and volatile qualifiers */
1409         Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1410
1411         /* Parse the type that the pointer points to */
1412         Declarator (Spec, D, Mode);
1413
1414         /* Add the type */
1415         AddTypeToDeclaration (D, T_PTR | Qualifiers);
1416         return;
1417     }
1418
1419     if (CurTok.Tok == TOK_LPAREN) {
1420         NextToken ();
1421         Declarator (Spec, D, Mode);
1422         ConsumeRParen ();
1423     } else {
1424         /* Things depend on Mode now:
1425         **  - Mode == DM_NEED_IDENT means:
1426         **      we *must* have a type and a variable identifer.
1427         **  - Mode == DM_NO_IDENT means:
1428         **      we must have a type but no variable identifer
1429         **      (if there is one, it's not read).
1430         **  - Mode == DM_ACCEPT_IDENT means:
1431         **      we *may* have an identifier. If there is an identifier,
1432         **      it is read, but it is no error, if there is none.
1433         */
1434         if (Mode == DM_NO_IDENT) {
1435             D->Ident[0] = '\0';
1436         } else if (CurTok.Tok == TOK_IDENT) {
1437             strcpy (D->Ident, CurTok.Ident);
1438             NextToken ();
1439         } else {
1440             if (Mode == DM_NEED_IDENT) {
1441                 Error ("Identifier expected");
1442             }
1443             D->Ident[0] = '\0';
1444         }
1445     }
1446
1447     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1448         if (CurTok.Tok == TOK_LPAREN) {
1449
1450             /* Function declaration */
1451             FuncDesc* F;
1452
1453             /* Skip the opening paren */
1454             NextToken ();
1455
1456             /* Parse the function declaration */
1457             F = ParseFuncDecl ();
1458
1459             /* We cannot specify fastcall for variadic functions */
1460             if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1461                 Error ("Variadic functions cannot be `__fastcall__'");
1462                 Qualifiers &= ~T_QUAL_FASTCALL;
1463             }
1464
1465             /* Add the function type. Be sure to bounds check the type buffer */
1466             NeedTypeSpace (D, 1);
1467             D->Type[D->Index].C = T_FUNC | Qualifiers;
1468             D->Type[D->Index].A.P = F;
1469             ++D->Index;
1470
1471             /* Qualifiers now used */
1472             Qualifiers = T_QUAL_NONE;
1473
1474         } else {
1475             /* Array declaration. */
1476             long Size = UNSPECIFIED;
1477
1478             /* We cannot have any qualifiers for an array */
1479             if (Qualifiers != T_QUAL_NONE) {
1480                 Error ("Invalid qualifiers for array");
1481                 Qualifiers = T_QUAL_NONE;
1482             }
1483
1484             /* Skip the left bracket */
1485             NextToken ();
1486
1487             /* Read the size if it is given */
1488             if (CurTok.Tok != TOK_RBRACK) {
1489                 ExprDesc Expr;
1490                 ConstAbsIntExpr (hie1, &Expr);
1491                 if (Expr.IVal <= 0) {
1492                     if (D->Ident[0] != '\0') {
1493                         Error ("Size of array `%s' is invalid", D->Ident);
1494                     } else {
1495                         Error ("Size of array is invalid");
1496                     }
1497                     Expr.IVal = 1;
1498                 }
1499                 Size = Expr.IVal;
1500             }
1501
1502             /* Skip the right bracket */
1503             ConsumeRBrack ();
1504
1505             /* Add the array type with the size to the type */
1506             NeedTypeSpace (D, 1);
1507             D->Type[D->Index].C = T_ARRAY;
1508             D->Type[D->Index].A.L = Size;
1509             ++D->Index;
1510         }
1511     }
1512
1513     /* If we have remaining qualifiers, flag them as invalid */
1514     if (Qualifiers & T_QUAL_NEAR) {
1515         Error ("Invalid `__near__' qualifier");
1516     }
1517     if (Qualifiers & T_QUAL_FAR) {
1518         Error ("Invalid `__far__' qualifier");
1519     }
1520     if (Qualifiers & T_QUAL_FASTCALL) {
1521         Error ("Invalid `__fastcall__' qualifier");
1522     }
1523     if (Qualifiers & T_QUAL_CDECL) {
1524         Error ("Invalid `__cdecl__' qualifier");
1525     }
1526 }
1527
1528
1529
1530 /*****************************************************************************/
1531 /*                                   code                                    */
1532 /*****************************************************************************/
1533
1534
1535
1536 Type* ParseType (Type* T)
1537 /* Parse a complete type specification */
1538 {
1539     DeclSpec Spec;
1540     Declaration Decl;
1541
1542     /* Get a type without a default */
1543     InitDeclSpec (&Spec);
1544     ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1545
1546     /* Parse additional declarators */
1547     ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1548
1549     /* Copy the type to the target buffer */
1550     TypeCopy (T, Decl.Type);
1551
1552     /* Return a pointer to the target buffer */
1553     return T;
1554 }
1555
1556
1557
1558 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1559 /* Parse a variable, type or function declaration */
1560 {
1561     /* Initialize the Declaration struct */
1562     InitDeclaration (D);
1563
1564     /* Get additional declarators and the identifier */
1565     Declarator (Spec, D, Mode);
1566
1567     /* Add the base type. */
1568     NeedTypeSpace (D, TypeLen (Spec->Type) + 1);        /* Bounds check */
1569     TypeCopy (D->Type + D->Index, Spec->Type);
1570
1571     /* Use the storage class from the declspec */
1572     D->StorageClass = Spec->StorageClass;
1573
1574     /* Do several fixes on qualifiers */
1575     FixQualifiers (D->Type);
1576
1577     /* If we have a function, add a special storage class */
1578     if (IsTypeFunc (D->Type)) {
1579         D->StorageClass |= SC_FUNC;
1580     }
1581
1582     /* Parse attributes for this declaration */
1583     ParseAttribute (D);
1584
1585     /* Check several things for function or function pointer types */
1586     if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1587
1588         /* A function. Check the return type */
1589         Type* RetType = GetFuncReturn (D->Type);
1590
1591         /* Functions may not return functions or arrays */
1592         if (IsTypeFunc (RetType)) {
1593             Error ("Functions are not allowed to return functions");
1594         } else if (IsTypeArray (RetType)) {
1595             Error ("Functions are not allowed to return arrays");
1596         }
1597
1598         /* The return type must not be qualified */
1599         if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1600
1601             if (GetType (RetType) == T_TYPE_VOID) {
1602                 /* A qualified void type is always an error */
1603                 Error ("function definition has qualified void return type");
1604             } else {
1605                 /* For others, qualifiers are ignored */
1606                 Warning ("type qualifiers ignored on function return type");
1607                 RetType[0].C = UnqualifiedType (RetType[0].C);
1608             }
1609         }
1610
1611         /* Warn about an implicit int return in the function */
1612         if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1613             RetType[0].C == T_INT && RetType[1].C == T_END) {
1614             /* Function has an implicit int return. Output a warning if we don't
1615             ** have the C89 standard enabled explicitly.
1616             */
1617             if (IS_Get (&Standard) >= STD_C99) {
1618                 Warning ("Implicit `int' return type is an obsolete feature");
1619             }
1620             GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1621         }
1622
1623     }
1624
1625     /* For anthing that is not a function or typedef, check for an implicit
1626     ** int declaration.
1627     */
1628     if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1629         (D->StorageClass & SC_TYPEMASK) != SC_TYPEDEF) {
1630         /* If the standard was not set explicitly to C89, print a warning
1631         ** for variables with implicit int type.
1632         */
1633         if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1634             Warning ("Implicit `int' is an obsolete feature");
1635         }
1636     }
1637
1638     /* Check the size of the generated type */
1639     if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1640         unsigned Size = SizeOf (D->Type);
1641         if (Size >= 0x10000) {
1642             if (D->Ident[0] != '\0') {
1643                 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1644             } else {
1645                 Error ("Invalid size in declaration (0x%06X)", Size);
1646             }
1647         }
1648     }
1649
1650 }
1651
1652
1653
1654 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1655 /* Parse a declaration specification */
1656 {
1657     TypeCode Qualifiers;
1658
1659     /* Initialize the DeclSpec struct */
1660     InitDeclSpec (D);
1661
1662     /* There may be qualifiers *before* the storage class specifier */
1663     Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1664
1665     /* Now get the storage class specifier for this declaration */
1666     ParseStorageClass (D, DefStorage);
1667
1668     /* Parse the type specifiers passing any initial type qualifiers */
1669     ParseTypeSpec (D, DefType, Qualifiers);
1670 }
1671
1672
1673
1674 void CheckEmptyDecl (const DeclSpec* D)
1675 /* Called after an empty type declaration (that is, a type declaration without
1676 ** a variable). Checks if the declaration does really make sense and issues a
1677 ** warning if not.
1678 */
1679 {
1680     if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1681         Warning ("Useless declaration");
1682     }
1683 }
1684
1685
1686
1687 static void SkipInitializer (unsigned BracesExpected)
1688 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1689 ** smart so we don't have too many following errors.
1690 */
1691 {
1692     while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1693         switch (CurTok.Tok) {
1694             case TOK_RCURLY:    --BracesExpected;   break;
1695             case TOK_LCURLY:    ++BracesExpected;   break;
1696             default:                                break;
1697         }
1698         NextToken ();
1699     }
1700 }
1701
1702
1703
1704 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1705 /* Accept any number of opening curly braces around an initialization, skip
1706 ** them and return the number. If the number of curly braces is less than
1707 ** BracesNeeded, issue a warning.
1708 */
1709 {
1710     unsigned BraceCount = 0;
1711     while (CurTok.Tok == TOK_LCURLY) {
1712         ++BraceCount;
1713         NextToken ();
1714     }
1715     if (BraceCount < BracesNeeded) {
1716         Error ("`{' expected");
1717     }
1718     return BraceCount;
1719 }
1720
1721
1722
1723 static void ClosingCurlyBraces (unsigned BracesExpected)
1724 /* Accept and skip the given number of closing curly braces together with
1725 ** an optional comma. Output an error messages, if the input does not contain
1726 ** the expected number of braces.
1727 */
1728 {
1729     while (BracesExpected) {
1730         if (CurTok.Tok == TOK_RCURLY) {
1731             NextToken ();
1732         } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1733             NextToken ();
1734             NextToken ();
1735         } else {
1736             Error ("`}' expected");
1737             return;
1738         }
1739         --BracesExpected;
1740     }
1741 }
1742
1743
1744
1745 static void DefineData (ExprDesc* Expr)
1746 /* Output a data definition for the given expression */
1747 {
1748     switch (ED_GetLoc (Expr)) {
1749
1750         case E_LOC_ABS:
1751             /* Absolute: numeric address or const */
1752             g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1753             break;
1754
1755         case E_LOC_GLOBAL:
1756             /* Global variable */
1757             g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1758             break;
1759
1760         case E_LOC_STATIC:
1761         case E_LOC_LITERAL:
1762             /* Static variable or literal in the literal pool */
1763             g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1764             break;
1765
1766         case E_LOC_REGISTER:
1767             /* Register variable. Taking the address is usually not
1768             ** allowed.
1769             */
1770             if (IS_Get (&AllowRegVarAddr) == 0) {
1771                 Error ("Cannot take the address of a register variable");
1772             }
1773             g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1774             break;
1775
1776         case E_LOC_STACK:
1777         case E_LOC_PRIMARY:
1778         case E_LOC_EXPR:
1779             Error ("Non constant initializer");
1780             break;
1781
1782         default:
1783             Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1784     }
1785 }
1786
1787
1788
1789 static void OutputBitFieldData (StructInitData* SI)
1790 /* Output bit field data */
1791 {
1792     /* Ignore if we have no data */
1793     if (SI->ValBits > 0) {
1794
1795         /* Output the data */
1796         g_defdata (CF_INT | CF_UNSIGNED | CF_CONST, SI->BitVal, 0);
1797
1798         /* Clear the data from SI and account for the size */
1799         SI->BitVal  = 0;
1800         SI->ValBits = 0;
1801         SI->Offs   += SIZEOF_INT;
1802     }
1803 }
1804
1805
1806
1807 static void ParseScalarInitInternal (Type* T, ExprDesc* ED)
1808 /* Parse initializaton for scalar data types. This function will not output the
1809 ** data but return it in ED.
1810 */
1811 {
1812     /* Optional opening brace */
1813     unsigned BraceCount = OpeningCurlyBraces (0);
1814
1815     /* We warn if an initializer for a scalar contains braces, because this is
1816     ** quite unusual and often a sign for some problem in the input.
1817     */
1818     if (BraceCount > 0) {
1819         Warning ("Braces around scalar initializer");
1820     }
1821
1822     /* Get the expression and convert it to the target type */
1823     ConstExpr (hie1, ED);
1824     TypeConversion (ED, T);
1825
1826     /* Close eventually opening braces */
1827     ClosingCurlyBraces (BraceCount);
1828 }
1829
1830
1831
1832 static unsigned ParseScalarInit (Type* T)
1833 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1834 {
1835     ExprDesc ED;
1836
1837     /* Parse initialization */
1838     ParseScalarInitInternal (T, &ED);
1839
1840     /* Output the data */
1841     DefineData (&ED);
1842
1843     /* Done */
1844     return SizeOf (T);
1845 }
1846
1847
1848
1849 static unsigned ParsePointerInit (Type* T)
1850 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1851 {
1852     /* Optional opening brace */
1853     unsigned BraceCount = OpeningCurlyBraces (0);
1854
1855     /* Expression */
1856     ExprDesc ED;
1857     ConstExpr (hie1, &ED);
1858     TypeConversion (&ED, T);
1859
1860     /* Output the data */
1861     DefineData (&ED);
1862
1863     /* Close eventually opening braces */
1864     ClosingCurlyBraces (BraceCount);
1865
1866     /* Done */
1867     return SIZEOF_PTR;
1868 }
1869
1870
1871
1872 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1873 /* Parse initializaton for arrays. Return the number of data bytes. */
1874 {
1875     int Count;
1876
1877     /* Get the array data */
1878     Type* ElementType    = GetElementType (T);
1879     unsigned ElementSize = CheckedSizeOf (ElementType);
1880     long ElementCount    = GetElementCount (T);
1881
1882     /* Special handling for a character array initialized by a literal */
1883     if (IsTypeChar (ElementType) &&
1884         (CurTok.Tok == TOK_SCONST || CurTok.Tok == TOK_WCSCONST ||
1885         (CurTok.Tok == TOK_LCURLY &&
1886          (NextTok.Tok == TOK_SCONST || NextTok.Tok == TOK_WCSCONST)))) {
1887
1888         /* Char array initialized by string constant */
1889         int NeedParen;
1890
1891         /* If we initializer is enclosed in brackets, remember this fact and
1892         ** skip the opening bracket.
1893         */
1894         NeedParen = (CurTok.Tok == TOK_LCURLY);
1895         if (NeedParen) {
1896             NextToken ();
1897         }
1898
1899         /* Translate into target charset */
1900         TranslateLiteral (CurTok.SVal);
1901
1902         /* If the array is one too small for the string literal, omit the
1903         ** trailing zero.
1904         */
1905         Count = GetLiteralSize (CurTok.SVal);
1906         if (ElementCount != UNSPECIFIED &&
1907             ElementCount != FLEXIBLE    &&
1908             Count        == ElementCount + 1) {
1909             /* Omit the trailing zero */
1910             --Count;
1911         }
1912
1913         /* Output the data */
1914         g_defbytes (GetLiteralStr (CurTok.SVal), Count);
1915
1916         /* Skip the string */
1917         NextToken ();
1918
1919         /* If the initializer was enclosed in curly braces, we need a closing
1920         ** one.
1921         */
1922         if (NeedParen) {
1923             ConsumeRCurly ();
1924         }
1925
1926     } else {
1927
1928         /* Curly brace */
1929         ConsumeLCurly ();
1930
1931         /* Initialize the array members */
1932         Count = 0;
1933         while (CurTok.Tok != TOK_RCURLY) {
1934             /* Flexible array members may not be initialized within
1935             ** an array (because the size of each element may differ
1936             ** otherwise).
1937             */
1938             ParseInitInternal (ElementType, 0);
1939             ++Count;
1940             if (CurTok.Tok != TOK_COMMA)
1941                 break;
1942             NextToken ();
1943         }
1944
1945         /* Closing curly braces */
1946         ConsumeRCurly ();
1947     }
1948
1949     if (ElementCount == UNSPECIFIED) {
1950         /* Number of elements determined by initializer */
1951         SetElementCount (T, Count);
1952         ElementCount = Count;
1953     } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1954         /* In non ANSI mode, allow initialization of flexible array
1955         ** members.
1956         */
1957         ElementCount = Count;
1958     } else if (Count < ElementCount) {
1959         g_zerobytes ((ElementCount - Count) * ElementSize);
1960     } else if (Count > ElementCount) {
1961         Error ("Too many initializers");
1962     }
1963     return ElementCount * ElementSize;
1964 }
1965
1966
1967
1968 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1969 /* Parse initialization of a struct or union. Return the number of data bytes. */
1970 {
1971     SymEntry*       Entry;
1972     SymTable*       Tab;
1973     StructInitData  SI;
1974
1975
1976     /* Consume the opening curly brace */
1977     ConsumeLCurly ();
1978
1979     /* Get a pointer to the struct entry from the type */
1980     Entry = GetSymEntry (T);
1981
1982     /* Get the size of the struct from the symbol table entry */
1983     SI.Size = Entry->V.S.Size;
1984
1985     /* Check if this struct definition has a field table. If it doesn't, it
1986     ** is an incomplete definition.
1987     */
1988     Tab = Entry->V.S.SymTab;
1989     if (Tab == 0) {
1990         Error ("Cannot initialize variables with incomplete type");
1991         /* Try error recovery */
1992         SkipInitializer (1);
1993         /* Nothing initialized */
1994         return 0;
1995     }
1996
1997     /* Get a pointer to the list of symbols */
1998     Entry = Tab->SymHead;
1999
2000     /* Initialize fields */
2001     SI.Offs    = 0;
2002     SI.BitVal  = 0;
2003     SI.ValBits = 0;
2004     while (CurTok.Tok != TOK_RCURLY) {
2005
2006         /* */
2007         if (Entry == 0) {
2008             Error ("Too many initializers");
2009             SkipInitializer (1);
2010             return SI.Offs;
2011         }
2012
2013         /* Parse initialization of one field. Bit-fields need a special
2014         ** handling.
2015         */
2016         if (SymIsBitField (Entry)) {
2017
2018             ExprDesc ED;
2019             unsigned Val;
2020             unsigned Shift;
2021
2022             /* Calculate the bitmask from the bit-field data */
2023             unsigned Mask = (1U << Entry->V.B.BitWidth) - 1U;
2024
2025             /* Safety ... */
2026             CHECK (Entry->V.B.Offs * CHAR_BITS + Entry->V.B.BitOffs ==
2027                    SI.Offs         * CHAR_BITS + SI.ValBits);
2028
2029             /* This may be an anonymous bit-field, in which case it doesn't
2030             ** have an initializer.
2031             */
2032             if (IsAnonName (Entry->Name)) {
2033                 /* Account for the data and output it if we have a full word */
2034                 SI.ValBits += Entry->V.B.BitWidth;
2035                 CHECK (SI.ValBits <= INT_BITS);
2036                 if (SI.ValBits == INT_BITS) {
2037                     OutputBitFieldData (&SI);
2038                 }
2039                 goto NextMember;
2040             } else {
2041                 /* Read the data, check for a constant integer, do a range
2042                 ** check.
2043                 */
2044                 ParseScalarInitInternal (type_uint, &ED);
2045                 if (!ED_IsConstAbsInt (&ED)) {
2046                     Error ("Constant initializer expected");
2047                     ED_MakeConstAbsInt (&ED, 1);
2048                 }
2049                 if (ED.IVal > (long) Mask) {
2050                     Warning ("Truncating value in bit-field initializer");
2051                     ED.IVal &= (long) Mask;
2052                 }
2053                 Val = (unsigned) ED.IVal;
2054             }
2055
2056             /* Add the value to the currently stored bit-field value */
2057             Shift = (Entry->V.B.Offs - SI.Offs) * CHAR_BITS + Entry->V.B.BitOffs;
2058             SI.BitVal |= (Val << Shift);
2059
2060             /* Account for the data and output it if we have a full word */
2061             SI.ValBits += Entry->V.B.BitWidth;
2062             CHECK (SI.ValBits <= INT_BITS);
2063             if (SI.ValBits == INT_BITS) {
2064                 OutputBitFieldData (&SI);
2065             }
2066
2067         } else {
2068
2069             /* Standard member. We should never have stuff from a
2070             ** bit-field left
2071             */
2072             CHECK (SI.ValBits == 0);
2073
2074             /* Flexible array members may only be initialized if they are
2075             ** the last field (or part of the last struct field).
2076             */
2077             SI.Offs += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
2078         }
2079
2080         /* More initializers? */
2081         if (CurTok.Tok != TOK_COMMA) {
2082             break;
2083         }
2084
2085         /* Skip the comma */
2086         NextToken ();
2087
2088 NextMember:
2089         /* Next member. For unions, only the first one can be initialized */
2090         if (IsTypeUnion (T)) {
2091             /* Union */
2092             Entry = 0;
2093         } else {
2094             /* Struct */
2095             Entry = Entry->NextSym;
2096         }
2097     }
2098
2099     /* Consume the closing curly brace */
2100     ConsumeRCurly ();
2101
2102     /* If we have data from a bit-field left, output it now */
2103     OutputBitFieldData (&SI);
2104
2105     /* If there are struct fields left, reserve additional storage */
2106     if (SI.Offs < SI.Size) {
2107         g_zerobytes (SI.Size - SI.Offs);
2108         SI.Offs = SI.Size;
2109     }
2110
2111     /* Return the actual number of bytes initialized. This number may be
2112     ** larger than sizeof (Struct) if flexible array members are present and
2113     ** were initialized (possible in non ANSI mode).
2114     */
2115     return SI.Offs;
2116 }
2117
2118
2119
2120 static unsigned ParseVoidInit (void)
2121 /* Parse an initialization of a void variable (special cc65 extension).
2122 ** Return the number of bytes initialized.
2123 */
2124 {
2125     ExprDesc Expr;
2126     unsigned Size;
2127
2128     /* Opening brace */
2129     ConsumeLCurly ();
2130
2131     /* Allow an arbitrary list of values */
2132     Size = 0;
2133     do {
2134         ConstExpr (hie1, &Expr);
2135         switch (UnqualifiedType (Expr.Type[0].C)) {
2136
2137             case T_SCHAR:
2138             case T_UCHAR:
2139                 if (ED_IsConstAbsInt (&Expr)) {
2140                     /* Make it byte sized */
2141                     Expr.IVal &= 0xFF;
2142                 }
2143                 DefineData (&Expr);
2144                 Size += SIZEOF_CHAR;
2145                 break;
2146
2147             case T_SHORT:
2148             case T_USHORT:
2149             case T_INT:
2150             case T_UINT:
2151             case T_PTR:
2152             case T_ARRAY:
2153                 if (ED_IsConstAbsInt (&Expr)) {
2154                     /* Make it word sized */
2155                     Expr.IVal &= 0xFFFF;
2156                 }
2157                 DefineData (&Expr);
2158                 Size += SIZEOF_INT;
2159                 break;
2160
2161             case T_LONG:
2162             case T_ULONG:
2163                 if (ED_IsConstAbsInt (&Expr)) {
2164                     /* Make it dword sized */
2165                     Expr.IVal &= 0xFFFFFFFF;
2166                 }
2167                 DefineData (&Expr);
2168                 Size += SIZEOF_LONG;
2169                 break;
2170
2171             default:
2172                 Error ("Illegal type in initialization");
2173                 break;
2174
2175         }
2176
2177         if (CurTok.Tok != TOK_COMMA) {
2178             break;
2179         }
2180         NextToken ();
2181
2182     } while (CurTok.Tok != TOK_RCURLY);
2183
2184     /* Closing brace */
2185     ConsumeRCurly ();
2186
2187     /* Return the number of bytes initialized */
2188     return Size;
2189 }
2190
2191
2192
2193 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
2194 /* Parse initialization of variables. Return the number of data bytes. */
2195 {
2196     switch (UnqualifiedType (T->C)) {
2197
2198         case T_SCHAR:
2199         case T_UCHAR:
2200         case T_SHORT:
2201         case T_USHORT:
2202         case T_INT:
2203         case T_UINT:
2204         case T_LONG:
2205         case T_ULONG:
2206         case T_FLOAT:
2207         case T_DOUBLE:
2208             return ParseScalarInit (T);
2209
2210         case T_PTR:
2211             return ParsePointerInit (T);
2212
2213         case T_ARRAY:
2214             return ParseArrayInit (T, AllowFlexibleMembers);
2215
2216         case T_STRUCT:
2217         case T_UNION:
2218             return ParseStructInit (T, AllowFlexibleMembers);
2219
2220         case T_VOID:
2221             if (IS_Get (&Standard) == STD_CC65) {
2222                 /* Special cc65 extension in non ANSI mode */
2223                 return ParseVoidInit ();
2224             }
2225             /* FALLTHROUGH */
2226
2227         default:
2228             Error ("Illegal type");
2229             return SIZEOF_CHAR;
2230
2231     }
2232 }
2233
2234
2235
2236 unsigned ParseInit (Type* T)
2237 /* Parse initialization of variables. Return the number of data bytes. */
2238 {
2239     /* Parse the initialization. Flexible array members can only be initialized
2240     ** in cc65 mode.
2241     */
2242     unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
2243
2244     /* The initialization may not generate code on global level, because code
2245     ** outside function scope will never get executed.
2246     */
2247     if (HaveGlobalCode ()) {
2248         Error ("Non constant initializers");
2249         RemoveGlobalCode ();
2250     }
2251
2252     /* Return the size needed for the initialization */
2253     return Size;
2254 }