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