]> git.sur5r.net Git - cc65/blob - src/cc65/declare.c
Merge pull request #249 from polluks/master
[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[1].C = T_END;
895             break;
896
897         case TOK_CHAR:
898             NextToken ();
899             D->Type[0].C = GetDefaultChar();
900             D->Type[1].C = T_END;
901             break;
902
903         case TOK_LONG:
904             NextToken ();
905             if (CurTok.Tok == TOK_UNSIGNED) {
906                 NextToken ();
907                 OptionalInt ();
908                 D->Type[0].C = T_ULONG;
909                 D->Type[1].C = T_END;
910             } else {
911                 OptionalSigned ();
912                 OptionalInt ();
913                 D->Type[0].C = T_LONG;
914                 D->Type[1].C = T_END;
915             }
916             break;
917
918         case TOK_SHORT:
919             NextToken ();
920             if (CurTok.Tok == TOK_UNSIGNED) {
921                 NextToken ();
922                 OptionalInt ();
923                 D->Type[0].C = T_USHORT;
924                 D->Type[1].C = T_END;
925             } else {
926                 OptionalSigned ();
927                 OptionalInt ();
928                 D->Type[0].C = T_SHORT;
929                 D->Type[1].C = T_END;
930             }
931             break;
932
933         case TOK_INT:
934             NextToken ();
935             D->Type[0].C = T_INT;
936             D->Type[1].C = T_END;
937             break;
938
939        case TOK_SIGNED:
940             NextToken ();
941             switch (CurTok.Tok) {
942
943                 case TOK_CHAR:
944                     NextToken ();
945                     D->Type[0].C = T_SCHAR;
946                     D->Type[1].C = T_END;
947                     break;
948
949                 case TOK_SHORT:
950                     NextToken ();
951                     OptionalInt ();
952                     D->Type[0].C = T_SHORT;
953                     D->Type[1].C = T_END;
954                     break;
955
956                 case TOK_LONG:
957                     NextToken ();
958                     OptionalInt ();
959                     D->Type[0].C = T_LONG;
960                     D->Type[1].C = T_END;
961                     break;
962
963                 case TOK_INT:
964                     NextToken ();
965                     /* FALL THROUGH */
966
967                 default:
968                     D->Type[0].C = T_INT;
969                     D->Type[1].C = T_END;
970                     break;
971             }
972             break;
973
974         case TOK_UNSIGNED:
975             NextToken ();
976             switch (CurTok.Tok) {
977
978                 case TOK_CHAR:
979                     NextToken ();
980                     D->Type[0].C = T_UCHAR;
981                     D->Type[1].C = T_END;
982                     break;
983
984                 case TOK_SHORT:
985                     NextToken ();
986                     OptionalInt ();
987                     D->Type[0].C = T_USHORT;
988                     D->Type[1].C = T_END;
989                     break;
990
991                 case TOK_LONG:
992                     NextToken ();
993                     OptionalInt ();
994                     D->Type[0].C = T_ULONG;
995                     D->Type[1].C = T_END;
996                     break;
997
998                 case TOK_INT:
999                     NextToken ();
1000                     /* FALL THROUGH */
1001
1002                 default:
1003                     D->Type[0].C = T_UINT;
1004                     D->Type[1].C = T_END;
1005                     break;
1006             }
1007             break;
1008
1009         case TOK_FLOAT:
1010             NextToken ();
1011             D->Type[0].C = T_FLOAT;
1012             D->Type[1].C = T_END;
1013             break;
1014
1015         case TOK_DOUBLE:
1016             NextToken ();
1017             D->Type[0].C = T_DOUBLE;
1018             D->Type[1].C = T_END;
1019             break;
1020
1021         case TOK_UNION:
1022             NextToken ();
1023             /* */
1024             if (CurTok.Tok == TOK_IDENT) {
1025                 strcpy (Ident, CurTok.Ident);
1026                 NextToken ();
1027             } else {
1028                 AnonName (Ident, "union");
1029             }
1030             /* Remember we have an extra type decl */
1031             D->Flags |= DS_EXTRA_TYPE;
1032             /* Declare the union in the current scope */
1033             Entry = ParseUnionDecl (Ident);
1034             /* Encode the union entry into the type */
1035             D->Type[0].C = T_UNION;
1036             SetSymEntry (D->Type, Entry);
1037             D->Type[1].C = T_END;
1038             break;
1039
1040         case TOK_STRUCT:
1041             NextToken ();
1042             /* */
1043             if (CurTok.Tok == TOK_IDENT) {
1044                 strcpy (Ident, CurTok.Ident);
1045                 NextToken ();
1046             } else {
1047                 AnonName (Ident, "struct");
1048             }
1049             /* Remember we have an extra type decl */
1050             D->Flags |= DS_EXTRA_TYPE;
1051             /* Declare the struct in the current scope */
1052             Entry = ParseStructDecl (Ident);
1053             /* Encode the struct entry into the type */
1054             D->Type[0].C = T_STRUCT;
1055             SetSymEntry (D->Type, Entry);
1056             D->Type[1].C = T_END;
1057             break;
1058
1059         case TOK_ENUM:
1060             NextToken ();
1061             if (CurTok.Tok != TOK_LCURLY) {
1062                 /* Named enum */
1063                 if (CurTok.Tok == TOK_IDENT) {
1064                     /* Find an entry with this name */
1065                     Entry = FindTagSym (CurTok.Ident);
1066                     if (Entry) {
1067                         if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
1068                             Error ("Symbol `%s' is already different kind", Entry->Name);
1069                         }
1070                     } else {
1071                         /* Insert entry into table ### */
1072                     }
1073                     /* Skip the identifier */
1074                     NextToken ();
1075                 } else {
1076                     Error ("Identifier expected");
1077                 }
1078             }
1079             /* Remember we have an extra type decl */
1080             D->Flags |= DS_EXTRA_TYPE;
1081             /* Parse the enum decl */
1082             ParseEnumDecl ();
1083             D->Type[0].C = T_INT;
1084             D->Type[1].C = T_END;
1085             break;
1086
1087         case TOK_IDENT:
1088             Entry = FindSym (CurTok.Ident);
1089             if (Entry && SymIsTypeDef (Entry)) {
1090                 /* It's a typedef */
1091                 NextToken ();
1092                 TypeCopy (D->Type, Entry->Type);
1093                 break;
1094             }
1095             /* FALL THROUGH */
1096
1097         default:
1098             if (Default < 0) {
1099                 Error ("Type expected");
1100                 D->Type[0].C = T_INT;
1101                 D->Type[1].C = T_END;
1102             } else {
1103                 D->Flags |= DS_DEF_TYPE;
1104                 D->Type[0].C = (TypeCode) Default;
1105                 D->Type[1].C = T_END;
1106             }
1107             break;
1108     }
1109
1110     /* There may also be qualifiers *after* the initial type */
1111     D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
1112 }
1113
1114
1115
1116 static Type* ParamTypeCvt (Type* T)
1117 /* If T is an array, convert it to a pointer else do nothing. Return the
1118 ** resulting type.
1119 */
1120 {
1121     if (IsTypeArray (T)) {
1122         T->C = T_PTR;
1123     }
1124     return T;
1125 }
1126
1127
1128
1129 static void ParseOldStyleParamList (FuncDesc* F)
1130 /* Parse an old style (K&R) parameter list */
1131 {
1132     /* Some fix point tokens that are used for error recovery */
1133     static const token_t TokenList[] = { TOK_COMMA, TOK_RPAREN, TOK_SEMI };
1134
1135     /* Parse params */
1136     while (CurTok.Tok != TOK_RPAREN) {
1137
1138         /* List of identifiers expected */
1139         if (CurTok.Tok == TOK_IDENT) {
1140
1141             /* Create a symbol table entry with type int */
1142             AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1143
1144             /* Count arguments */
1145             ++F->ParamCount;
1146
1147             /* Skip the identifier */
1148             NextToken ();
1149
1150         } else {
1151             /* Not a parameter name */
1152             Error ("Identifier expected");
1153
1154             /* Try some smart error recovery */
1155             SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0]));
1156         }
1157
1158         /* Check for more parameters */
1159         if (CurTok.Tok == TOK_COMMA) {
1160             NextToken ();
1161         } else {
1162             break;
1163         }
1164     }
1165
1166     /* Skip right paren. We must explicitly check for one here, since some of
1167     ** the breaks above bail out without checking.
1168     */
1169     ConsumeRParen ();
1170
1171     /* An optional list of type specifications follows */
1172     while (CurTok.Tok != TOK_LCURLY) {
1173
1174         DeclSpec        Spec;
1175
1176         /* Read the declaration specifier */
1177         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1178
1179         /* We accept only auto and register as storage class specifiers, but
1180         ** we ignore all this, since we use auto anyway.
1181         */
1182         if ((Spec.StorageClass & SC_AUTO) == 0 &&
1183             (Spec.StorageClass & SC_REGISTER) == 0) {
1184             Error ("Illegal storage class");
1185         }
1186
1187         /* Parse a comma separated variable list */
1188         while (1) {
1189
1190             Declaration         Decl;
1191
1192             /* Read the parameter */
1193             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1194             if (Decl.Ident[0] != '\0') {
1195
1196                 /* We have a name given. Search for the symbol */
1197                 SymEntry* Sym = FindLocalSym (Decl.Ident);
1198                 if (Sym) {
1199                     /* Check if we already changed the type for this
1200                     ** parameter
1201                     */
1202                     if (Sym->Flags & SC_DEFTYPE) {
1203                         /* Found it, change the default type to the one given */
1204                         ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1205                         /* Reset the "default type" flag */
1206                         Sym->Flags &= ~SC_DEFTYPE;
1207                     } else {
1208                         /* Type has already been changed */
1209                         Error ("Redefinition for parameter `%s'", Sym->Name);
1210                     }
1211                 } else {
1212                     Error ("Unknown identifier: `%s'", Decl.Ident);
1213                 }
1214             }
1215
1216             if (CurTok.Tok == TOK_COMMA) {
1217                 NextToken ();
1218             } else {
1219                 break;
1220             }
1221
1222         }
1223
1224         /* Variable list must be semicolon terminated */
1225         ConsumeSemi ();
1226     }
1227 }
1228
1229
1230
1231 static void ParseAnsiParamList (FuncDesc* F)
1232 /* Parse a new style (ANSI) parameter list */
1233 {
1234     /* Parse params */
1235     while (CurTok.Tok != TOK_RPAREN) {
1236
1237         DeclSpec        Spec;
1238         Declaration     Decl;
1239         SymEntry*       Sym;
1240
1241         /* Allow an ellipsis as last parameter */
1242         if (CurTok.Tok == TOK_ELLIPSIS) {
1243             NextToken ();
1244             F->Flags |= FD_VARIADIC;
1245             break;
1246         }
1247
1248         /* Read the declaration specifier */
1249         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1250
1251         /* We accept only auto and register as storage class specifiers */
1252         if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1253             Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1254         } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1255             Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1256         } else {
1257             Error ("Illegal storage class");
1258             Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1259         }
1260
1261         /* Allow parameters without a name, but remember if we had some to
1262         ** eventually print an error message later.
1263         */
1264         ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1265         if (Decl.Ident[0] == '\0') {
1266
1267             /* Unnamed symbol. Generate a name that is not user accessible,
1268             ** then handle the symbol normal.
1269             */
1270             AnonName (Decl.Ident, "param");
1271             F->Flags |= FD_UNNAMED_PARAMS;
1272
1273             /* Clear defined bit on nonames */
1274             Decl.StorageClass &= ~SC_DEF;
1275         }
1276
1277         /* Parse attributes for this parameter */
1278         ParseAttribute (&Decl);
1279
1280         /* Create a symbol table entry */
1281         Sym = AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1282
1283         /* Add attributes if we have any */
1284         SymUseAttr (Sym, &Decl);
1285
1286         /* If the parameter is a struct or union, emit a warning */
1287         if (IsClassStruct (Decl.Type)) {
1288             if (IS_Get (&WarnStructParam)) {
1289                 Warning ("Passing struct by value for parameter `%s'", Decl.Ident);
1290             }
1291         }
1292
1293         /* Count arguments */
1294         ++F->ParamCount;
1295
1296         /* Check for more parameters */
1297         if (CurTok.Tok == TOK_COMMA) {
1298             NextToken ();
1299         } else {
1300             break;
1301         }
1302     }
1303
1304     /* Skip right paren. We must explicitly check for one here, since some of
1305     ** the breaks above bail out without checking.
1306     */
1307     ConsumeRParen ();
1308 }
1309
1310
1311
1312 static FuncDesc* ParseFuncDecl (void)
1313 /* Parse the argument list of a function. */
1314 {
1315     unsigned Offs;
1316     SymEntry* Sym;
1317
1318     /* Create a new function descriptor */
1319     FuncDesc* F = NewFuncDesc ();
1320
1321     /* Enter a new lexical level */
1322     EnterFunctionLevel ();
1323
1324     /* Check for several special parameter lists */
1325     if (CurTok.Tok == TOK_RPAREN) {
1326         /* Parameter list is empty */
1327         F->Flags |= (FD_EMPTY | FD_VARIADIC);
1328     } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1329         /* Parameter list declared as void */
1330         NextToken ();
1331         F->Flags |= FD_VOID_PARAM;
1332     } else if (CurTok.Tok == TOK_IDENT &&
1333                (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1334         /* If the identifier is a typedef, we have a new style parameter list,
1335         ** if it's some other identifier, it's an old style parameter list.
1336         */
1337         Sym = FindSym (CurTok.Ident);
1338         if (Sym == 0 || !SymIsTypeDef (Sym)) {
1339             /* Old style (K&R) function. */
1340             F->Flags |= FD_OLDSTYLE;
1341         }
1342     }
1343
1344     /* Parse params */
1345     if ((F->Flags & FD_OLDSTYLE) == 0) {
1346
1347         /* New style function */
1348         ParseAnsiParamList (F);
1349
1350     } else {
1351         /* Old style function */
1352         ParseOldStyleParamList (F);
1353     }
1354
1355     /* Remember the last function parameter. We need it later for several
1356     ** purposes, for example when passing stuff to fastcall functions. Since
1357     ** more symbols are added to the table, it is easier if we remember it
1358     ** now, since it is currently the last entry in the symbol table.
1359     */
1360     F->LastParam = GetSymTab()->SymTail;
1361
1362     /* Assign offsets. If the function has a variable parameter list,
1363     ** there's one additional byte (the arg size).
1364     */
1365     Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1366     Sym = F->LastParam;
1367     while (Sym) {
1368         unsigned Size = CheckedSizeOf (Sym->Type);
1369         if (SymIsRegVar (Sym)) {
1370             Sym->V.R.SaveOffs = Offs;
1371         } else {
1372             Sym->V.Offs = Offs;
1373         }
1374         Offs += Size;
1375         F->ParamSize += Size;
1376         Sym = Sym->PrevSym;
1377     }
1378
1379     /* Leave the lexical level remembering the symbol tables */
1380     RememberFunctionLevel (F);
1381
1382     /* Return the function descriptor */
1383     return F;
1384 }
1385
1386
1387
1388 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1389 /* Recursively process declarators. Build a type array in reverse order. */
1390 {
1391     /* Read optional function or pointer qualifiers. They modify the
1392     ** identifier or token to the right. For convenience, we allow a calling
1393     ** convention also for pointers here. If it's a pointer-to-function, the
1394     ** qualifier later will be transfered to the function itself. If it's a
1395     ** pointer to something else, it will be flagged as an error.
1396     */
1397     TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_CCONV);
1398
1399     /* Pointer to something */
1400     if (CurTok.Tok == TOK_STAR) {
1401
1402         /* Skip the star */
1403         NextToken ();
1404
1405         /* Allow const, restrict, and volatile qualifiers */
1406         Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1407
1408         /* Parse the type that the pointer points to */
1409         Declarator (Spec, D, Mode);
1410
1411         /* Add the type */
1412         AddTypeToDeclaration (D, T_PTR | Qualifiers);
1413         return;
1414     }
1415
1416     if (CurTok.Tok == TOK_LPAREN) {
1417         NextToken ();
1418         Declarator (Spec, D, Mode);
1419         ConsumeRParen ();
1420     } else {
1421         /* Things depend on Mode now:
1422         **  - Mode == DM_NEED_IDENT means:
1423         **      we *must* have a type and a variable identifer.
1424         **  - Mode == DM_NO_IDENT means:
1425         **      we must have a type but no variable identifer
1426         **      (if there is one, it's not read).
1427         **  - Mode == DM_ACCEPT_IDENT means:
1428         **      we *may* have an identifier. If there is an identifier,
1429         **      it is read, but it is no error, if there is none.
1430         */
1431         if (Mode == DM_NO_IDENT) {
1432             D->Ident[0] = '\0';
1433         } else if (CurTok.Tok == TOK_IDENT) {
1434             strcpy (D->Ident, CurTok.Ident);
1435             NextToken ();
1436         } else {
1437             if (Mode == DM_NEED_IDENT) {
1438                 Error ("Identifier expected");
1439             }
1440             D->Ident[0] = '\0';
1441         }
1442     }
1443
1444     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1445         if (CurTok.Tok == TOK_LPAREN) {
1446
1447             /* Function declaration */
1448             FuncDesc* F;
1449
1450             /* Skip the opening paren */
1451             NextToken ();
1452
1453             /* Parse the function declaration */
1454             F = ParseFuncDecl ();
1455
1456             /* We cannot specify fastcall for variadic functions */
1457             if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1458                 Error ("Variadic functions cannot be __fastcall__");
1459                 Qualifiers &= ~T_QUAL_FASTCALL;
1460             }
1461
1462             /* Add the function type. Be sure to bounds check the type buffer */
1463             NeedTypeSpace (D, 1);
1464             D->Type[D->Index].C = T_FUNC | Qualifiers;
1465             D->Type[D->Index].A.P = F;
1466             ++D->Index;
1467
1468             /* Qualifiers now used */
1469             Qualifiers = T_QUAL_NONE;
1470
1471         } else {
1472             /* Array declaration. */
1473             long Size = UNSPECIFIED;
1474
1475             /* We cannot have any qualifiers for an array */
1476             if (Qualifiers != T_QUAL_NONE) {
1477                 Error ("Invalid qualifiers for array");
1478                 Qualifiers = T_QUAL_NONE;
1479             }
1480
1481             /* Skip the left bracket */
1482             NextToken ();
1483
1484             /* Read the size if it is given */
1485             if (CurTok.Tok != TOK_RBRACK) {
1486                 ExprDesc Expr;
1487                 ConstAbsIntExpr (hie1, &Expr);
1488                 if (Expr.IVal <= 0) {
1489                     if (D->Ident[0] != '\0') {
1490                         Error ("Size of array `%s' is invalid", D->Ident);
1491                     } else {
1492                         Error ("Size of array is invalid");
1493                     }
1494                     Expr.IVal = 1;
1495                 }
1496                 Size = Expr.IVal;
1497             }
1498
1499             /* Skip the right bracket */
1500             ConsumeRBrack ();
1501
1502             /* Add the array type with the size to the type */
1503             NeedTypeSpace (D, 1);
1504             D->Type[D->Index].C = T_ARRAY;
1505             D->Type[D->Index].A.L = Size;
1506             ++D->Index;
1507         }
1508     }
1509
1510     /* If we have remaining qualifiers, flag them as invalid */
1511     if (Qualifiers & T_QUAL_NEAR) {
1512         Error ("Invalid `__near__' qualifier");
1513     }
1514     if (Qualifiers & T_QUAL_FAR) {
1515         Error ("Invalid `__far__' qualifier");
1516     }
1517     if (Qualifiers & T_QUAL_FASTCALL) {
1518         Error ("Invalid `__fastcall__' qualifier");
1519     }
1520     if (Qualifiers & T_QUAL_CDECL) {
1521         Error ("Invalid `__cdecl__' qualifier");
1522     }
1523 }
1524
1525
1526
1527 /*****************************************************************************/
1528 /*                                   code                                    */
1529 /*****************************************************************************/
1530
1531
1532
1533 Type* ParseType (Type* T)
1534 /* Parse a complete type specification */
1535 {
1536     DeclSpec Spec;
1537     Declaration Decl;
1538
1539     /* Get a type without a default */
1540     InitDeclSpec (&Spec);
1541     ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1542
1543     /* Parse additional declarators */
1544     ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1545
1546     /* Copy the type to the target buffer */
1547     TypeCopy (T, Decl.Type);
1548
1549     /* Return a pointer to the target buffer */
1550     return T;
1551 }
1552
1553
1554
1555 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1556 /* Parse a variable, type or function declaration */
1557 {
1558     /* Initialize the Declaration struct */
1559     InitDeclaration (D);
1560
1561     /* Get additional declarators and the identifier */
1562     Declarator (Spec, D, Mode);
1563
1564     /* Add the base type. */
1565     NeedTypeSpace (D, TypeLen (Spec->Type) + 1);        /* Bounds check */
1566     TypeCopy (D->Type + D->Index, Spec->Type);
1567
1568     /* Use the storage class from the declspec */
1569     D->StorageClass = Spec->StorageClass;
1570
1571     /* Do several fixes on qualifiers */
1572     FixQualifiers (D->Type);
1573
1574     /* If we have a function, add a special storage class */
1575     if (IsTypeFunc (D->Type)) {
1576         D->StorageClass |= SC_FUNC;
1577     }
1578
1579     /* Parse attributes for this declaration */
1580     ParseAttribute (D);
1581
1582     /* Check several things for function or function pointer types */
1583     if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1584
1585         /* A function. Check the return type */
1586         Type* RetType = GetFuncReturn (D->Type);
1587
1588         /* Functions may not return functions or arrays */
1589         if (IsTypeFunc (RetType)) {
1590             Error ("Functions are not allowed to return functions");
1591         } else if (IsTypeArray (RetType)) {
1592             Error ("Functions are not allowed to return arrays");
1593         }
1594
1595         /* The return type must not be qualified */
1596         if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1597
1598             if (GetType (RetType) == T_TYPE_VOID) {
1599                 /* A qualified void type is always an error */
1600                 Error ("function definition has qualified void return type");
1601             } else {
1602                 /* For others, qualifiers are ignored */
1603                 Warning ("type qualifiers ignored on function return type");
1604                 RetType[0].C = UnqualifiedType (RetType[0].C);
1605             }
1606         }
1607
1608         /* Warn about an implicit int return in the function */
1609         if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1610             RetType[0].C == T_INT && RetType[1].C == T_END) {
1611             /* Function has an implicit int return. Output a warning if we don't
1612             ** have the C89 standard enabled explicitly.
1613             */
1614             if (IS_Get (&Standard) >= STD_C99) {
1615                 Warning ("Implicit `int' return type is an obsolete feature");
1616             }
1617             GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1618         }
1619
1620     }
1621
1622     /* For anthing that is not a function or typedef, check for an implicit
1623     ** int declaration.
1624     */
1625     if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1626         (D->StorageClass & SC_TYPEMASK) != SC_TYPEDEF) {
1627         /* If the standard was not set explicitly to C89, print a warning
1628         ** for variables with implicit int type.
1629         */
1630         if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1631             Warning ("Implicit `int' is an obsolete feature");
1632         }
1633     }
1634
1635     /* Check the size of the generated type */
1636     if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1637         unsigned Size = SizeOf (D->Type);
1638         if (Size >= 0x10000) {
1639             if (D->Ident[0] != '\0') {
1640                 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1641             } else {
1642                 Error ("Invalid size in declaration (0x%06X)", Size);
1643             }
1644         }
1645     }
1646
1647 }
1648
1649
1650
1651 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1652 /* Parse a declaration specification */
1653 {
1654     TypeCode Qualifiers;
1655
1656     /* Initialize the DeclSpec struct */
1657     InitDeclSpec (D);
1658
1659     /* There may be qualifiers *before* the storage class specifier */
1660     Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1661
1662     /* Now get the storage class specifier for this declaration */
1663     ParseStorageClass (D, DefStorage);
1664
1665     /* Parse the type specifiers passing any initial type qualifiers */
1666     ParseTypeSpec (D, DefType, Qualifiers);
1667 }
1668
1669
1670
1671 void CheckEmptyDecl (const DeclSpec* D)
1672 /* Called after an empty type declaration (that is, a type declaration without
1673 ** a variable). Checks if the declaration does really make sense and issues a
1674 ** warning if not.
1675 */
1676 {
1677     if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1678         Warning ("Useless declaration");
1679     }
1680 }
1681
1682
1683
1684 static void SkipInitializer (unsigned BracesExpected)
1685 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1686 ** smart so we don't have too many following errors.
1687 */
1688 {
1689     while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1690         switch (CurTok.Tok) {
1691             case TOK_RCURLY:    --BracesExpected;   break;
1692             case TOK_LCURLY:    ++BracesExpected;   break;
1693             default:                                break;
1694         }
1695         NextToken ();
1696     }
1697 }
1698
1699
1700
1701 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1702 /* Accept any number of opening curly braces around an initialization, skip
1703 ** them and return the number. If the number of curly braces is less than
1704 ** BracesNeeded, issue a warning.
1705 */
1706 {
1707     unsigned BraceCount = 0;
1708     while (CurTok.Tok == TOK_LCURLY) {
1709         ++BraceCount;
1710         NextToken ();
1711     }
1712     if (BraceCount < BracesNeeded) {
1713         Error ("`{' expected");
1714     }
1715     return BraceCount;
1716 }
1717
1718
1719
1720 static void ClosingCurlyBraces (unsigned BracesExpected)
1721 /* Accept and skip the given number of closing curly braces together with
1722 ** an optional comma. Output an error messages, if the input does not contain
1723 ** the expected number of braces.
1724 */
1725 {
1726     while (BracesExpected) {
1727         if (CurTok.Tok == TOK_RCURLY) {
1728             NextToken ();
1729         } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1730             NextToken ();
1731             NextToken ();
1732         } else {
1733             Error ("`}' expected");
1734             return;
1735         }
1736         --BracesExpected;
1737     }
1738 }
1739
1740
1741
1742 static void DefineData (ExprDesc* Expr)
1743 /* Output a data definition for the given expression */
1744 {
1745     switch (ED_GetLoc (Expr)) {
1746
1747         case E_LOC_ABS:
1748             /* Absolute: numeric address or const */
1749             g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1750             break;
1751
1752         case E_LOC_GLOBAL:
1753             /* Global variable */
1754             g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1755             break;
1756
1757         case E_LOC_STATIC:
1758         case E_LOC_LITERAL:
1759             /* Static variable or literal in the literal pool */
1760             g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1761             break;
1762
1763         case E_LOC_REGISTER:
1764             /* Register variable. Taking the address is usually not
1765             ** allowed.
1766             */
1767             if (IS_Get (&AllowRegVarAddr) == 0) {
1768                 Error ("Cannot take the address of a register variable");
1769             }
1770             g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1771             break;
1772
1773         case E_LOC_STACK:
1774         case E_LOC_PRIMARY:
1775         case E_LOC_EXPR:
1776             Error ("Non constant initializer");
1777             break;
1778
1779         default:
1780             Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1781     }
1782 }
1783
1784
1785
1786 static void OutputBitFieldData (StructInitData* SI)
1787 /* Output bit field data */
1788 {
1789     /* Ignore if we have no data */
1790     if (SI->ValBits > 0) {
1791
1792         /* Output the data */
1793         g_defdata (CF_INT | CF_UNSIGNED | CF_CONST, SI->BitVal, 0);
1794
1795         /* Clear the data from SI and account for the size */
1796         SI->BitVal  = 0;
1797         SI->ValBits = 0;
1798         SI->Offs   += SIZEOF_INT;
1799     }
1800 }
1801
1802
1803
1804 static void ParseScalarInitInternal (Type* T, ExprDesc* ED)
1805 /* Parse initializaton for scalar data types. This function will not output the
1806 ** data but return it in ED.
1807 */
1808 {
1809     /* Optional opening brace */
1810     unsigned BraceCount = OpeningCurlyBraces (0);
1811
1812     /* We warn if an initializer for a scalar contains braces, because this is
1813     ** quite unusual and often a sign for some problem in the input.
1814     */
1815     if (BraceCount > 0) {
1816         Warning ("Braces around scalar initializer");
1817     }
1818
1819     /* Get the expression and convert it to the target type */
1820     ConstExpr (hie1, ED);
1821     TypeConversion (ED, T);
1822
1823     /* Close eventually opening braces */
1824     ClosingCurlyBraces (BraceCount);
1825 }
1826
1827
1828
1829 static unsigned ParseScalarInit (Type* T)
1830 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1831 {
1832     ExprDesc ED;
1833
1834     /* Parse initialization */
1835     ParseScalarInitInternal (T, &ED);
1836
1837     /* Output the data */
1838     DefineData (&ED);
1839
1840     /* Done */
1841     return SizeOf (T);
1842 }
1843
1844
1845
1846 static unsigned ParsePointerInit (Type* T)
1847 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1848 {
1849     /* Optional opening brace */
1850     unsigned BraceCount = OpeningCurlyBraces (0);
1851
1852     /* Expression */
1853     ExprDesc ED;
1854     ConstExpr (hie1, &ED);
1855     TypeConversion (&ED, T);
1856
1857     /* Output the data */
1858     DefineData (&ED);
1859
1860     /* Close eventually opening braces */
1861     ClosingCurlyBraces (BraceCount);
1862
1863     /* Done */
1864     return SIZEOF_PTR;
1865 }
1866
1867
1868
1869 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1870 /* Parse initializaton for arrays. Return the number of data bytes. */
1871 {
1872     int Count;
1873
1874     /* Get the array data */
1875     Type* ElementType    = GetElementType (T);
1876     unsigned ElementSize = CheckedSizeOf (ElementType);
1877     long ElementCount    = GetElementCount (T);
1878
1879     /* Special handling for a character array initialized by a literal */
1880     if (IsTypeChar (ElementType) &&
1881         (CurTok.Tok == TOK_SCONST || CurTok.Tok == TOK_WCSCONST ||
1882         (CurTok.Tok == TOK_LCURLY &&
1883          (NextTok.Tok == TOK_SCONST || NextTok.Tok == TOK_WCSCONST)))) {
1884
1885         /* Char array initialized by string constant */
1886         int NeedParen;
1887
1888         /* If we initializer is enclosed in brackets, remember this fact and
1889         ** skip the opening bracket.
1890         */
1891         NeedParen = (CurTok.Tok == TOK_LCURLY);
1892         if (NeedParen) {
1893             NextToken ();
1894         }
1895
1896         /* Translate into target charset */
1897         TranslateLiteral (CurTok.SVal);
1898
1899         /* If the array is one too small for the string literal, omit the
1900         ** trailing zero.
1901         */
1902         Count = GetLiteralSize (CurTok.SVal);
1903         if (ElementCount != UNSPECIFIED &&
1904             ElementCount != FLEXIBLE    &&
1905             Count        == ElementCount + 1) {
1906             /* Omit the trailing zero */
1907             --Count;
1908         }
1909
1910         /* Output the data */
1911         g_defbytes (GetLiteralStr (CurTok.SVal), Count);
1912
1913         /* Skip the string */
1914         NextToken ();
1915
1916         /* If the initializer was enclosed in curly braces, we need a closing
1917         ** one.
1918         */
1919         if (NeedParen) {
1920             ConsumeRCurly ();
1921         }
1922
1923     } else {
1924
1925         /* Curly brace */
1926         ConsumeLCurly ();
1927
1928         /* Initialize the array members */
1929         Count = 0;
1930         while (CurTok.Tok != TOK_RCURLY) {
1931             /* Flexible array members may not be initialized within
1932             ** an array (because the size of each element may differ
1933             ** otherwise).
1934             */
1935             ParseInitInternal (ElementType, 0);
1936             ++Count;
1937             if (CurTok.Tok != TOK_COMMA)
1938                 break;
1939             NextToken ();
1940         }
1941
1942         /* Closing curly braces */
1943         ConsumeRCurly ();
1944     }
1945
1946     if (ElementCount == UNSPECIFIED) {
1947         /* Number of elements determined by initializer */
1948         SetElementCount (T, Count);
1949         ElementCount = Count;
1950     } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1951         /* In non ANSI mode, allow initialization of flexible array
1952         ** members.
1953         */
1954         ElementCount = Count;
1955     } else if (Count < ElementCount) {
1956         g_zerobytes ((ElementCount - Count) * ElementSize);
1957     } else if (Count > ElementCount) {
1958         Error ("Too many initializers");
1959     }
1960     return ElementCount * ElementSize;
1961 }
1962
1963
1964
1965 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1966 /* Parse initialization of a struct or union. Return the number of data bytes. */
1967 {
1968     SymEntry*       Entry;
1969     SymTable*       Tab;
1970     StructInitData  SI;
1971
1972
1973     /* Consume the opening curly brace */
1974     ConsumeLCurly ();
1975
1976     /* Get a pointer to the struct entry from the type */
1977     Entry = GetSymEntry (T);
1978
1979     /* Get the size of the struct from the symbol table entry */
1980     SI.Size = Entry->V.S.Size;
1981
1982     /* Check if this struct definition has a field table. If it doesn't, it
1983     ** is an incomplete definition.
1984     */
1985     Tab = Entry->V.S.SymTab;
1986     if (Tab == 0) {
1987         Error ("Cannot initialize variables with incomplete type");
1988         /* Try error recovery */
1989         SkipInitializer (1);
1990         /* Nothing initialized */
1991         return 0;
1992     }
1993
1994     /* Get a pointer to the list of symbols */
1995     Entry = Tab->SymHead;
1996
1997     /* Initialize fields */
1998     SI.Offs    = 0;
1999     SI.BitVal  = 0;
2000     SI.ValBits = 0;
2001     while (CurTok.Tok != TOK_RCURLY) {
2002
2003         /* */
2004         if (Entry == 0) {
2005             Error ("Too many initializers");
2006             SkipInitializer (1);
2007             return SI.Offs;
2008         }
2009
2010         /* Parse initialization of one field. Bit-fields need a special
2011         ** handling.
2012         */
2013         if (SymIsBitField (Entry)) {
2014
2015             ExprDesc ED;
2016             unsigned Val;
2017             unsigned Shift;
2018
2019             /* Calculate the bitmask from the bit-field data */
2020             unsigned Mask = (1U << Entry->V.B.BitWidth) - 1U;
2021
2022             /* Safety ... */
2023             CHECK (Entry->V.B.Offs * CHAR_BITS + Entry->V.B.BitOffs ==
2024                    SI.Offs         * CHAR_BITS + SI.ValBits);
2025
2026             /* This may be an anonymous bit-field, in which case it doesn't
2027             ** have an initializer.
2028             */
2029             if (IsAnonName (Entry->Name)) {
2030                 /* Account for the data and output it if we have a full word */
2031                 SI.ValBits += Entry->V.B.BitWidth;
2032                 CHECK (SI.ValBits <= INT_BITS);
2033                 if (SI.ValBits == INT_BITS) {
2034                     OutputBitFieldData (&SI);
2035                 }
2036                 goto NextMember;
2037             } else {
2038                 /* Read the data, check for a constant integer, do a range
2039                 ** check.
2040                 */
2041                 ParseScalarInitInternal (type_uint, &ED);
2042                 if (!ED_IsConstAbsInt (&ED)) {
2043                     Error ("Constant initializer expected");
2044                     ED_MakeConstAbsInt (&ED, 1);
2045                 }
2046                 if (ED.IVal > (long) Mask) {
2047                     Warning ("Truncating value in bit-field initializer");
2048                     ED.IVal &= (long) Mask;
2049                 }
2050                 Val = (unsigned) ED.IVal;
2051             }
2052
2053             /* Add the value to the currently stored bit-field value */
2054             Shift = (Entry->V.B.Offs - SI.Offs) * CHAR_BITS + Entry->V.B.BitOffs;
2055             SI.BitVal |= (Val << Shift);
2056
2057             /* Account for the data and output it if we have a full word */
2058             SI.ValBits += Entry->V.B.BitWidth;
2059             CHECK (SI.ValBits <= INT_BITS);
2060             if (SI.ValBits == INT_BITS) {
2061                 OutputBitFieldData (&SI);
2062             }
2063
2064         } else {
2065
2066             /* Standard member. We should never have stuff from a
2067             ** bit-field left
2068             */
2069             CHECK (SI.ValBits == 0);
2070
2071             /* Flexible array members may only be initialized if they are
2072             ** the last field (or part of the last struct field).
2073             */
2074             SI.Offs += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
2075         }
2076
2077         /* More initializers? */
2078         if (CurTok.Tok != TOK_COMMA) {
2079             break;
2080         }
2081
2082         /* Skip the comma */
2083         NextToken ();
2084
2085 NextMember:
2086         /* Next member. For unions, only the first one can be initialized */
2087         if (IsTypeUnion (T)) {
2088             /* Union */
2089             Entry = 0;
2090         } else {
2091             /* Struct */
2092             Entry = Entry->NextSym;
2093         }
2094     }
2095
2096     /* Consume the closing curly brace */
2097     ConsumeRCurly ();
2098
2099     /* If we have data from a bit-field left, output it now */
2100     OutputBitFieldData (&SI);
2101
2102     /* If there are struct fields left, reserve additional storage */
2103     if (SI.Offs < SI.Size) {
2104         g_zerobytes (SI.Size - SI.Offs);
2105         SI.Offs = SI.Size;
2106     }
2107
2108     /* Return the actual number of bytes initialized. This number may be
2109     ** larger than sizeof (Struct) if flexible array members are present and
2110     ** were initialized (possible in non ANSI mode).
2111     */
2112     return SI.Offs;
2113 }
2114
2115
2116
2117 static unsigned ParseVoidInit (void)
2118 /* Parse an initialization of a void variable (special cc65 extension).
2119 ** Return the number of bytes initialized.
2120 */
2121 {
2122     ExprDesc Expr;
2123     unsigned Size;
2124
2125     /* Opening brace */
2126     ConsumeLCurly ();
2127
2128     /* Allow an arbitrary list of values */
2129     Size = 0;
2130     do {
2131         ConstExpr (hie1, &Expr);
2132         switch (UnqualifiedType (Expr.Type[0].C)) {
2133
2134             case T_SCHAR:
2135             case T_UCHAR:
2136                 if (ED_IsConstAbsInt (&Expr)) {
2137                     /* Make it byte sized */
2138                     Expr.IVal &= 0xFF;
2139                 }
2140                 DefineData (&Expr);
2141                 Size += SIZEOF_CHAR;
2142                 break;
2143
2144             case T_SHORT:
2145             case T_USHORT:
2146             case T_INT:
2147             case T_UINT:
2148             case T_PTR:
2149             case T_ARRAY:
2150                 if (ED_IsConstAbsInt (&Expr)) {
2151                     /* Make it word sized */
2152                     Expr.IVal &= 0xFFFF;
2153                 }
2154                 DefineData (&Expr);
2155                 Size += SIZEOF_INT;
2156                 break;
2157
2158             case T_LONG:
2159             case T_ULONG:
2160                 if (ED_IsConstAbsInt (&Expr)) {
2161                     /* Make it dword sized */
2162                     Expr.IVal &= 0xFFFFFFFF;
2163                 }
2164                 DefineData (&Expr);
2165                 Size += SIZEOF_LONG;
2166                 break;
2167
2168             default:
2169                 Error ("Illegal type in initialization");
2170                 break;
2171
2172         }
2173
2174         if (CurTok.Tok != TOK_COMMA) {
2175             break;
2176         }
2177         NextToken ();
2178
2179     } while (CurTok.Tok != TOK_RCURLY);
2180
2181     /* Closing brace */
2182     ConsumeRCurly ();
2183
2184     /* Return the number of bytes initialized */
2185     return Size;
2186 }
2187
2188
2189
2190 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
2191 /* Parse initialization of variables. Return the number of data bytes. */
2192 {
2193     switch (UnqualifiedType (T->C)) {
2194
2195         case T_SCHAR:
2196         case T_UCHAR:
2197         case T_SHORT:
2198         case T_USHORT:
2199         case T_INT:
2200         case T_UINT:
2201         case T_LONG:
2202         case T_ULONG:
2203         case T_FLOAT:
2204         case T_DOUBLE:
2205             return ParseScalarInit (T);
2206
2207         case T_PTR:
2208             return ParsePointerInit (T);
2209
2210         case T_ARRAY:
2211             return ParseArrayInit (T, AllowFlexibleMembers);
2212
2213         case T_STRUCT:
2214         case T_UNION:
2215             return ParseStructInit (T, AllowFlexibleMembers);
2216
2217         case T_VOID:
2218             if (IS_Get (&Standard) == STD_CC65) {
2219                 /* Special cc65 extension in non ANSI mode */
2220                 return ParseVoidInit ();
2221             }
2222             /* FALLTHROUGH */
2223
2224         default:
2225             Error ("Illegal type");
2226             return SIZEOF_CHAR;
2227
2228     }
2229 }
2230
2231
2232
2233 unsigned ParseInit (Type* T)
2234 /* Parse initialization of variables. Return the number of data bytes. */
2235 {
2236     /* Parse the initialization. Flexible array members can only be initialized
2237     ** in cc65 mode.
2238     */
2239     unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
2240
2241     /* The initialization may not generate code on global level, because code
2242     ** outside function scope will never get executed.
2243     */
2244     if (HaveGlobalCode ()) {
2245         Error ("Non constant initializers");
2246         RemoveGlobalCode ();
2247     }
2248
2249     /* Return the size needed for the initialization */
2250     return Size;
2251 }