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