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