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