]> git.sur5r.net Git - cc65/blob - src/cc65/declare.c
c15cc53a3e12f0547d740cf39cd1fac6cfb22595
[cc65] / src / cc65 / declare.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 declare.c                                 */
4 /*                                                                           */
5 /*                 Parse variable and function declarations                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2005 Ullrich von Bassewitz                                       */
10 /*               Römerstraße 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 /*                                 Forwards                                  */
67 /*****************************************************************************/
68
69
70
71 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers);
72 /* Parse a type specificier */
73
74 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers);
75 /* Parse initialization of variables. Return the number of data bytes. */
76
77
78
79 /*****************************************************************************/
80 /*                            internal functions                             */
81 /*****************************************************************************/
82
83
84
85 static TypeCode OptionalQualifiers (TypeCode Q)
86 /* Read type qualifiers if we have any */
87 {
88     while (TokIsTypeQual (&CurTok)) {
89
90         switch (CurTok.Tok) {
91
92             case TOK_CONST:
93                 if (Q & T_QUAL_CONST) {
94                     Error ("Duplicate qualifier: `const'");
95                 }
96                 Q |= T_QUAL_CONST;
97                 break;
98
99             case TOK_VOLATILE:
100                 if (Q & T_QUAL_VOLATILE) {
101                     Error ("Duplicate qualifier: `volatile'");
102                 }
103                 Q |= T_QUAL_VOLATILE;
104                 break;
105
106             case TOK_RESTRICT:
107                 if (Q & T_QUAL_RESTRICT) {
108                     Error ("Duplicate qualifier: `restrict'");
109                 }
110                 Q |= T_QUAL_RESTRICT;
111                 break;
112
113             default:
114                 Internal ("Unexpected type qualifier token: %d", CurTok.Tok);
115
116         }
117
118         /* Skip the token */
119         NextToken ();
120     }
121
122     /* Return the qualifiers read */
123     return Q;
124 }
125
126
127
128 static void OptionalInt (void)
129 /* Eat an optional "int" token */
130 {
131     if (CurTok.Tok == TOK_INT) {
132         /* Skip it */
133         NextToken ();
134     }
135 }
136
137
138
139 static void OptionalSigned (void)
140 /* Eat an optional "signed" token */
141 {
142     if (CurTok.Tok == TOK_SIGNED) {
143         /* Skip it */
144         NextToken ();
145     }
146 }
147
148
149
150 static void InitDeclSpec (DeclSpec* D)
151 /* Initialize the DeclSpec struct for use */
152 {
153     D->StorageClass     = 0;
154     D->Type[0].C        = T_END;
155     D->Flags            = 0;
156 }
157
158
159
160 static void InitDeclaration (Declaration* D)
161 /* Initialize the Declaration struct for use */
162 {
163     D->Ident[0]  = '\0';
164     D->Type[0].C = T_END;
165     D->Index     = 0;
166 }
167
168
169
170 static void NeedTypeSpace (Declaration* D, unsigned Count)
171 /* Check if there is enough space for Count type specifiers within D */
172 {
173     if (D->Index + Count >= MAXTYPELEN) {
174         /* We must call Fatal() here, since calling Error() will try to
175          * continue, and the declaration type is not correctly terminated
176          * in case we come here.
177          */
178         Fatal ("Too many type specifiers");
179     }
180 }
181
182
183
184 static void AddTypeToDeclaration (Declaration* D, TypeCode T)
185 /* Add a type specifier to the type of a declaration */
186 {
187     NeedTypeSpace (D, 1);
188     D->Type[D->Index++].C = T;
189 }
190
191
192
193 static void AddFuncTypeToDeclaration (Declaration* D, FuncDesc* F)
194 /* Add a function type plus function descriptor to the type of a declaration */
195 {
196     NeedTypeSpace (D, 1);
197     D->Type[D->Index].C = T_FUNC;
198     SetFuncDesc (D->Type + D->Index, F);
199     ++D->Index;
200 }
201
202
203
204 static void AddArrayToDeclaration (Declaration* D, long Size)
205 /* Add an array type plus size to the type of a declaration */
206 {
207     NeedTypeSpace (D, 1);
208     D->Type[D->Index].C = T_ARRAY;
209     D->Type[D->Index].A.L = Size;
210     ++D->Index;
211 }
212
213
214
215 static void FixArrayQualifiers (Type* T)
216 /* Using typedefs, it is possible to generate declarations that have
217  * type qualifiers attached to an array, not the element type. Go and
218  * fix these here.
219  */
220 {
221     TypeCode Q = T_QUAL_NONE;
222     while (T->C != T_END) {
223         if (IsTypeArray (T)) {
224             /* Extract any type qualifiers */
225             Q |= T->C & T_MASK_QUAL;
226             T->C = UnqualifiedType (T->C);
227         } else {
228             /* Add extracted type qualifiers here */
229             T->C |= Q;
230             Q = T_QUAL_NONE;
231         }
232         ++T;
233     }
234
235     /* Q must be empty now */
236     CHECK (Q == T_QUAL_NONE);
237 }
238
239
240
241 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
242 /* Parse a storage class */
243 {
244     /* Assume we're using an explicit storage class */
245     D->Flags &= ~DS_DEF_STORAGE;
246
247     /* Check the storage class given */
248     switch (CurTok.Tok) {
249
250         case TOK_EXTERN:
251             D->StorageClass = SC_EXTERN | SC_STATIC;
252             NextToken ();
253             break;
254
255         case TOK_STATIC:
256             D->StorageClass = SC_STATIC;
257             NextToken ();
258             break;
259
260         case TOK_REGISTER:
261             D->StorageClass = SC_REGISTER | SC_STATIC;
262             NextToken ();
263             break;
264
265         case TOK_AUTO:
266             D->StorageClass = SC_AUTO;
267             NextToken ();
268             break;
269
270         case TOK_TYPEDEF:
271             D->StorageClass = SC_TYPEDEF;
272             NextToken ();
273             break;
274
275         default:
276             /* No storage class given, use default */
277             D->Flags |= DS_DEF_STORAGE;
278             D->StorageClass = DefStorage;
279             break;
280     }
281 }
282
283
284
285 static void ParseEnumDecl (void)
286 /* Process an enum declaration . */
287 {
288     int EnumVal;
289     ident Ident;
290
291     /* Accept forward definitions */
292     if (CurTok.Tok != TOK_LCURLY) {
293         return;
294     }
295
296     /* Skip the opening curly brace */
297     NextToken ();
298
299     /* Read the enum tags */
300     EnumVal = 0;
301     while (CurTok.Tok != TOK_RCURLY) {
302
303         /* We expect an identifier */
304         if (CurTok.Tok != TOK_IDENT) {
305             Error ("Identifier expected");
306             continue;
307         }
308
309         /* Remember the identifier and skip it */
310         strcpy (Ident, CurTok.Ident);
311         NextToken ();
312
313         /* Check for an assigned value */
314         if (CurTok.Tok == TOK_ASSIGN) {
315             ExprDesc Expr;
316             NextToken ();
317             ConstAbsIntExpr (hie1, &Expr);
318             EnumVal = Expr.IVal;
319         }
320
321         /* Add an entry to the symbol table */
322         AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
323
324         /* Check for end of definition */
325         if (CurTok.Tok != TOK_COMMA)
326             break;
327         NextToken ();
328     }
329     ConsumeRCurly ();
330 }
331
332
333
334 static SymEntry* ParseStructDecl (const char* Name, TypeCode StructType)
335 /* Parse a struct/union declaration. */
336 {
337
338     unsigned  StructSize;
339     unsigned  FieldSize;
340     unsigned  Offs;
341     int       FlexibleMember;
342     SymTable* FieldTab;
343     SymEntry* Entry;
344
345
346     if (CurTok.Tok != TOK_LCURLY) {
347         /* Just a forward declaration. Try to find a struct with the given
348          * name. If there is none, insert a forward declaration into the
349          * current lexical level.
350          */
351         Entry = FindTagSym (Name);
352         if (Entry == 0) {
353             Entry = AddStructSym (Name, 0, 0);
354         } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
355             /* Already defined in the level but no struct */
356             Error ("Symbol `%s' is already different kind", Name);
357         }
358         return Entry;
359     }
360
361     /* Add a forward declaration for the struct in the current lexical level */
362     Entry = AddStructSym (Name, 0, 0);
363
364     /* Skip the curly brace */
365     NextToken ();
366
367     /* Enter a new lexical level for the struct */
368     EnterStructLevel ();
369
370     /* Parse struct fields */
371     FlexibleMember = 0;
372     StructSize     = 0;
373     while (CurTok.Tok != TOK_RCURLY) {
374
375         /* Get the type of the entry */
376         DeclSpec Spec;
377         InitDeclSpec (&Spec);
378         ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
379
380         /* Read fields with this type */
381         while (1) {
382
383             Declaration Decl;
384
385             /* If we had a flexible array member before, no other fields can
386              * follow.
387              */
388             if (FlexibleMember) {
389                 Error ("Flexible array member must be last field");
390                 FlexibleMember = 0;     /* Avoid further errors */
391             }
392
393             /* Get type and name of the struct field */
394             ParseDecl (&Spec, &Decl, 0);
395
396             /* Get the offset of this field */
397             Offs = (StructType == T_STRUCT)? StructSize : 0;
398
399             /* Calculate the sizes, handle flexible array members */
400             if (StructType == T_STRUCT) {
401
402                 /* It's a struct. Check if this field is a flexible array
403                  * member, and calculate the size of the field.
404                  */
405                 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
406                     /* Array with unspecified size */
407                     if (StructSize == 0) {
408                         Error ("Flexible array member cannot be first struct field");
409                     }
410                     FlexibleMember = 1;
411                     /* Assume zero for size calculations */
412                     SetElementCount (Decl.Type, FLEXIBLE);
413                 } else {
414                     StructSize += CheckedSizeOf (Decl.Type);
415                 }
416
417             } else {
418
419                 /* It's a union */
420                 FieldSize = CheckedSizeOf (Decl.Type);
421                 if (FieldSize > StructSize) {
422                     StructSize = FieldSize;
423                 }
424             }
425
426             /* Add a field entry to the table */
427             AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
428
429             if (CurTok.Tok != TOK_COMMA) {
430                 break;
431             }
432             NextToken ();
433         }
434         ConsumeSemi ();
435     }
436
437     /* Skip the closing brace */
438     NextToken ();
439
440     /* Remember the symbol table and leave the struct level */
441     FieldTab = GetSymTab ();
442     LeaveStructLevel ();
443
444     /* Make a real entry from the forward decl and return it */
445     return AddStructSym (Name, StructSize, FieldTab);
446 }
447
448
449
450 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
451 /* Parse a type specificier */
452 {
453     ident       Ident;
454     SymEntry*   Entry;
455     TypeCode    StructType;
456
457     /* Assume we have an explicit type */
458     D->Flags &= ~DS_DEF_TYPE;
459
460     /* Read type qualifiers if we have any */
461     Qualifiers = OptionalQualifiers (Qualifiers);
462
463     /* Look at the data type */
464     switch (CurTok.Tok) {
465
466         case TOK_VOID:
467             NextToken ();
468             D->Type[0].C = T_VOID;
469             D->Type[1].C = T_END;
470             break;
471
472         case TOK_CHAR:
473             NextToken ();
474             D->Type[0].C = GetDefaultChar();
475             D->Type[1].C = T_END;
476             break;
477
478         case TOK_LONG:
479             NextToken ();
480             if (CurTok.Tok == TOK_UNSIGNED) {
481                 NextToken ();
482                 OptionalInt ();
483                 D->Type[0].C = T_ULONG;
484                 D->Type[1].C = T_END;
485             } else {
486                 OptionalSigned ();
487                 OptionalInt ();
488                 D->Type[0].C = T_LONG;
489                 D->Type[1].C = T_END;
490             }
491             break;
492
493         case TOK_SHORT:
494             NextToken ();
495             if (CurTok.Tok == TOK_UNSIGNED) {
496                 NextToken ();
497                 OptionalInt ();
498                 D->Type[0].C = T_USHORT;
499                 D->Type[1].C = T_END;
500             } else {
501                 OptionalSigned ();
502                 OptionalInt ();
503                 D->Type[0].C = T_SHORT;
504                 D->Type[1].C = T_END;
505             }
506             break;
507
508         case TOK_INT:
509             NextToken ();
510             D->Type[0].C = T_INT;
511             D->Type[1].C = T_END;
512             break;
513
514        case TOK_SIGNED:
515             NextToken ();
516             switch (CurTok.Tok) {
517
518                 case TOK_CHAR:
519                     NextToken ();
520                     D->Type[0].C = T_SCHAR;
521                     D->Type[1].C = T_END;
522                     break;
523
524                 case TOK_SHORT:
525                     NextToken ();
526                     OptionalInt ();
527                     D->Type[0].C = T_SHORT;
528                     D->Type[1].C = T_END;
529                     break;
530
531                 case TOK_LONG:
532                     NextToken ();
533                     OptionalInt ();
534                     D->Type[0].C = T_LONG;
535                     D->Type[1].C = T_END;
536                     break;
537
538                 case TOK_INT:
539                     NextToken ();
540                     /* FALL THROUGH */
541
542                 default:
543                     D->Type[0].C = T_INT;
544                     D->Type[1].C = T_END;
545                     break;
546             }
547             break;
548
549         case TOK_UNSIGNED:
550             NextToken ();
551             switch (CurTok.Tok) {
552
553                 case TOK_CHAR:
554                     NextToken ();
555                     D->Type[0].C = T_UCHAR;
556                     D->Type[1].C = T_END;
557                     break;
558
559                 case TOK_SHORT:
560                     NextToken ();
561                     OptionalInt ();
562                     D->Type[0].C = T_USHORT;
563                     D->Type[1].C = T_END;
564                     break;
565
566                 case TOK_LONG:
567                     NextToken ();
568                     OptionalInt ();
569                     D->Type[0].C = T_ULONG;
570                     D->Type[1].C = T_END;
571                     break;
572
573                 case TOK_INT:
574                     NextToken ();
575                     /* FALL THROUGH */
576
577                 default:
578                     D->Type[0].C = T_UINT;
579                     D->Type[1].C = T_END;
580                     break;
581             }
582             break;
583
584         case TOK_FLOAT:
585             NextToken ();
586             D->Type[0].C = T_FLOAT;
587             D->Type[1].C = T_END;
588             break;
589
590         case TOK_DOUBLE:
591             NextToken ();
592             D->Type[0].C = T_DOUBLE;
593             D->Type[1].C = T_END;
594             break;
595
596         case TOK_STRUCT:
597         case TOK_UNION:
598             StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
599             NextToken ();
600             /* */
601             if (CurTok.Tok == TOK_IDENT) {
602                 strcpy (Ident, CurTok.Ident);
603                 NextToken ();
604             } else {
605                 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
606             }
607             /* Remember we have an extra type decl */
608             D->Flags |= DS_EXTRA_TYPE;
609             /* Declare the struct in the current scope */
610             Entry = ParseStructDecl (Ident, StructType);
611             /* Encode the struct entry into the type */
612             D->Type[0].C = StructType;
613             SetSymEntry (D->Type, Entry);
614             D->Type[1].C = T_END;
615             break;
616
617         case TOK_ENUM:
618             NextToken ();
619             if (CurTok.Tok != TOK_LCURLY) {
620                 /* Named enum */
621                 if (CurTok.Tok == TOK_IDENT) {
622                     /* Find an entry with this name */
623                     Entry = FindTagSym (CurTok.Ident);
624                     if (Entry) {
625                         if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
626                             Error ("Symbol `%s' is already different kind", Entry->Name);
627                         }
628                     } else {
629                         /* Insert entry into table ### */
630                     }
631                     /* Skip the identifier */
632                     NextToken ();
633                 } else {
634                     Error ("Identifier expected");
635                 }
636             }
637             /* Remember we have an extra type decl */
638             D->Flags |= DS_EXTRA_TYPE;
639             /* Parse the enum decl */
640             ParseEnumDecl ();
641             D->Type[0].C = T_INT;
642             D->Type[1].C = T_END;
643             break;
644
645         case TOK_IDENT:
646             Entry = FindSym (CurTok.Ident);
647             if (Entry && SymIsTypeDef (Entry)) {
648                 /* It's a typedef */
649                 NextToken ();
650                 TypeCpy (D->Type, Entry->Type);
651                 break;
652             }
653             /* FALL THROUGH */
654
655         default:
656             if (Default < 0) {
657                 Error ("Type expected");
658                 D->Type[0].C = T_INT;
659                 D->Type[1].C = T_END;
660             } else {
661                 D->Flags |= DS_DEF_TYPE;
662                 D->Type[0].C = (TypeCode) Default;
663                 D->Type[1].C = T_END;
664             }
665             break;
666     }
667
668     /* There may also be qualifiers *after* the initial type */
669     D->Type[0].C |= OptionalQualifiers (Qualifiers);
670 }
671
672
673
674 static Type* ParamTypeCvt (Type* T)
675 /* If T is an array, convert it to a pointer else do nothing. Return the
676  * resulting type.
677  */
678 {
679     if (IsTypeArray (T)) {
680         T->C = T_PTR;
681     }
682     return T;
683 }
684
685
686
687 static void ParseOldStyleParamList (FuncDesc* F)
688 /* Parse an old style (K&R) parameter list */
689 {
690     /* Parse params */
691     while (CurTok.Tok != TOK_RPAREN) {
692
693         /* List of identifiers expected */
694         if (CurTok.Tok != TOK_IDENT) {
695             Error ("Identifier expected");
696         }
697
698         /* Create a symbol table entry with type int */
699         AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF, 0);
700
701         /* Count arguments */
702         ++F->ParamCount;
703
704         /* Skip the identifier */
705         NextToken ();
706
707         /* Check for more parameters */
708         if (CurTok.Tok == TOK_COMMA) {
709             NextToken ();
710         } else {
711             break;
712         }
713     }
714
715     /* Skip right paren. We must explicitly check for one here, since some of
716      * the breaks above bail out without checking.
717      */
718     ConsumeRParen ();
719
720     /* An optional list of type specifications follows */
721     while (CurTok.Tok != TOK_LCURLY) {
722
723         DeclSpec        Spec;
724
725         /* Read the declaration specifier */
726         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
727
728         /* We accept only auto and register as storage class specifiers, but
729          * we ignore all this, since we use auto anyway.
730          */
731         if ((Spec.StorageClass & SC_AUTO) == 0 &&
732             (Spec.StorageClass & SC_REGISTER) == 0) {
733             Error ("Illegal storage class");
734         }
735
736         /* Parse a comma separated variable list */
737         while (1) {
738
739             Declaration         Decl;
740
741             /* Read the parameter */
742             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
743             if (Decl.Ident[0] != '\0') {
744
745                 /* We have a name given. Search for the symbol */
746                 SymEntry* Sym = FindLocalSym (Decl.Ident);
747                 if (Sym) {
748                     /* Found it, change the default type to the one given */
749                     ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
750                 } else {
751                     Error ("Unknown identifier: `%s'", Decl.Ident);
752                 }
753             }
754
755             if (CurTok.Tok == TOK_COMMA) {
756                 NextToken ();
757             } else {
758                 break;
759             }
760
761         }
762
763         /* Variable list must be semicolon terminated */
764         ConsumeSemi ();
765     }
766 }
767
768
769
770 static void ParseAnsiParamList (FuncDesc* F)
771 /* Parse a new style (ANSI) parameter list */
772 {
773     /* Parse params */
774     while (CurTok.Tok != TOK_RPAREN) {
775
776         DeclSpec        Spec;
777         Declaration     Decl;
778         DeclAttr        Attr;
779
780         /* Allow an ellipsis as last parameter */
781         if (CurTok.Tok == TOK_ELLIPSIS) {
782             NextToken ();
783             F->Flags |= FD_VARIADIC;
784             break;
785         }
786
787         /* Read the declaration specifier */
788         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
789
790         /* We accept only auto and register as storage class specifiers */
791         if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
792             Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
793         } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
794             Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
795         } else {
796             Error ("Illegal storage class");
797             Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
798         }
799
800         /* Allow parameters without a name, but remember if we had some to
801          * eventually print an error message later.
802          */
803         ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
804         if (Decl.Ident[0] == '\0') {
805
806             /* Unnamed symbol. Generate a name that is not user accessible,
807              * then handle the symbol normal.
808              */
809             AnonName (Decl.Ident, "param");
810             F->Flags |= FD_UNNAMED_PARAMS;
811
812             /* Clear defined bit on nonames */
813             Spec.StorageClass &= ~SC_DEF;
814         }
815
816         /* Parse an attribute ### */
817         ParseAttribute (&Decl, &Attr);
818
819         /* Create a symbol table entry */
820         AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Spec.StorageClass, 0);
821
822         /* Count arguments */
823         ++F->ParamCount;
824
825         /* Check for more parameters */
826         if (CurTok.Tok == TOK_COMMA) {
827             NextToken ();
828         } else {
829             break;
830         }
831     }
832
833     /* Skip right paren. We must explicitly check for one here, since some of
834      * the breaks above bail out without checking.
835      */
836     ConsumeRParen ();
837
838     /* Check if this is a function definition */
839     if (CurTok.Tok == TOK_LCURLY) {
840         /* Print an error if we have unnamed parameters and cc65 extensions
841          * are disabled.
842          */
843         if (IS_Get (&Standard) != STD_CC65 &&
844             (F->Flags & FD_UNNAMED_PARAMS) != 0) {
845             Error ("Parameter name omitted");
846         }
847     }
848 }
849
850
851
852 static FuncDesc* ParseFuncDecl (void)
853 /* Parse the argument list of a function. */
854 {
855     unsigned Offs;
856     SymEntry* Sym;
857
858     /* Create a new function descriptor */
859     FuncDesc* F = NewFuncDesc ();
860
861     /* Enter a new lexical level */
862     EnterFunctionLevel ();
863
864     /* Check for several special parameter lists */
865     if (CurTok.Tok == TOK_RPAREN) {
866         /* Parameter list is empty */
867         F->Flags |= (FD_EMPTY | FD_VARIADIC);
868     } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
869         /* Parameter list declared as void */
870         NextToken ();
871         F->Flags |= FD_VOID_PARAM;
872     } else if (CurTok.Tok == TOK_IDENT &&
873                (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
874         /* If the identifier is a typedef, we have a new style parameter list,
875          * if it's some other identifier, it's an old style parameter list.
876          */
877         Sym = FindSym (CurTok.Ident);
878         if (Sym == 0 || !SymIsTypeDef (Sym)) {
879             /* Old style (K&R) function. */
880             F->Flags |= FD_OLDSTYLE;
881         }
882     }
883
884     /* Parse params */
885     if ((F->Flags & FD_OLDSTYLE) == 0) {
886         /* New style function */
887         ParseAnsiParamList (F);
888     } else {
889         /* Old style function */
890         ParseOldStyleParamList (F);
891     }
892
893     /* Remember the last function parameter. We need it later for several
894      * purposes, for example when passing stuff to fastcall functions. Since
895      * more symbols are added to the table, it is easier if we remember it
896      * now, since it is currently the last entry in the symbol table.
897      */
898     F->LastParam = GetSymTab()->SymTail;
899
900     /* Assign offsets. If the function has a variable parameter list,
901      * there's one additional byte (the arg size).
902      */
903     Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
904     Sym = F->LastParam;
905     while (Sym) {
906         unsigned Size = CheckedSizeOf (Sym->Type);
907         if (SymIsRegVar (Sym)) {
908             Sym->V.R.SaveOffs = Offs;
909         } else {
910             Sym->V.Offs = Offs;
911         }
912         Offs += Size;
913         F->ParamSize += Size;
914         Sym = Sym->PrevSym;
915     }
916
917     /* Add the default address size for the function */
918     if (CodeAddrSize == ADDR_SIZE_FAR) {
919         F->Flags |= FD_FAR;
920     } else {
921         F->Flags |= FD_NEAR;
922     }
923
924     /* Leave the lexical level remembering the symbol tables */
925     RememberFunctionLevel (F);
926
927     /* Return the function descriptor */
928     return F;
929 }
930
931
932
933 static unsigned FunctionModifierFlags (void)
934 /* Parse __fastcall__, __near__ and __far__ and return the matching FD_ flags */
935 {
936     /* Read the flags */
937     unsigned Flags = FD_NONE;
938     while (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
939
940         /* Get the flag bit for the next token */
941         unsigned F = FD_NONE;
942         switch (CurTok.Tok) {
943             case TOK_FASTCALL:  F = FD_FASTCALL; break;
944             case TOK_NEAR:      F = FD_NEAR;     break;
945             case TOK_FAR:       F = FD_FAR;      break;
946             default:            Internal ("Unexpected token: %d", CurTok.Tok);
947         }
948
949         /* Remember the flag for this modifier */
950         if (Flags & F) {
951             Error ("Duplicate modifier");
952         }
953         Flags |= F;
954
955         /* Skip the token */
956         NextToken ();
957     }
958
959     /* Sanity check */
960     if ((Flags & (FD_NEAR | FD_FAR)) == (FD_NEAR | FD_FAR)) {
961         Error ("Cannot specify both, `__near__' and `__far__' modifiers");
962         Flags &= ~(FD_NEAR | FD_FAR);
963     }
964
965     /* Return the flags read */
966     return Flags;
967 }
968
969
970
971 static void ApplyFunctionModifiers (Type* T, unsigned Flags)
972 /* Apply a set of function modifier flags to a function */
973 {
974     /* Get the function descriptor */
975     FuncDesc* F = GetFuncDesc (T);
976
977     /* Special check for __fastcall__ */
978     if ((Flags & FD_FASTCALL) != 0 && IsVariadicFunc (T)) {
979         Error ("Cannot apply `__fastcall__' to functions with "
980                "variable parameter list");
981         Flags &= ~FD_FASTCALL;
982     }
983
984     /* Remove the default function address size modifiers */
985     F->Flags &= ~(FD_NEAR | FD_FAR);
986
987     /* Add the new modifers */
988     F->Flags |= Flags;
989 }
990
991
992
993 static void Decl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
994 /* Recursively process declarators. Build a type array in reverse order. */
995 {
996     /* Pointer to something */
997     if (CurTok.Tok == TOK_STAR) {
998
999         TypeCode C;
1000
1001         /* Skip the star */
1002         NextToken ();
1003
1004         /* Allow optional const or volatile qualifiers */
1005         C = T_PTR | OptionalQualifiers (T_QUAL_NONE);
1006
1007         /* Parse the type, the pointer points to */
1008         Decl (Spec, D, Mode);
1009
1010         /* Add the type */
1011         AddTypeToDeclaration (D, C);
1012         return;
1013     }
1014
1015     /* Function modifiers */
1016     if (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
1017
1018         /* Remember the current type pointer */
1019         Type* T = D->Type + D->Index;
1020
1021         /* Read the flags */
1022         unsigned Flags = FunctionModifierFlags ();
1023
1024         /* Parse the function */
1025         Decl (Spec, D, Mode);
1026
1027         /* Check that we have a function */
1028         if (!IsTypeFunc (T) && !IsTypeFuncPtr (T)) {
1029             Error ("Function modifier applied to non function");
1030         } else {
1031             ApplyFunctionModifiers (T, Flags);
1032         }
1033
1034         /* Done */
1035         return;
1036     }
1037
1038     if (CurTok.Tok == TOK_LPAREN) {
1039         NextToken ();
1040         Decl (Spec, D, Mode);
1041         ConsumeRParen ();
1042     } else {
1043         /* Things depend on Mode now:
1044          *  - Mode == DM_NEED_IDENT means:
1045          *      we *must* have a type and a variable identifer.
1046          *  - Mode == DM_NO_IDENT means:
1047          *      we must have a type but no variable identifer
1048          *      (if there is one, it's not read).
1049          *  - Mode == DM_ACCEPT_IDENT means:
1050          *      we *may* have an identifier. If there is an identifier,
1051          *      it is read, but it is no error, if there is none.
1052          */
1053         if (Mode == DM_NO_IDENT) {
1054             D->Ident[0] = '\0';
1055         } else if (CurTok.Tok == TOK_IDENT) {
1056             strcpy (D->Ident, CurTok.Ident);
1057             NextToken ();
1058         } else {
1059             if (Mode == DM_NEED_IDENT) {
1060                 Error ("Identifier expected");
1061             }
1062             D->Ident[0] = '\0';
1063         }
1064     }
1065
1066     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1067         if (CurTok.Tok == TOK_LPAREN) {
1068
1069             /* Function declaration */
1070             FuncDesc* F;
1071             NextToken ();
1072
1073             /* Parse the function declaration */
1074             F = ParseFuncDecl ();
1075
1076             /* Add the function type. Be sure to bounds check the type buffer */
1077             AddFuncTypeToDeclaration (D, F);
1078         } else {
1079             /* Array declaration */
1080             long Size = UNSPECIFIED;
1081             NextToken ();
1082             /* Read the size if it is given */
1083             if (CurTok.Tok != TOK_RBRACK) {
1084                 ExprDesc Expr;
1085                 ConstAbsIntExpr (hie1, &Expr);
1086                 if (Expr.IVal <= 0) {
1087                     if (D->Ident[0] != '\0') {
1088                         Error ("Size of array `%s' is invalid", D->Ident);
1089                     } else {
1090                         Error ("Size of array is invalid");
1091                     }
1092                     Expr.IVal = 1;
1093                 }
1094                 Size = Expr.IVal;
1095             }
1096             ConsumeRBrack ();
1097
1098             /* Add the array type with the size */
1099             AddArrayToDeclaration (D, Size);
1100         }
1101     }
1102 }
1103
1104
1105
1106 /*****************************************************************************/
1107 /*                                   code                                    */
1108 /*****************************************************************************/
1109
1110
1111
1112 Type* ParseType (Type* T)
1113 /* Parse a complete type specification */
1114 {
1115     DeclSpec Spec;
1116     Declaration Decl;
1117
1118     /* Get a type without a default */
1119     InitDeclSpec (&Spec);
1120     ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1121
1122     /* Parse additional declarators */
1123     ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1124
1125     /* Copy the type to the target buffer */
1126     TypeCpy (T, Decl.Type);
1127
1128     /* Return a pointer to the target buffer */
1129     return T;
1130 }
1131
1132
1133
1134 void ParseDecl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
1135 /* Parse a variable, type or function declaration */
1136 {
1137     /* Initialize the Declaration struct */
1138     InitDeclaration (D);
1139
1140     /* Get additional declarators and the identifier */
1141     Decl (Spec, D, Mode);
1142
1143     /* Add the base type. */
1144     NeedTypeSpace (D, TypeLen (Spec->Type) + 1);        /* Bounds check */
1145     TypeCpy (D->Type + D->Index, Spec->Type);
1146
1147     /* Fix any type qualifiers attached to an array type */
1148     FixArrayQualifiers (D->Type);
1149
1150     /* Check several things for function or function pointer types */
1151     if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1152
1153         /* A function. Check the return type */
1154         Type* RetType = GetFuncReturn (D->Type);
1155
1156         /* Functions may not return functions or arrays */
1157         if (IsTypeFunc (RetType)) {
1158             Error ("Functions are not allowed to return functions");
1159         } else if (IsTypeArray (RetType)) {
1160             Error ("Functions are not allowed to return arrays");
1161         }
1162
1163         /* The return type must not be qualified */
1164         if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1165
1166             if (GetType (RetType) == T_TYPE_VOID) {
1167                 /* A qualified void type is always an error */
1168                 Error ("function definition has qualified void return type");
1169             } else {
1170                 /* For others, qualifiers are ignored */
1171                 Warning ("type qualifiers ignored on function return type");
1172                 RetType[0].C = UnqualifiedType (RetType[0].C);
1173             }
1174         }
1175
1176         /* Warn about an implicit int return in the function */
1177         if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1178             RetType[0].C == T_INT && RetType[1].C == T_END) {
1179             /* Function has an implicit int return. Output a warning if we don't
1180              * have the C89 standard enabled explicitly.
1181              */
1182             if (IS_Get (&Standard) >= STD_C99) {
1183                 Warning ("Implicit `int' return type is an obsolete feature");
1184             }
1185             GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1186         }
1187
1188     }
1189
1190     /* Check the size of the generated type */
1191     if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1192         unsigned Size = SizeOf (D->Type);
1193         if (Size >= 0x10000) {
1194             if (D->Ident[0] != '\0') {
1195                 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1196             } else {
1197                 Error ("Invalid size in declaration (0x%06X)", Size);
1198             }
1199         }
1200     }
1201
1202 }
1203
1204
1205
1206 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1207 /* Parse a declaration specification */
1208 {
1209     TypeCode Qualifiers;
1210
1211     /* Initialize the DeclSpec struct */
1212     InitDeclSpec (D);
1213
1214     /* There may be qualifiers *before* the storage class specifier */
1215     Qualifiers = OptionalQualifiers (T_QUAL_NONE);
1216
1217     /* Now get the storage class specifier for this declaration */
1218     ParseStorageClass (D, DefStorage);
1219
1220     /* Parse the type specifiers passing any initial type qualifiers */
1221     ParseTypeSpec (D, DefType, Qualifiers);
1222 }
1223
1224
1225
1226 void CheckEmptyDecl (const DeclSpec* D)
1227 /* Called after an empty type declaration (that is, a type declaration without
1228  * a variable). Checks if the declaration does really make sense and issues a
1229  * warning if not.
1230  */
1231 {
1232     if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1233         Warning ("Useless declaration");
1234     }
1235 }
1236
1237
1238
1239 static void SkipInitializer (unsigned BracesExpected)
1240 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1241  * smart so we don't have too many following errors.
1242  */
1243 {
1244     while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1245         switch (CurTok.Tok) {
1246             case TOK_RCURLY:    --BracesExpected;   break;
1247             case TOK_LCURLY:    ++BracesExpected;   break;
1248             default:                                break;
1249         }
1250         NextToken ();
1251     }
1252 }
1253
1254
1255
1256 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1257 /* Accept any number of opening curly braces around an initialization, skip
1258  * them and return the number. If the number of curly braces is less than
1259  * BracesNeeded, issue a warning.
1260  */
1261 {
1262     unsigned BraceCount = 0;
1263     while (CurTok.Tok == TOK_LCURLY) {
1264         ++BraceCount;
1265         NextToken ();
1266     }
1267     if (BraceCount < BracesNeeded) {
1268         Error ("`{' expected");
1269     }
1270     return BraceCount;
1271 }
1272
1273
1274
1275 static void ClosingCurlyBraces (unsigned BracesExpected)
1276 /* Accept and skip the given number of closing curly braces together with
1277  * an optional comma. Output an error messages, if the input does not contain
1278  * the expected number of braces.
1279  */
1280 {
1281     while (BracesExpected) {
1282         if (CurTok.Tok == TOK_RCURLY) {
1283             NextToken ();
1284         } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1285             NextToken ();
1286             NextToken ();
1287         } else {
1288             Error ("`}' expected");
1289             return;
1290         }
1291         --BracesExpected;
1292     }
1293 }
1294
1295
1296
1297 static void DefineData (ExprDesc* Expr)
1298 /* Output a data definition for the given expression */
1299 {
1300     switch (ED_GetLoc (Expr)) {
1301
1302         case E_LOC_ABS:
1303             /* Absolute: numeric address or const */
1304             g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1305             break;
1306
1307         case E_LOC_GLOBAL:
1308             /* Global variable */
1309             g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1310             break;
1311
1312         case E_LOC_STATIC:
1313         case E_LOC_LITERAL:
1314             /* Static variable or literal in the literal pool */
1315             g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1316             break;
1317
1318         case E_LOC_REGISTER:
1319             /* Register variable. Taking the address is usually not
1320              * allowed.
1321              */
1322             if (IS_Get (&AllowRegVarAddr) == 0) {
1323                 Error ("Cannot take the address of a register variable");
1324             }
1325             g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1326             break;
1327
1328         case E_LOC_STACK:
1329         case E_LOC_PRIMARY:
1330         case E_LOC_EXPR:
1331             Error ("Non constant initializer");
1332             break;
1333
1334         default:
1335             Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1336     }
1337 }
1338
1339
1340
1341 static unsigned ParseScalarInit (Type* T)
1342 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1343 {
1344     ExprDesc ED;
1345
1346     /* Optional opening brace */
1347     unsigned BraceCount = OpeningCurlyBraces (0);
1348
1349     /* We warn if an initializer for a scalar contains braces, because this is
1350      * quite unusual and often a sign for some problem in the input.
1351      */
1352     if (BraceCount > 0) {
1353         Warning ("Braces around scalar initializer");
1354     }
1355
1356     /* Get the expression and convert it to the target type */
1357     ConstExpr (hie1, &ED);
1358     TypeConversion (&ED, T);
1359
1360     /* Output the data */
1361     DefineData (&ED);
1362
1363     /* Close eventually opening braces */
1364     ClosingCurlyBraces (BraceCount);
1365
1366     /* Done */
1367     return SizeOf (T);
1368 }
1369
1370
1371
1372 static unsigned ParsePointerInit (Type* T)
1373 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1374 {
1375     /* Optional opening brace */
1376     unsigned BraceCount = OpeningCurlyBraces (0);
1377
1378     /* Expression */
1379     ExprDesc ED;
1380     ConstExpr (hie1, &ED);
1381     TypeConversion (&ED, T);
1382
1383     /* Output the data */
1384     DefineData (&ED);
1385
1386     /* Close eventually opening braces */
1387     ClosingCurlyBraces (BraceCount);
1388
1389     /* Done */
1390     return SIZEOF_PTR;
1391 }
1392
1393
1394
1395 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1396 /* Parse initializaton for arrays. Return the number of data bytes. */
1397 {
1398     int Count;
1399
1400     /* Get the array data */
1401     Type* ElementType    = GetElementType (T);
1402     unsigned ElementSize = CheckedSizeOf (ElementType);
1403     long ElementCount    = GetElementCount (T);
1404
1405     /* Special handling for a character array initialized by a literal */
1406     if (IsTypeChar (ElementType) &&
1407         (CurTok.Tok == TOK_SCONST ||
1408         (CurTok.Tok == TOK_LCURLY && NextTok.Tok == TOK_SCONST))) {
1409
1410         /* Char array initialized by string constant */
1411         int NeedParen;
1412         const char* Str;
1413
1414         /* If we initializer is enclosed in brackets, remember this fact and
1415          * skip the opening bracket.
1416          */
1417         NeedParen = (CurTok.Tok == TOK_LCURLY);
1418         if (NeedParen) {
1419             NextToken ();
1420         }
1421
1422         /* Get the initializer string and its size */
1423         Str = GetLiteral (CurTok.IVal);
1424         Count = GetLiteralPoolOffs () - CurTok.IVal;
1425
1426         /* Translate into target charset */
1427         TranslateLiteralPool (CurTok.IVal);
1428
1429         /* If the array is one too small for the string literal, omit the
1430          * trailing zero.
1431          */
1432         if (ElementCount != UNSPECIFIED &&
1433             ElementCount != FLEXIBLE    &&
1434             Count        == ElementCount + 1) {
1435             /* Omit the trailing zero */
1436             --Count;
1437         }
1438
1439         /* Output the data */
1440         g_defbytes (Str, Count);
1441
1442         /* Remove string from pool */
1443         ResetLiteralPoolOffs (CurTok.IVal);
1444         NextToken ();
1445
1446         /* If the initializer was enclosed in curly braces, we need a closing
1447          * one.
1448          */
1449         if (NeedParen) {
1450             ConsumeRCurly ();
1451         }
1452
1453     } else {
1454
1455         /* Curly brace */
1456         ConsumeLCurly ();
1457
1458         /* Initialize the array members */
1459         Count = 0;
1460         while (CurTok.Tok != TOK_RCURLY) {
1461             /* Flexible array members may not be initialized within
1462              * an array (because the size of each element may differ
1463              * otherwise).
1464              */
1465             ParseInitInternal (ElementType, 0);
1466             ++Count;
1467             if (CurTok.Tok != TOK_COMMA)
1468                 break;
1469             NextToken ();
1470         }
1471
1472         /* Closing curly braces */
1473         ConsumeRCurly ();
1474     }
1475
1476     if (ElementCount == UNSPECIFIED) {
1477         /* Number of elements determined by initializer */
1478         SetElementCount (T, Count);
1479         ElementCount = Count;
1480     } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1481         /* In non ANSI mode, allow initialization of flexible array
1482          * members.
1483          */
1484         ElementCount = Count;
1485     } else if (Count < ElementCount) {
1486         g_zerobytes ((ElementCount - Count) * ElementSize);
1487     } else if (Count > ElementCount) {
1488         Error ("Too many initializers");
1489     }
1490     return ElementCount * ElementSize;
1491 }
1492
1493
1494
1495 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1496 /* Parse initialization of a struct or union. Return the number of data bytes. */
1497 {
1498     SymEntry* Entry;
1499     SymTable* Tab;
1500     unsigned  StructSize;
1501     unsigned  Size;
1502
1503
1504     /* Consume the opening curly brace */
1505     ConsumeLCurly ();
1506
1507     /* Get a pointer to the struct entry from the type */
1508     Entry = GetSymEntry (T);
1509
1510     /* Get the size of the struct from the symbol table entry */
1511     StructSize = Entry->V.S.Size;
1512
1513     /* Check if this struct definition has a field table. If it doesn't, it
1514      * is an incomplete definition.
1515      */
1516     Tab = Entry->V.S.SymTab;
1517     if (Tab == 0) {
1518         Error ("Cannot initialize variables with incomplete type");
1519         /* Try error recovery */
1520         SkipInitializer (1);
1521         /* Nothing initialized */
1522         return 0;
1523     }
1524
1525     /* Get a pointer to the list of symbols */
1526     Entry = Tab->SymHead;
1527
1528     /* Initialize fields */
1529     Size = 0;
1530     while (CurTok.Tok != TOK_RCURLY) {
1531         if (Entry == 0) {
1532             Error ("Too many initializers");
1533             SkipInitializer (1);
1534             return Size;
1535         }
1536         /* Parse initialization of one field. Flexible array members may
1537          * only be initialized if they are the last field (or part of the
1538          * last struct field).
1539          */
1540         Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1541         Entry = Entry->NextSym;
1542         if (CurTok.Tok != TOK_COMMA)
1543             break;
1544         NextToken ();
1545     }
1546
1547     /* Consume the closing curly brace */
1548     ConsumeRCurly ();
1549
1550     /* If there are struct fields left, reserve additional storage */
1551     if (Size < StructSize) {
1552         g_zerobytes (StructSize - Size);
1553         Size = StructSize;
1554     }
1555
1556     /* Return the actual number of bytes initialized. This number may be
1557      * larger than StructSize if flexible array members are present and were
1558      * initialized (possible in non ANSI mode).
1559      */
1560     return Size;
1561 }
1562
1563
1564
1565 static unsigned ParseVoidInit (void)
1566 /* Parse an initialization of a void variable (special cc65 extension).
1567  * Return the number of bytes initialized.
1568  */
1569 {
1570     ExprDesc Expr;
1571     unsigned Size;
1572
1573     /* Opening brace */
1574     ConsumeLCurly ();
1575
1576     /* Allow an arbitrary list of values */
1577     Size = 0;
1578     do {
1579         ConstExpr (hie1, &Expr);
1580         switch (UnqualifiedType (Expr.Type[0].C)) {
1581
1582             case T_SCHAR:
1583             case T_UCHAR:
1584                 if (ED_IsConstAbsInt (&Expr)) {
1585                     /* Make it byte sized */
1586                     Expr.IVal &= 0xFF;
1587                 }
1588                 DefineData (&Expr);
1589                 Size += SIZEOF_CHAR;
1590                 break;
1591
1592             case T_SHORT:
1593             case T_USHORT:
1594             case T_INT:
1595             case T_UINT:
1596             case T_PTR:
1597             case T_ARRAY:
1598                 if (ED_IsConstAbsInt (&Expr)) {
1599                     /* Make it word sized */
1600                     Expr.IVal &= 0xFFFF;
1601                 }
1602                 DefineData (&Expr);
1603                 Size += SIZEOF_INT;
1604                 break;
1605
1606             case T_LONG:
1607             case T_ULONG:
1608                 if (ED_IsConstAbsInt (&Expr)) {
1609                     /* Make it dword sized */
1610                     Expr.IVal &= 0xFFFFFFFF;
1611                 }
1612                 DefineData (&Expr);
1613                 Size += SIZEOF_LONG;
1614                 break;
1615
1616             default:
1617                 Error ("Illegal type in initialization");
1618                 break;
1619
1620         }
1621
1622         if (CurTok.Tok != TOK_COMMA) {
1623             break;
1624         }
1625         NextToken ();
1626
1627     } while (CurTok.Tok != TOK_RCURLY);
1628
1629     /* Closing brace */
1630     ConsumeRCurly ();
1631
1632     /* Return the number of bytes initialized */
1633     return Size;
1634 }
1635
1636
1637
1638 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
1639 /* Parse initialization of variables. Return the number of data bytes. */
1640 {
1641     switch (UnqualifiedType (T->C)) {
1642
1643         case T_SCHAR:
1644         case T_UCHAR:
1645         case T_SHORT:
1646         case T_USHORT:
1647         case T_INT:
1648         case T_UINT:
1649         case T_LONG:
1650         case T_ULONG:
1651             return ParseScalarInit (T);
1652
1653         case T_PTR:
1654             return ParsePointerInit (T);
1655
1656         case T_ARRAY:
1657             return ParseArrayInit (T, AllowFlexibleMembers);
1658
1659         case T_STRUCT:
1660         case T_UNION:
1661             return ParseStructInit (T, AllowFlexibleMembers);
1662
1663         case T_VOID:
1664             if (IS_Get (&Standard) == STD_CC65) {
1665                 /* Special cc65 extension in non ANSI mode */
1666                 return ParseVoidInit ();
1667             }
1668             /* FALLTHROUGH */
1669
1670         default:
1671             Error ("Illegal type");
1672             return SIZEOF_CHAR;
1673
1674     }
1675 }
1676
1677
1678
1679 unsigned ParseInit (Type* T)
1680 /* Parse initialization of variables. Return the number of data bytes. */
1681 {
1682     /* Parse the initialization. Flexible array members can only be initialized
1683      * in cc65 mode.
1684      */
1685     unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
1686
1687     /* The initialization may not generate code on global level, because code
1688      * outside function scope will never get executed.
1689      */
1690     if (HaveGlobalCode ()) {
1691         Error ("Non constant initializers");
1692         RemoveGlobalCode ();
1693     }
1694
1695     /* Return the size needed for the initialization */
1696     return Size;
1697 }
1698
1699
1700