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