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