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