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