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