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