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