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