1 /*****************************************************************************/
5 /* Parse variable and function declarations */
9 /* (C) 1998-2010, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
65 /*****************************************************************************/
67 /*****************************************************************************/
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 */
81 /*****************************************************************************/
83 /*****************************************************************************/
87 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers);
88 /* Parse a type specificier */
90 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers);
91 /* Parse initialization of variables. Return the number of data bytes. */
95 /*****************************************************************************/
96 /* Internal functions */
97 /*****************************************************************************/
101 static void DuplicateQualifier (const char* Name)
102 /* Print an error message */
104 Warning ("Duplicate qualifier: `%s'", Name);
109 static TypeCode OptionalQualifiers (TypeCode Allowed)
110 /* Read type qualifiers if we have any. Allowed specifies the allowed
114 /* We start without any qualifiers */
115 TypeCode Q = T_QUAL_NONE;
117 /* Check for more qualifiers */
120 switch (CurTok.Tok) {
123 if (Allowed & T_QUAL_CONST) {
124 if (Q & T_QUAL_CONST) {
125 DuplicateQualifier ("const");
134 if (Allowed & T_QUAL_VOLATILE) {
135 if (Q & T_QUAL_VOLATILE) {
136 DuplicateQualifier ("volatile");
138 Q |= T_QUAL_VOLATILE;
145 if (Allowed & T_QUAL_RESTRICT) {
146 if (Q & T_QUAL_RESTRICT) {
147 DuplicateQualifier ("restrict");
149 Q |= T_QUAL_RESTRICT;
156 if (Allowed & T_QUAL_NEAR) {
157 if (Q & T_QUAL_NEAR) {
158 DuplicateQualifier ("near");
167 if (Allowed & T_QUAL_FAR) {
168 if (Q & T_QUAL_FAR) {
169 DuplicateQualifier ("far");
178 if (Allowed & T_QUAL_FASTCALL) {
179 if (Q & T_QUAL_FASTCALL) {
180 DuplicateQualifier ("fastcall");
182 Q |= T_QUAL_FASTCALL;
189 if (Allowed & T_QUAL_CDECL) {
190 if (Q & T_QUAL_CDECL) {
191 DuplicateQualifier ("cdecl");
209 /* We cannot have more than one address size far qualifier */
210 switch (Q & T_QUAL_ADDRSIZE) {
218 Error ("Cannot specify more than one address size qualifier");
219 Q &= ~T_QUAL_ADDRSIZE;
222 /* We cannot have more than one calling convention specifier */
223 switch (Q & T_QUAL_CCONV) {
226 case T_QUAL_FASTCALL:
231 Error ("Cannot specify more than one calling convention qualifier");
235 /* Return the qualifiers read */
241 static void OptionalInt (void)
242 /* Eat an optional "int" token */
244 if (CurTok.Tok == TOK_INT) {
252 static void OptionalSigned (void)
253 /* Eat an optional "signed" token */
255 if (CurTok.Tok == TOK_SIGNED) {
263 static void InitDeclSpec (DeclSpec* D)
264 /* Initialize the DeclSpec struct for use */
267 D->Type[0].C = T_END;
273 static void InitDeclaration (Declaration* D)
274 /* Initialize the Declaration struct for use */
277 D->Type[0].C = T_END;
284 static void NeedTypeSpace (Declaration* D, unsigned Count)
285 /* Check if there is enough space for Count type specifiers within D */
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.
292 Fatal ("Too many type specifiers");
298 static void AddTypeToDeclaration (Declaration* D, TypeCode T)
299 /* Add a type specifier to the type of a declaration */
301 NeedTypeSpace (D, 1);
302 D->Type[D->Index++].C = T;
307 static void FixQualifiers (Type* DataType)
308 /* Apply several fixes to qualifiers */
313 /* Using typedefs, it is possible to generate declarations that have
314 * type qualifiers attached to an array, not the element type. Go and
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);
325 /* Add extracted type qualifiers here */
331 /* Q must be empty now */
332 CHECK (Q == T_QUAL_NONE);
334 /* Do some fixes on pointers and functions. */
336 while (T->C != T_END) {
339 /* Fastcall qualifier on the pointer? */
340 if (IsQualFastcall (T)) {
341 /* Pointer to function which is not fastcall? */
342 if (IsTypeFunc (T+1) && !IsQualFastcall (T+1)) {
343 /* Move the fastcall qualifier from the pointer to
346 T[0].C &= ~T_QUAL_FASTCALL;
347 T[1].C |= T_QUAL_FASTCALL;
349 Error ("Invalid `_fastcall__' qualifier for pointer");
353 /* Apply the default far and near qualifiers if none are given */
354 Q = (T[0].C & T_QUAL_ADDRSIZE);
355 if (Q == T_QUAL_NONE) {
356 /* No address size qualifiers specified */
357 if (IsTypeFunc (T+1)) {
358 /* Pointer to function. Use the qualifier from the function
359 * or the default if the function don't has one.
361 Q = (T[1].C & T_QUAL_ADDRSIZE);
362 if (Q == T_QUAL_NONE) {
363 Q = CodeAddrSizeQualifier ();
366 Q = DataAddrSizeQualifier ();
370 /* We have address size qualifiers. If followed by a function,
371 * apply these also to the function.
373 if (IsTypeFunc (T+1)) {
374 TypeCode FQ = (T[1].C & T_QUAL_ADDRSIZE);
375 if (FQ == T_QUAL_NONE) {
377 } else if (FQ != Q) {
378 Error ("Address size qualifier mismatch");
379 T[1].C = (T[1].C & ~T_QUAL_ADDRSIZE) | Q;
384 } else if (IsTypeFunc (T)) {
386 /* Apply the default far and near qualifiers if none are given */
387 if ((T[0].C & T_QUAL_ADDRSIZE) == 0) {
388 T[0].C |= CodeAddrSizeQualifier ();
398 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
399 /* Parse a storage class */
401 /* Assume we're using an explicit storage class */
402 D->Flags &= ~DS_DEF_STORAGE;
404 /* Check the storage class given */
405 switch (CurTok.Tok) {
408 D->StorageClass = SC_EXTERN | SC_STATIC;
413 D->StorageClass = SC_STATIC;
418 D->StorageClass = SC_REGISTER | SC_STATIC;
423 D->StorageClass = SC_AUTO;
428 D->StorageClass = SC_TYPEDEF;
433 /* No storage class given, use default */
434 D->Flags |= DS_DEF_STORAGE;
435 D->StorageClass = DefStorage;
442 static void ParseEnumDecl (void)
443 /* Process an enum declaration . */
448 /* Accept forward definitions */
449 if (CurTok.Tok != TOK_LCURLY) {
453 /* Skip the opening curly brace */
456 /* Read the enum tags */
458 while (CurTok.Tok != TOK_RCURLY) {
460 /* We expect an identifier */
461 if (CurTok.Tok != TOK_IDENT) {
462 Error ("Identifier expected");
466 /* Remember the identifier and skip it */
467 strcpy (Ident, CurTok.Ident);
470 /* Check for an assigned value */
471 if (CurTok.Tok == TOK_ASSIGN) {
474 ConstAbsIntExpr (hie1, &Expr);
478 /* Add an entry to the symbol table */
479 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
481 /* Check for end of definition */
482 if (CurTok.Tok != TOK_COMMA)
491 static int ParseFieldWidth (Declaration* Decl)
492 /* Parse an optional field width. Returns -1 if no field width is speficied,
493 * otherwise the width of the field.
498 if (CurTok.Tok != TOK_COLON) {
499 /* No bit-field declaration */
505 ConstAbsIntExpr (hie1, &Expr);
507 Error ("Negative width in bit-field");
510 if (Expr.IVal > (int) INT_BITS) {
511 Error ("Width of bit-field exceeds its type");
514 if (Expr.IVal == 0 && Decl->Ident[0] != '\0') {
515 Error ("Zero width for named bit-field");
518 if (!IsTypeInt (Decl->Type)) {
519 /* Only integer types may be used for bit-fields */
520 Error ("Bit-field has invalid type");
524 /* Return the field width */
525 return (int) Expr.IVal;
530 static SymEntry* StructOrUnionForwardDecl (const char* Name)
531 /* Handle a struct or union forward decl */
533 /* Try to find a struct with the given name. If there is none,
534 * insert a forward declaration into the current lexical level.
536 SymEntry* Entry = FindTagSym (Name);
538 Entry = AddStructSym (Name, 0, 0);
539 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) != SC_STRUCT) {
540 /* Already defined in the level, but no struct */
541 Error ("Symbol `%s' is already different kind", Name);
548 static SymEntry* ParseUnionDecl (const char* Name)
549 /* Parse a union declaration. */
554 int FieldWidth; /* Width in bits, -1 if not a bit-field */
559 if (CurTok.Tok != TOK_LCURLY) {
560 /* Just a forward declaration. */
561 return StructOrUnionForwardDecl (Name);
564 /* Add a forward declaration for the struct in the current lexical level */
565 Entry = AddStructSym (Name, 0, 0);
567 /* Skip the curly brace */
570 /* Enter a new lexical level for the struct */
573 /* Parse union fields */
575 while (CurTok.Tok != TOK_RCURLY) {
577 /* Get the type of the entry */
579 InitDeclSpec (&Spec);
580 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
582 /* Read fields with this type */
587 /* Get type and name of the struct field */
588 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
590 /* Check for a bit-field declaration */
591 FieldWidth = ParseFieldWidth (&Decl);
593 /* Ignore zero sized bit fields in a union */
594 if (FieldWidth == 0) {
598 /* Check for fields without a name */
599 if (Decl.Ident[0] == '\0') {
600 /* Any field without a name is legal but useless in a union */
601 Warning ("Declaration does not declare anything");
606 FieldSize = CheckedSizeOf (Decl.Type);
607 if (FieldSize > UnionSize) {
608 UnionSize = FieldSize;
611 /* Add a field entry to the table. */
612 if (FieldWidth > 0) {
613 AddBitField (Decl.Ident, 0, 0, FieldWidth);
615 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, 0);
618 NextMember: if (CurTok.Tok != TOK_COMMA) {
626 /* Skip the closing brace */
629 /* Remember the symbol table and leave the struct level */
630 FieldTab = GetSymTab ();
633 /* Make a real entry from the forward decl and return it */
634 return AddStructSym (Name, UnionSize, FieldTab);
639 static SymEntry* ParseStructDecl (const char* Name)
640 /* Parse a struct declaration. */
645 int BitOffs; /* Bit offset for bit-fields */
646 int FieldWidth; /* Width in bits, -1 if not a bit-field */
651 if (CurTok.Tok != TOK_LCURLY) {
652 /* Just a forward declaration. */
653 return StructOrUnionForwardDecl (Name);
656 /* Add a forward declaration for the struct in the current lexical level */
657 Entry = AddStructSym (Name, 0, 0);
659 /* Skip the curly brace */
662 /* Enter a new lexical level for the struct */
665 /* Parse struct fields */
669 while (CurTok.Tok != TOK_RCURLY) {
671 /* Get the type of the entry */
673 InitDeclSpec (&Spec);
674 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
676 /* Read fields with this type */
682 /* If we had a flexible array member before, no other fields can
685 if (FlexibleMember) {
686 Error ("Flexible array member must be last field");
687 FlexibleMember = 0; /* Avoid further errors */
690 /* Get type and name of the struct field */
691 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
693 /* Check for a bit-field declaration */
694 FieldWidth = ParseFieldWidth (&Decl);
696 /* If this is not a bit field, or the bit field is too large for
697 * the remainder of the current member, or we have a bit field
698 * with width zero, align the struct to the next member by adding
699 * a member with an anonymous name.
702 if (FieldWidth <= 0 || (BitOffs + FieldWidth) > (int) INT_BITS) {
704 /* We need an anonymous name */
705 AnonName (Ident, "bit-field");
707 /* Add an anonymous bit-field that aligns to the next
710 AddBitField (Ident, StructSize, BitOffs, INT_BITS - BitOffs);
713 StructSize += SIZEOF_INT;
718 /* Apart from the above, a bit field with width 0 is not processed
721 if (FieldWidth == 0) {
725 /* Check for fields without names */
726 if (Decl.Ident[0] == '\0') {
727 if (FieldWidth < 0) {
728 /* A non bit-field without a name is legal but useless */
729 Warning ("Declaration does not declare anything");
732 /* A bit-field without a name will get an anonymous one */
733 AnonName (Decl.Ident, "bit-field");
737 /* Check if this field is a flexible array member, and
738 * calculate the size of the field.
740 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
741 /* Array with unspecified size */
742 if (StructSize == 0) {
743 Error ("Flexible array member cannot be first struct field");
746 /* Assume zero for size calculations */
747 SetElementCount (Decl.Type, FLEXIBLE);
750 /* Add a field entry to the table */
751 if (FieldWidth > 0) {
752 /* Add full byte from the bit offset to the variable offset.
753 * This simplifies handling he bit-field as a char type
756 unsigned Offs = StructSize + (BitOffs / CHAR_BITS);
757 AddBitField (Decl.Ident, Offs, BitOffs % CHAR_BITS, FieldWidth);
758 BitOffs += FieldWidth;
759 CHECK (BitOffs <= (int) INT_BITS);
760 if (BitOffs == INT_BITS) {
761 StructSize += SIZEOF_INT;
765 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, StructSize);
766 if (!FlexibleMember) {
767 StructSize += CheckedSizeOf (Decl.Type);
771 NextMember: if (CurTok.Tok != TOK_COMMA) {
779 /* If we have bits from bit-fields left, add them to the size. */
781 StructSize += ((BitOffs + CHAR_BITS - 1) / CHAR_BITS);
784 /* Skip the closing brace */
787 /* Remember the symbol table and leave the struct level */
788 FieldTab = GetSymTab ();
791 /* Make a real entry from the forward decl and return it */
792 return AddStructSym (Name, StructSize, FieldTab);
797 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
798 /* Parse a type specificier */
803 /* Assume we have an explicit type */
804 D->Flags &= ~DS_DEF_TYPE;
806 /* Read type qualifiers if we have any */
807 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
809 /* Look at the data type */
810 switch (CurTok.Tok) {
814 D->Type[0].C = T_VOID;
815 D->Type[1].C = T_END;
820 D->Type[0].C = GetDefaultChar();
821 D->Type[1].C = T_END;
826 if (CurTok.Tok == TOK_UNSIGNED) {
829 D->Type[0].C = T_ULONG;
830 D->Type[1].C = T_END;
834 D->Type[0].C = T_LONG;
835 D->Type[1].C = T_END;
841 if (CurTok.Tok == TOK_UNSIGNED) {
844 D->Type[0].C = T_USHORT;
845 D->Type[1].C = T_END;
849 D->Type[0].C = T_SHORT;
850 D->Type[1].C = T_END;
856 D->Type[0].C = T_INT;
857 D->Type[1].C = T_END;
862 switch (CurTok.Tok) {
866 D->Type[0].C = T_SCHAR;
867 D->Type[1].C = T_END;
873 D->Type[0].C = T_SHORT;
874 D->Type[1].C = T_END;
880 D->Type[0].C = T_LONG;
881 D->Type[1].C = T_END;
889 D->Type[0].C = T_INT;
890 D->Type[1].C = T_END;
897 switch (CurTok.Tok) {
901 D->Type[0].C = T_UCHAR;
902 D->Type[1].C = T_END;
908 D->Type[0].C = T_USHORT;
909 D->Type[1].C = T_END;
915 D->Type[0].C = T_ULONG;
916 D->Type[1].C = T_END;
924 D->Type[0].C = T_UINT;
925 D->Type[1].C = T_END;
932 D->Type[0].C = T_FLOAT;
933 D->Type[1].C = T_END;
938 D->Type[0].C = T_DOUBLE;
939 D->Type[1].C = T_END;
945 if (CurTok.Tok == TOK_IDENT) {
946 strcpy (Ident, CurTok.Ident);
949 AnonName (Ident, "union");
951 /* Remember we have an extra type decl */
952 D->Flags |= DS_EXTRA_TYPE;
953 /* Declare the union in the current scope */
954 Entry = ParseUnionDecl (Ident);
955 /* Encode the union entry into the type */
956 D->Type[0].C = T_UNION;
957 SetSymEntry (D->Type, Entry);
958 D->Type[1].C = T_END;
964 if (CurTok.Tok == TOK_IDENT) {
965 strcpy (Ident, CurTok.Ident);
968 AnonName (Ident, "struct");
970 /* Remember we have an extra type decl */
971 D->Flags |= DS_EXTRA_TYPE;
972 /* Declare the struct in the current scope */
973 Entry = ParseStructDecl (Ident);
974 /* Encode the struct entry into the type */
975 D->Type[0].C = T_STRUCT;
976 SetSymEntry (D->Type, Entry);
977 D->Type[1].C = T_END;
982 if (CurTok.Tok != TOK_LCURLY) {
984 if (CurTok.Tok == TOK_IDENT) {
985 /* Find an entry with this name */
986 Entry = FindTagSym (CurTok.Ident);
988 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
989 Error ("Symbol `%s' is already different kind", Entry->Name);
992 /* Insert entry into table ### */
994 /* Skip the identifier */
997 Error ("Identifier expected");
1000 /* Remember we have an extra type decl */
1001 D->Flags |= DS_EXTRA_TYPE;
1002 /* Parse the enum decl */
1004 D->Type[0].C = T_INT;
1005 D->Type[1].C = T_END;
1009 Entry = FindSym (CurTok.Ident);
1010 if (Entry && SymIsTypeDef (Entry)) {
1011 /* It's a typedef */
1013 TypeCopy (D->Type, Entry->Type);
1020 Error ("Type expected");
1021 D->Type[0].C = T_INT;
1022 D->Type[1].C = T_END;
1024 D->Flags |= DS_DEF_TYPE;
1025 D->Type[0].C = (TypeCode) Default;
1026 D->Type[1].C = T_END;
1031 /* There may also be qualifiers *after* the initial type */
1032 D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
1037 static Type* ParamTypeCvt (Type* T)
1038 /* If T is an array, convert it to a pointer else do nothing. Return the
1042 if (IsTypeArray (T)) {
1050 static void ParseOldStyleParamList (FuncDesc* F)
1051 /* Parse an old style (K&R) parameter list */
1054 while (CurTok.Tok != TOK_RPAREN) {
1056 /* List of identifiers expected */
1057 if (CurTok.Tok != TOK_IDENT) {
1058 Error ("Identifier expected");
1061 /* Create a symbol table entry with type int */
1062 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1064 /* Count arguments */
1067 /* Skip the identifier */
1070 /* Check for more parameters */
1071 if (CurTok.Tok == TOK_COMMA) {
1078 /* Skip right paren. We must explicitly check for one here, since some of
1079 * the breaks above bail out without checking.
1083 /* An optional list of type specifications follows */
1084 while (CurTok.Tok != TOK_LCURLY) {
1088 /* Read the declaration specifier */
1089 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1091 /* We accept only auto and register as storage class specifiers, but
1092 * we ignore all this, since we use auto anyway.
1094 if ((Spec.StorageClass & SC_AUTO) == 0 &&
1095 (Spec.StorageClass & SC_REGISTER) == 0) {
1096 Error ("Illegal storage class");
1099 /* Parse a comma separated variable list */
1104 /* Read the parameter */
1105 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1106 if (Decl.Ident[0] != '\0') {
1108 /* We have a name given. Search for the symbol */
1109 SymEntry* Sym = FindLocalSym (Decl.Ident);
1111 /* Check if we already changed the type for this
1114 if (Sym->Flags & SC_DEFTYPE) {
1115 /* Found it, change the default type to the one given */
1116 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1117 /* Reset the "default type" flag */
1118 Sym->Flags &= ~SC_DEFTYPE;
1120 /* Type has already been changed */
1121 Error ("Redefinition for parameter `%s'", Sym->Name);
1124 Error ("Unknown identifier: `%s'", Decl.Ident);
1128 if (CurTok.Tok == TOK_COMMA) {
1136 /* Variable list must be semicolon terminated */
1143 static void ParseAnsiParamList (FuncDesc* F)
1144 /* Parse a new style (ANSI) parameter list */
1147 while (CurTok.Tok != TOK_RPAREN) {
1153 /* Allow an ellipsis as last parameter */
1154 if (CurTok.Tok == TOK_ELLIPSIS) {
1156 F->Flags |= FD_VARIADIC;
1160 /* Read the declaration specifier */
1161 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1163 /* We accept only auto and register as storage class specifiers */
1164 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1165 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1166 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1167 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1169 Error ("Illegal storage class");
1170 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1173 /* Allow parameters without a name, but remember if we had some to
1174 * eventually print an error message later.
1176 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1177 if (Decl.Ident[0] == '\0') {
1179 /* Unnamed symbol. Generate a name that is not user accessible,
1180 * then handle the symbol normal.
1182 AnonName (Decl.Ident, "param");
1183 F->Flags |= FD_UNNAMED_PARAMS;
1185 /* Clear defined bit on nonames */
1186 Decl.StorageClass &= ~SC_DEF;
1189 /* Parse attributes for this parameter */
1190 ParseAttribute (&Decl);
1192 /* Create a symbol table entry */
1193 Sym = AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1195 /* Add attributes if we have any */
1196 SymUseAttr (Sym, &Decl);
1198 /* If the parameter is a struct or union, emit a warning */
1199 if (IsClassStruct (Decl.Type)) {
1200 if (IS_Get (&WarnStructParam)) {
1201 Warning ("Passing struct by value for parameter `%s'", Decl.Ident);
1205 /* Count arguments */
1208 /* Check for more parameters */
1209 if (CurTok.Tok == TOK_COMMA) {
1216 /* Skip right paren. We must explicitly check for one here, since some of
1217 * the breaks above bail out without checking.
1224 static FuncDesc* ParseFuncDecl (void)
1225 /* Parse the argument list of a function. */
1230 /* Create a new function descriptor */
1231 FuncDesc* F = NewFuncDesc ();
1233 /* Enter a new lexical level */
1234 EnterFunctionLevel ();
1236 /* Check for several special parameter lists */
1237 if (CurTok.Tok == TOK_RPAREN) {
1238 /* Parameter list is empty */
1239 F->Flags |= (FD_EMPTY | FD_VARIADIC);
1240 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1241 /* Parameter list declared as void */
1243 F->Flags |= FD_VOID_PARAM;
1244 } else if (CurTok.Tok == TOK_IDENT &&
1245 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1246 /* If the identifier is a typedef, we have a new style parameter list,
1247 * if it's some other identifier, it's an old style parameter list.
1249 Sym = FindSym (CurTok.Ident);
1250 if (Sym == 0 || !SymIsTypeDef (Sym)) {
1251 /* Old style (K&R) function. */
1252 F->Flags |= FD_OLDSTYLE;
1257 if ((F->Flags & FD_OLDSTYLE) == 0) {
1259 /* New style function */
1260 ParseAnsiParamList (F);
1263 /* Old style function */
1264 ParseOldStyleParamList (F);
1267 /* Remember the last function parameter. We need it later for several
1268 * purposes, for example when passing stuff to fastcall functions. Since
1269 * more symbols are added to the table, it is easier if we remember it
1270 * now, since it is currently the last entry in the symbol table.
1272 F->LastParam = GetSymTab()->SymTail;
1274 /* Assign offsets. If the function has a variable parameter list,
1275 * there's one additional byte (the arg size).
1277 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1280 unsigned Size = CheckedSizeOf (Sym->Type);
1281 if (SymIsRegVar (Sym)) {
1282 Sym->V.R.SaveOffs = Offs;
1287 F->ParamSize += Size;
1291 /* Leave the lexical level remembering the symbol tables */
1292 RememberFunctionLevel (F);
1294 /* Return the function descriptor */
1300 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1301 /* Recursively process declarators. Build a type array in reverse order. */
1303 /* Read optional function or pointer qualifiers. These modify the
1304 * identifier or token to the right. For convenience, we allow the fastcall
1305 * qualifier also for pointers here. If it is a pointer-to-function, the
1306 * qualifier will later be transfered to the function itself. If it's a
1307 * pointer to something else, it will be flagged as an error.
1309 TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL);
1311 /* Pointer to something */
1312 if (CurTok.Tok == TOK_STAR) {
1317 /* Allow const, restrict and volatile qualifiers */
1318 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1320 /* Parse the type, the pointer points to */
1321 Declarator (Spec, D, Mode);
1324 AddTypeToDeclaration (D, T_PTR | Qualifiers);
1328 if (CurTok.Tok == TOK_LPAREN) {
1330 Declarator (Spec, D, Mode);
1333 /* Things depend on Mode now:
1334 * - Mode == DM_NEED_IDENT means:
1335 * we *must* have a type and a variable identifer.
1336 * - Mode == DM_NO_IDENT means:
1337 * we must have a type but no variable identifer
1338 * (if there is one, it's not read).
1339 * - Mode == DM_ACCEPT_IDENT means:
1340 * we *may* have an identifier. If there is an identifier,
1341 * it is read, but it is no error, if there is none.
1343 if (Mode == DM_NO_IDENT) {
1345 } else if (CurTok.Tok == TOK_IDENT) {
1346 strcpy (D->Ident, CurTok.Ident);
1349 if (Mode == DM_NEED_IDENT) {
1350 Error ("Identifier expected");
1356 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1357 if (CurTok.Tok == TOK_LPAREN) {
1359 /* Function declaration */
1362 /* Skip the opening paren */
1365 /* Parse the function declaration */
1366 F = ParseFuncDecl ();
1368 /* We cannot specify fastcall for variadic functions */
1369 if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1370 Error ("Variadic functions cannot be `__fastcall'");
1371 Qualifiers &= ~T_QUAL_FASTCALL;
1374 /* Add the function type. Be sure to bounds check the type buffer */
1375 NeedTypeSpace (D, 1);
1376 D->Type[D->Index].C = T_FUNC | Qualifiers;
1377 D->Type[D->Index].A.P = F;
1380 /* Qualifiers now used */
1381 Qualifiers = T_QUAL_NONE;
1384 /* Array declaration. */
1385 long Size = UNSPECIFIED;
1387 /* We cannot have any qualifiers for an array */
1388 if (Qualifiers != T_QUAL_NONE) {
1389 Error ("Invalid qualifiers for array");
1390 Qualifiers = T_QUAL_NONE;
1393 /* Skip the left bracket */
1396 /* Read the size if it is given */
1397 if (CurTok.Tok != TOK_RBRACK) {
1399 ConstAbsIntExpr (hie1, &Expr);
1400 if (Expr.IVal <= 0) {
1401 if (D->Ident[0] != '\0') {
1402 Error ("Size of array `%s' is invalid", D->Ident);
1404 Error ("Size of array is invalid");
1411 /* Skip the right bracket */
1414 /* Add the array type with the size to the type */
1415 NeedTypeSpace (D, 1);
1416 D->Type[D->Index].C = T_ARRAY;
1417 D->Type[D->Index].A.L = Size;
1422 /* If we have remaining qualifiers, flag them as invalid */
1423 if (Qualifiers & T_QUAL_NEAR) {
1424 Error ("Invalid `__near__' qualifier");
1426 if (Qualifiers & T_QUAL_FAR) {
1427 Error ("Invalid `__far__' qualifier");
1429 if (Qualifiers & T_QUAL_FASTCALL) {
1430 Error ("Invalid `__fastcall__' qualifier");
1432 if (Qualifiers & T_QUAL_CDECL) {
1433 Error ("Invalid `__cdecl__' qualifier");
1439 /*****************************************************************************/
1441 /*****************************************************************************/
1445 Type* ParseType (Type* T)
1446 /* Parse a complete type specification */
1451 /* Get a type without a default */
1452 InitDeclSpec (&Spec);
1453 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1455 /* Parse additional declarators */
1456 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1458 /* Copy the type to the target buffer */
1459 TypeCopy (T, Decl.Type);
1461 /* Return a pointer to the target buffer */
1467 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1468 /* Parse a variable, type or function declaration */
1470 /* Initialize the Declaration struct */
1471 InitDeclaration (D);
1473 /* Get additional declarators and the identifier */
1474 Declarator (Spec, D, Mode);
1476 /* Add the base type. */
1477 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1478 TypeCopy (D->Type + D->Index, Spec->Type);
1480 /* Use the storage class from the declspec */
1481 D->StorageClass = Spec->StorageClass;
1483 /* Do several fixes on qualifiers */
1484 FixQualifiers (D->Type);
1486 /* If we have a function, add a special storage class */
1487 if (IsTypeFunc (D->Type)) {
1488 D->StorageClass |= SC_FUNC;
1491 /* Parse attributes for this declaration */
1494 /* Check several things for function or function pointer types */
1495 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1497 /* A function. Check the return type */
1498 Type* RetType = GetFuncReturn (D->Type);
1500 /* Functions may not return functions or arrays */
1501 if (IsTypeFunc (RetType)) {
1502 Error ("Functions are not allowed to return functions");
1503 } else if (IsTypeArray (RetType)) {
1504 Error ("Functions are not allowed to return arrays");
1507 /* The return type must not be qualified */
1508 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1510 if (GetType (RetType) == T_TYPE_VOID) {
1511 /* A qualified void type is always an error */
1512 Error ("function definition has qualified void return type");
1514 /* For others, qualifiers are ignored */
1515 Warning ("type qualifiers ignored on function return type");
1516 RetType[0].C = UnqualifiedType (RetType[0].C);
1520 /* Warn about an implicit int return in the function */
1521 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1522 RetType[0].C == T_INT && RetType[1].C == T_END) {
1523 /* Function has an implicit int return. Output a warning if we don't
1524 * have the C89 standard enabled explicitly.
1526 if (IS_Get (&Standard) >= STD_C99) {
1527 Warning ("Implicit `int' return type is an obsolete feature");
1529 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1534 /* For anthing that is not a function or typedef, check for an implicit
1537 if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1538 (D->StorageClass & SC_TYPEDEF) != SC_TYPEDEF) {
1539 /* If the standard was not set explicitly to C89, print a warning
1540 * for variables with implicit int type.
1542 if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1543 Warning ("Implicit `int' is an obsolete feature");
1547 /* Check the size of the generated type */
1548 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1549 unsigned Size = SizeOf (D->Type);
1550 if (Size >= 0x10000) {
1551 if (D->Ident[0] != '\0') {
1552 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1554 Error ("Invalid size in declaration (0x%06X)", Size);
1563 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1564 /* Parse a declaration specification */
1566 TypeCode Qualifiers;
1568 /* Initialize the DeclSpec struct */
1571 /* There may be qualifiers *before* the storage class specifier */
1572 Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1574 /* Now get the storage class specifier for this declaration */
1575 ParseStorageClass (D, DefStorage);
1577 /* Parse the type specifiers passing any initial type qualifiers */
1578 ParseTypeSpec (D, DefType, Qualifiers);
1583 void CheckEmptyDecl (const DeclSpec* D)
1584 /* Called after an empty type declaration (that is, a type declaration without
1585 * a variable). Checks if the declaration does really make sense and issues a
1589 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1590 Warning ("Useless declaration");
1596 static void SkipInitializer (unsigned BracesExpected)
1597 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1598 * smart so we don't have too many following errors.
1601 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1602 switch (CurTok.Tok) {
1603 case TOK_RCURLY: --BracesExpected; break;
1604 case TOK_LCURLY: ++BracesExpected; break;
1613 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1614 /* Accept any number of opening curly braces around an initialization, skip
1615 * them and return the number. If the number of curly braces is less than
1616 * BracesNeeded, issue a warning.
1619 unsigned BraceCount = 0;
1620 while (CurTok.Tok == TOK_LCURLY) {
1624 if (BraceCount < BracesNeeded) {
1625 Error ("`{' expected");
1632 static void ClosingCurlyBraces (unsigned BracesExpected)
1633 /* Accept and skip the given number of closing curly braces together with
1634 * an optional comma. Output an error messages, if the input does not contain
1635 * the expected number of braces.
1638 while (BracesExpected) {
1639 if (CurTok.Tok == TOK_RCURLY) {
1641 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1645 Error ("`}' expected");
1654 static void DefineData (ExprDesc* Expr)
1655 /* Output a data definition for the given expression */
1657 switch (ED_GetLoc (Expr)) {
1660 /* Absolute: numeric address or const */
1661 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1665 /* Global variable */
1666 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1671 /* Static variable or literal in the literal pool */
1672 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1675 case E_LOC_REGISTER:
1676 /* Register variable. Taking the address is usually not
1679 if (IS_Get (&AllowRegVarAddr) == 0) {
1680 Error ("Cannot take the address of a register variable");
1682 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1688 Error ("Non constant initializer");
1692 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1698 static void OutputBitFieldData (StructInitData* SI)
1699 /* Output bit field data */
1701 /* Ignore if we have no data */
1702 if (SI->ValBits > 0) {
1704 /* Output the data */
1705 g_defdata (CF_INT | CF_UNSIGNED | CF_CONST, SI->BitVal, 0);
1707 /* Clear the data from SI and account for the size */
1710 SI->Offs += SIZEOF_INT;
1716 static void ParseScalarInitInternal (Type* T, ExprDesc* ED)
1717 /* Parse initializaton for scalar data types. This function will not output the
1718 * data but return it in ED.
1721 /* Optional opening brace */
1722 unsigned BraceCount = OpeningCurlyBraces (0);
1724 /* We warn if an initializer for a scalar contains braces, because this is
1725 * quite unusual and often a sign for some problem in the input.
1727 if (BraceCount > 0) {
1728 Warning ("Braces around scalar initializer");
1731 /* Get the expression and convert it to the target type */
1732 ConstExpr (hie1, ED);
1733 TypeConversion (ED, T);
1735 /* Close eventually opening braces */
1736 ClosingCurlyBraces (BraceCount);
1741 static unsigned ParseScalarInit (Type* T)
1742 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1746 /* Parse initialization */
1747 ParseScalarInitInternal (T, &ED);
1749 /* Output the data */
1758 static unsigned ParsePointerInit (Type* T)
1759 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1761 /* Optional opening brace */
1762 unsigned BraceCount = OpeningCurlyBraces (0);
1766 ConstExpr (hie1, &ED);
1767 TypeConversion (&ED, T);
1769 /* Output the data */
1772 /* Close eventually opening braces */
1773 ClosingCurlyBraces (BraceCount);
1781 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1782 /* Parse initializaton for arrays. Return the number of data bytes. */
1786 /* Get the array data */
1787 Type* ElementType = GetElementType (T);
1788 unsigned ElementSize = CheckedSizeOf (ElementType);
1789 long ElementCount = GetElementCount (T);
1791 /* Special handling for a character array initialized by a literal */
1792 if (IsTypeChar (ElementType) &&
1793 (CurTok.Tok == TOK_SCONST || CurTok.Tok == TOK_WCSCONST ||
1794 (CurTok.Tok == TOK_LCURLY &&
1795 (NextTok.Tok == TOK_SCONST || NextTok.Tok == TOK_WCSCONST)))) {
1797 /* Char array initialized by string constant */
1800 /* If we initializer is enclosed in brackets, remember this fact and
1801 * skip the opening bracket.
1803 NeedParen = (CurTok.Tok == TOK_LCURLY);
1808 /* Translate into target charset */
1809 TranslateLiteral (CurTok.SVal);
1811 /* If the array is one too small for the string literal, omit the
1814 Count = GetLiteralSize (CurTok.SVal);
1815 if (ElementCount != UNSPECIFIED &&
1816 ElementCount != FLEXIBLE &&
1817 Count == ElementCount + 1) {
1818 /* Omit the trailing zero */
1822 /* Output the data */
1823 g_defbytes (GetLiteralStr (CurTok.SVal), Count);
1825 /* Skip the string */
1828 /* If the initializer was enclosed in curly braces, we need a closing
1840 /* Initialize the array members */
1842 while (CurTok.Tok != TOK_RCURLY) {
1843 /* Flexible array members may not be initialized within
1844 * an array (because the size of each element may differ
1847 ParseInitInternal (ElementType, 0);
1849 if (CurTok.Tok != TOK_COMMA)
1854 /* Closing curly braces */
1858 if (ElementCount == UNSPECIFIED) {
1859 /* Number of elements determined by initializer */
1860 SetElementCount (T, Count);
1861 ElementCount = Count;
1862 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1863 /* In non ANSI mode, allow initialization of flexible array
1866 ElementCount = Count;
1867 } else if (Count < ElementCount) {
1868 g_zerobytes ((ElementCount - Count) * ElementSize);
1869 } else if (Count > ElementCount) {
1870 Error ("Too many initializers");
1872 return ElementCount * ElementSize;
1877 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1878 /* Parse initialization of a struct or union. Return the number of data bytes. */
1885 /* Consume the opening curly brace */
1888 /* Get a pointer to the struct entry from the type */
1889 Entry = GetSymEntry (T);
1891 /* Get the size of the struct from the symbol table entry */
1892 SI.Size = Entry->V.S.Size;
1894 /* Check if this struct definition has a field table. If it doesn't, it
1895 * is an incomplete definition.
1897 Tab = Entry->V.S.SymTab;
1899 Error ("Cannot initialize variables with incomplete type");
1900 /* Try error recovery */
1901 SkipInitializer (1);
1902 /* Nothing initialized */
1906 /* Get a pointer to the list of symbols */
1907 Entry = Tab->SymHead;
1909 /* Initialize fields */
1913 while (CurTok.Tok != TOK_RCURLY) {
1917 Error ("Too many initializers");
1918 SkipInitializer (1);
1922 /* Parse initialization of one field. Bit-fields need a special
1925 if (SymIsBitField (Entry)) {
1931 /* Calculate the bitmask from the bit-field data */
1932 unsigned Mask = (1U << Entry->V.B.BitWidth) - 1U;
1935 CHECK (Entry->V.B.Offs * CHAR_BITS + Entry->V.B.BitOffs ==
1936 SI.Offs * CHAR_BITS + SI.ValBits);
1938 /* This may be an anonymous bit-field, in which case it doesn't
1939 * have an initializer.
1941 if (IsAnonName (Entry->Name)) {
1942 /* Account for the data and output it if we have a full word */
1943 SI.ValBits += Entry->V.B.BitWidth;
1944 CHECK (SI.ValBits <= INT_BITS);
1945 if (SI.ValBits == INT_BITS) {
1946 OutputBitFieldData (&SI);
1950 /* Read the data, check for a constant integer, do a range
1953 ParseScalarInitInternal (type_uint, &ED);
1954 if (!ED_IsConstAbsInt (&ED)) {
1955 Error ("Constant initializer expected");
1956 ED_MakeConstAbsInt (&ED, 1);
1958 if (ED.IVal > (long) Mask) {
1959 Warning ("Truncating value in bit-field initializer");
1960 ED.IVal &= (long) Mask;
1962 Val = (unsigned) ED.IVal;
1965 /* Add the value to the currently stored bit-field value */
1966 Shift = (Entry->V.B.Offs - SI.Offs) * CHAR_BITS + Entry->V.B.BitOffs;
1967 SI.BitVal |= (Val << Shift);
1969 /* Account for the data and output it if we have a full word */
1970 SI.ValBits += Entry->V.B.BitWidth;
1971 CHECK (SI.ValBits <= INT_BITS);
1972 if (SI.ValBits == INT_BITS) {
1973 OutputBitFieldData (&SI);
1978 /* Standard member. We should never have stuff from a
1981 CHECK (SI.ValBits == 0);
1983 /* Flexible array members may only be initialized if they are
1984 * the last field (or part of the last struct field).
1986 SI.Offs += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1989 /* More initializers? */
1990 if (CurTok.Tok != TOK_COMMA) {
1994 /* Skip the comma */
1998 /* Next member. For unions, only the first one can be initialized */
1999 if (IsTypeUnion (T)) {
2004 Entry = Entry->NextSym;
2008 /* Consume the closing curly brace */
2011 /* If we have data from a bit-field left, output it now */
2012 OutputBitFieldData (&SI);
2014 /* If there are struct fields left, reserve additional storage */
2015 if (SI.Offs < SI.Size) {
2016 g_zerobytes (SI.Size - SI.Offs);
2020 /* Return the actual number of bytes initialized. This number may be
2021 * larger than sizeof (Struct) if flexible array members are present and
2022 * were initialized (possible in non ANSI mode).
2029 static unsigned ParseVoidInit (void)
2030 /* Parse an initialization of a void variable (special cc65 extension).
2031 * Return the number of bytes initialized.
2040 /* Allow an arbitrary list of values */
2043 ConstExpr (hie1, &Expr);
2044 switch (UnqualifiedType (Expr.Type[0].C)) {
2048 if (ED_IsConstAbsInt (&Expr)) {
2049 /* Make it byte sized */
2053 Size += SIZEOF_CHAR;
2062 if (ED_IsConstAbsInt (&Expr)) {
2063 /* Make it word sized */
2064 Expr.IVal &= 0xFFFF;
2072 if (ED_IsConstAbsInt (&Expr)) {
2073 /* Make it dword sized */
2074 Expr.IVal &= 0xFFFFFFFF;
2077 Size += SIZEOF_LONG;
2081 Error ("Illegal type in initialization");
2086 if (CurTok.Tok != TOK_COMMA) {
2091 } while (CurTok.Tok != TOK_RCURLY);
2096 /* Return the number of bytes initialized */
2102 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
2103 /* Parse initialization of variables. Return the number of data bytes. */
2105 switch (UnqualifiedType (T->C)) {
2117 return ParseScalarInit (T);
2120 return ParsePointerInit (T);
2123 return ParseArrayInit (T, AllowFlexibleMembers);
2127 return ParseStructInit (T, AllowFlexibleMembers);
2130 if (IS_Get (&Standard) == STD_CC65) {
2131 /* Special cc65 extension in non ANSI mode */
2132 return ParseVoidInit ();
2137 Error ("Illegal type");
2145 unsigned ParseInit (Type* T)
2146 /* Parse initialization of variables. Return the number of data bytes. */
2148 /* Parse the initialization. Flexible array members can only be initialized
2151 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
2153 /* The initialization may not generate code on global level, because code
2154 * outside function scope will never get executed.
2156 if (HaveGlobalCode ()) {
2157 Error ("Non constant initializers");
2158 RemoveGlobalCode ();
2161 /* Return the size needed for the initialization */