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