1 /*****************************************************************************/
5 /* Parse variable and function declarations */
9 /* (C) 1998-2008 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 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers);
72 /* Parse a type specificier */
74 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers);
75 /* Parse initialization of variables. Return the number of data bytes. */
79 /*****************************************************************************/
80 /* internal functions */
81 /*****************************************************************************/
85 static void DuplicateQualifier (const char* Name)
86 /* Print an error message */
88 Warning ("Duplicate qualifier: `%s'", Name);
93 static TypeCode OptionalQualifiers (TypeCode Allowed)
94 /* Read type qualifiers if we have any. Allowed specifies the allowed
98 /* We start without any qualifiers */
99 TypeCode Q = T_QUAL_NONE;
101 /* Check for more qualifiers */
104 switch (CurTok.Tok) {
107 if (Allowed & T_QUAL_CONST) {
108 if (Q & T_QUAL_CONST) {
109 DuplicateQualifier ("const");
118 if (Allowed & T_QUAL_VOLATILE) {
119 if (Q & T_QUAL_VOLATILE) {
120 DuplicateQualifier ("volatile");
122 Q |= T_QUAL_VOLATILE;
129 if (Allowed & T_QUAL_RESTRICT) {
130 if (Q & T_QUAL_RESTRICT) {
131 DuplicateQualifier ("restrict");
133 Q |= T_QUAL_RESTRICT;
140 if (Allowed & T_QUAL_NEAR) {
141 if (Q & T_QUAL_NEAR) {
142 DuplicateQualifier ("near");
151 if (Allowed & T_QUAL_FAR) {
152 if (Q & T_QUAL_FAR) {
153 DuplicateQualifier ("far");
162 if (Allowed & T_QUAL_FASTCALL) {
163 if (Q & T_QUAL_FASTCALL) {
164 DuplicateQualifier ("fastcall");
166 Q |= T_QUAL_FASTCALL;
182 /* We cannot have more than one address size far qualifier */
183 switch (Q & T_QUAL_ADDRSIZE) {
191 Error ("Cannot specify more than one address size qualifier");
192 Q &= ~T_QUAL_ADDRSIZE;
195 /* Return the qualifiers read */
201 static void OptionalInt (void)
202 /* Eat an optional "int" token */
204 if (CurTok.Tok == TOK_INT) {
212 static void OptionalSigned (void)
213 /* Eat an optional "signed" token */
215 if (CurTok.Tok == TOK_SIGNED) {
223 static void InitDeclSpec (DeclSpec* D)
224 /* Initialize the DeclSpec struct for use */
227 D->Type[0].C = T_END;
233 static void InitDeclaration (Declaration* D)
234 /* Initialize the Declaration struct for use */
237 D->Type[0].C = T_END;
243 static void NeedTypeSpace (Declaration* D, unsigned Count)
244 /* Check if there is enough space for Count type specifiers within D */
246 if (D->Index + Count >= MAXTYPELEN) {
247 /* We must call Fatal() here, since calling Error() will try to
248 * continue, and the declaration type is not correctly terminated
249 * in case we come here.
251 Fatal ("Too many type specifiers");
257 static void AddTypeToDeclaration (Declaration* D, TypeCode T)
258 /* Add a type specifier to the type of a declaration */
260 NeedTypeSpace (D, 1);
261 D->Type[D->Index++].C = T;
266 static void FixQualifiers (Type* DataType)
267 /* Apply several fixes to qualifiers */
272 /* Using typedefs, it is possible to generate declarations that have
273 * type qualifiers attached to an array, not the element type. Go and
278 while (T->C != T_END) {
279 if (IsTypeArray (T)) {
280 /* Extract any type qualifiers */
281 Q |= T->C & T_MASK_QUAL;
282 T->C = UnqualifiedType (T->C);
284 /* Add extracted type qualifiers here */
290 /* Q must be empty now */
291 CHECK (Q == T_QUAL_NONE);
293 /* Do some fixes on pointers and functions. */
295 while (T->C != T_END) {
298 /* Fastcall qualifier on the pointer? */
299 if (IsQualFastcall (T)) {
300 /* Pointer to function which is not fastcall? */
301 if (IsTypeFunc (T+1) && !IsQualFastcall (T+1)) {
302 /* Move the fastcall qualifier from the pointer to
305 T[0].C &= ~T_QUAL_FASTCALL;
306 T[1].C |= T_QUAL_FASTCALL;
308 Error ("Invalid `_fastcall__' qualifier for pointer");
312 /* Apply the default far and near qualifiers if none are given */
313 Q = (T[0].C & T_QUAL_ADDRSIZE);
314 if (Q == T_QUAL_NONE) {
315 /* No address size qualifiers specified */
316 if (IsTypeFunc (T+1)) {
317 /* Pointer to function. Use the qualifier from the function
318 * or the default if the function don't has one.
320 Q = (T[1].C & T_QUAL_ADDRSIZE);
321 if (Q == T_QUAL_NONE) {
322 Q = CodeAddrSizeQualifier ();
325 Q = DataAddrSizeQualifier ();
329 /* We have address size qualifiers. If followed by a function,
330 * apply these also to the function.
332 if (IsTypeFunc (T+1)) {
333 TypeCode FQ = (T[1].C & T_QUAL_ADDRSIZE);
334 if (FQ == T_QUAL_NONE) {
336 } else if (FQ != Q) {
337 Error ("Address size qualifier mismatch");
338 T[1].C = (T[1].C & ~T_QUAL_ADDRSIZE) | Q;
343 } else if (IsTypeFunc (T)) {
345 /* Apply the default far and near qualifiers if none are given */
346 if ((T[0].C & T_QUAL_ADDRSIZE) == 0) {
347 T[0].C |= CodeAddrSizeQualifier ();
357 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
358 /* Parse a storage class */
360 /* Assume we're using an explicit storage class */
361 D->Flags &= ~DS_DEF_STORAGE;
363 /* Check the storage class given */
364 switch (CurTok.Tok) {
367 D->StorageClass = SC_EXTERN | SC_STATIC;
372 D->StorageClass = SC_STATIC;
377 D->StorageClass = SC_REGISTER | SC_STATIC;
382 D->StorageClass = SC_AUTO;
387 D->StorageClass = SC_TYPEDEF;
392 /* No storage class given, use default */
393 D->Flags |= DS_DEF_STORAGE;
394 D->StorageClass = DefStorage;
401 static void ParseEnumDecl (void)
402 /* Process an enum declaration . */
407 /* Accept forward definitions */
408 if (CurTok.Tok != TOK_LCURLY) {
412 /* Skip the opening curly brace */
415 /* Read the enum tags */
417 while (CurTok.Tok != TOK_RCURLY) {
419 /* We expect an identifier */
420 if (CurTok.Tok != TOK_IDENT) {
421 Error ("Identifier expected");
425 /* Remember the identifier and skip it */
426 strcpy (Ident, CurTok.Ident);
429 /* Check for an assigned value */
430 if (CurTok.Tok == TOK_ASSIGN) {
433 ConstAbsIntExpr (hie1, &Expr);
437 /* Add an entry to the symbol table */
438 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
440 /* Check for end of definition */
441 if (CurTok.Tok != TOK_COMMA)
450 static int ParseFieldWidth (Declaration* Decl)
451 /* Parse an optional field width. Returns -1 if no field width is speficied,
452 * otherwise the width of the field.
457 if (CurTok.Tok != TOK_COLON) {
458 /* No bit-field declaration */
464 ConstAbsIntExpr (hie1, &Expr);
466 Error ("Negative width in bit-field");
469 if (Expr.IVal > (int) INT_BITS) {
470 Error ("Width of bit-field exceeds its type");
473 if (Expr.IVal == 0 && Decl->Ident[0] != '\0') {
474 Error ("Zero width for named bit-field");
477 if (!IsTypeInt (Decl->Type)) {
478 /* Only integer types may be used for bit-fields */
479 Error ("Bit-field has invalid type");
483 /* Return the field width */
484 return (int) Expr.IVal;
489 static SymEntry* StructOrUnionForwardDecl (const char* Name)
490 /* Handle a struct or union forward decl */
492 /* Try to find a struct with the given name. If there is none,
493 * insert a forward declaration into the current lexical level.
495 SymEntry* Entry = FindTagSym (Name);
497 Entry = AddStructSym (Name, 0, 0);
498 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) != SC_STRUCT) {
499 /* Already defined in the level, but no struct */
500 Error ("Symbol `%s' is already different kind", Name);
507 static SymEntry* ParseUnionDecl (const char* Name)
508 /* Parse a union declaration. */
513 int FieldWidth; /* Width in bits, -1 if not a bit-field */
518 if (CurTok.Tok != TOK_LCURLY) {
519 /* Just a forward declaration. */
520 return StructOrUnionForwardDecl (Name);
523 /* Add a forward declaration for the struct in the current lexical level */
524 Entry = AddStructSym (Name, 0, 0);
526 /* Skip the curly brace */
529 /* Enter a new lexical level for the struct */
532 /* Parse union fields */
534 while (CurTok.Tok != TOK_RCURLY) {
536 /* Get the type of the entry */
538 InitDeclSpec (&Spec);
539 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
541 /* Read fields with this type */
546 /* Get type and name of the struct field */
547 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
549 /* Check for a bit-field declaration */
550 FieldWidth = ParseFieldWidth (&Decl);
552 /* Ignore zero sized bit fields in a union */
553 if (FieldWidth == 0) {
557 /* Check for fields without a name */
558 if (Decl.Ident[0] == '\0') {
559 /* Any field without a name is legal but useless in a union */
560 Warning ("Declaration does not declare anything");
565 FieldSize = CheckedSizeOf (Decl.Type);
566 if (FieldSize > UnionSize) {
567 UnionSize = FieldSize;
570 /* Add a field entry to the table. */
571 if (FieldWidth > 0) {
572 AddBitField (Decl.Ident, 0, 0, FieldWidth);
574 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, 0);
577 NextMember: if (CurTok.Tok != TOK_COMMA) {
585 /* Skip the closing brace */
588 /* Remember the symbol table and leave the struct level */
589 FieldTab = GetSymTab ();
592 /* Make a real entry from the forward decl and return it */
593 return AddStructSym (Name, UnionSize, FieldTab);
598 static SymEntry* ParseStructDecl (const char* Name)
599 /* Parse a struct declaration. */
605 int BitOffs; /* Bit offset for bit-fields */
606 int FieldWidth; /* Width in bits, -1 if not a bit-field */
611 if (CurTok.Tok != TOK_LCURLY) {
612 /* Just a forward declaration. */
613 return StructOrUnionForwardDecl (Name);
616 /* Add a forward declaration for the struct in the current lexical level */
617 Entry = AddStructSym (Name, 0, 0);
619 /* Skip the curly brace */
622 /* Enter a new lexical level for the struct */
625 /* Parse struct fields */
629 while (CurTok.Tok != TOK_RCURLY) {
631 /* Get the type of the entry */
633 InitDeclSpec (&Spec);
634 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
636 /* Read fields with this type */
641 /* If we had a flexible array member before, no other fields can
644 if (FlexibleMember) {
645 Error ("Flexible array member must be last field");
646 FlexibleMember = 0; /* Avoid further errors */
649 /* Get type and name of the struct field */
650 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
652 /* Check for a bit-field declaration */
653 FieldWidth = ParseFieldWidth (&Decl);
655 /* If this is not a bit field, or the bit field is too large for
656 * the remainder of the current member, or we have a bit field
657 * with width zero, align the struct to the next member
660 if (FieldWidth <= 0 || (BitOffs + FieldWidth) > (int) INT_BITS) {
661 StructSize += SIZEOF_INT;
666 /* Apart from the above, a bit field with width 0 is not processed
669 if (FieldWidth == 0) {
673 /* Check for fields without names */
674 if (Decl.Ident[0] == '\0') {
675 if (FieldWidth < 0) {
676 /* A non bit-field without a name is legal but useless */
677 Warning ("Declaration does not declare anything");
680 /* A bit-field without a name will just increase the
683 BitOffs += FieldWidth;
688 /* Byte offset of this member is the current struct size plus any
689 * full bytes from the bit offset in case of bit-fields.
691 Offs = StructSize + (BitOffs / CHAR_BITS);
693 /* Check if this field is a flexible array member, and
694 * calculate the size of the field.
696 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
697 /* Array with unspecified size */
698 if (StructSize == 0) {
699 Error ("Flexible array member cannot be first struct field");
702 /* Assume zero for size calculations */
703 SetElementCount (Decl.Type, FLEXIBLE);
704 } else if (FieldWidth < 0) {
705 StructSize += CheckedSizeOf (Decl.Type);
708 /* Add a field entry to the table */
709 if (FieldWidth > 0) {
710 AddBitField (Decl.Ident, Offs, BitOffs % CHAR_BITS, FieldWidth);
711 BitOffs += FieldWidth;
713 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
716 NextMember: if (CurTok.Tok != TOK_COMMA) {
724 /* If we have bits from bit-fields left, add them to the size. */
726 StructSize += ((BitOffs + CHAR_BITS - 1) / CHAR_BITS);
729 /* Skip the closing brace */
732 /* Remember the symbol table and leave the struct level */
733 FieldTab = GetSymTab ();
736 /* Make a real entry from the forward decl and return it */
737 return AddStructSym (Name, StructSize, FieldTab);
742 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
743 /* Parse a type specificier */
748 /* Assume we have an explicit type */
749 D->Flags &= ~DS_DEF_TYPE;
751 /* Read type qualifiers if we have any */
752 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
754 /* Look at the data type */
755 switch (CurTok.Tok) {
759 D->Type[0].C = T_VOID;
760 D->Type[1].C = T_END;
765 D->Type[0].C = GetDefaultChar();
766 D->Type[1].C = T_END;
771 if (CurTok.Tok == TOK_UNSIGNED) {
774 D->Type[0].C = T_ULONG;
775 D->Type[1].C = T_END;
779 D->Type[0].C = T_LONG;
780 D->Type[1].C = T_END;
786 if (CurTok.Tok == TOK_UNSIGNED) {
789 D->Type[0].C = T_USHORT;
790 D->Type[1].C = T_END;
794 D->Type[0].C = T_SHORT;
795 D->Type[1].C = T_END;
801 D->Type[0].C = T_INT;
802 D->Type[1].C = T_END;
807 switch (CurTok.Tok) {
811 D->Type[0].C = T_SCHAR;
812 D->Type[1].C = T_END;
818 D->Type[0].C = T_SHORT;
819 D->Type[1].C = T_END;
825 D->Type[0].C = T_LONG;
826 D->Type[1].C = T_END;
834 D->Type[0].C = T_INT;
835 D->Type[1].C = T_END;
842 switch (CurTok.Tok) {
846 D->Type[0].C = T_UCHAR;
847 D->Type[1].C = T_END;
853 D->Type[0].C = T_USHORT;
854 D->Type[1].C = T_END;
860 D->Type[0].C = T_ULONG;
861 D->Type[1].C = T_END;
869 D->Type[0].C = T_UINT;
870 D->Type[1].C = T_END;
877 D->Type[0].C = T_FLOAT;
878 D->Type[1].C = T_END;
883 D->Type[0].C = T_DOUBLE;
884 D->Type[1].C = T_END;
890 if (CurTok.Tok == TOK_IDENT) {
891 strcpy (Ident, CurTok.Ident);
894 AnonName (Ident, "union");
896 /* Remember we have an extra type decl */
897 D->Flags |= DS_EXTRA_TYPE;
898 /* Declare the union in the current scope */
899 Entry = ParseUnionDecl (Ident);
900 /* Encode the union entry into the type */
901 D->Type[0].C = T_UNION;
902 SetSymEntry (D->Type, Entry);
903 D->Type[1].C = T_END;
909 if (CurTok.Tok == TOK_IDENT) {
910 strcpy (Ident, CurTok.Ident);
913 AnonName (Ident, "struct");
915 /* Remember we have an extra type decl */
916 D->Flags |= DS_EXTRA_TYPE;
917 /* Declare the struct in the current scope */
918 Entry = ParseStructDecl (Ident);
919 /* Encode the struct entry into the type */
920 D->Type[0].C = T_STRUCT;
921 SetSymEntry (D->Type, Entry);
922 D->Type[1].C = T_END;
927 if (CurTok.Tok != TOK_LCURLY) {
929 if (CurTok.Tok == TOK_IDENT) {
930 /* Find an entry with this name */
931 Entry = FindTagSym (CurTok.Ident);
933 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
934 Error ("Symbol `%s' is already different kind", Entry->Name);
937 /* Insert entry into table ### */
939 /* Skip the identifier */
942 Error ("Identifier expected");
945 /* Remember we have an extra type decl */
946 D->Flags |= DS_EXTRA_TYPE;
947 /* Parse the enum decl */
949 D->Type[0].C = T_INT;
950 D->Type[1].C = T_END;
954 Entry = FindSym (CurTok.Ident);
955 if (Entry && SymIsTypeDef (Entry)) {
958 TypeCopy (D->Type, Entry->Type);
965 Error ("Type expected");
966 D->Type[0].C = T_INT;
967 D->Type[1].C = T_END;
969 D->Flags |= DS_DEF_TYPE;
970 D->Type[0].C = (TypeCode) Default;
971 D->Type[1].C = T_END;
976 /* There may also be qualifiers *after* the initial type */
977 D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
982 static Type* ParamTypeCvt (Type* T)
983 /* If T is an array, convert it to a pointer else do nothing. Return the
987 if (IsTypeArray (T)) {
995 static void ParseOldStyleParamList (FuncDesc* F)
996 /* Parse an old style (K&R) parameter list */
999 while (CurTok.Tok != TOK_RPAREN) {
1001 /* List of identifiers expected */
1002 if (CurTok.Tok != TOK_IDENT) {
1003 Error ("Identifier expected");
1006 /* Create a symbol table entry with type int */
1007 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1009 /* Count arguments */
1012 /* Skip the identifier */
1015 /* Check for more parameters */
1016 if (CurTok.Tok == TOK_COMMA) {
1023 /* Skip right paren. We must explicitly check for one here, since some of
1024 * the breaks above bail out without checking.
1028 /* An optional list of type specifications follows */
1029 while (CurTok.Tok != TOK_LCURLY) {
1033 /* Read the declaration specifier */
1034 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1036 /* We accept only auto and register as storage class specifiers, but
1037 * we ignore all this, since we use auto anyway.
1039 if ((Spec.StorageClass & SC_AUTO) == 0 &&
1040 (Spec.StorageClass & SC_REGISTER) == 0) {
1041 Error ("Illegal storage class");
1044 /* Parse a comma separated variable list */
1049 /* Read the parameter */
1050 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1051 if (Decl.Ident[0] != '\0') {
1053 /* We have a name given. Search for the symbol */
1054 SymEntry* Sym = FindLocalSym (Decl.Ident);
1056 /* Check if we already changed the type for this
1059 if (Sym->Flags & SC_DEFTYPE) {
1060 /* Found it, change the default type to the one given */
1061 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1062 /* Reset the "default type" flag */
1063 Sym->Flags &= ~SC_DEFTYPE;
1065 /* Type has already been changed */
1066 Error ("Redefinition for parameter `%s'", Sym->Name);
1069 Error ("Unknown identifier: `%s'", Decl.Ident);
1073 if (CurTok.Tok == TOK_COMMA) {
1081 /* Variable list must be semicolon terminated */
1088 static void ParseAnsiParamList (FuncDesc* F)
1089 /* Parse a new style (ANSI) parameter list */
1092 while (CurTok.Tok != TOK_RPAREN) {
1098 /* Allow an ellipsis as last parameter */
1099 if (CurTok.Tok == TOK_ELLIPSIS) {
1101 F->Flags |= FD_VARIADIC;
1105 /* Read the declaration specifier */
1106 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1108 /* We accept only auto and register as storage class specifiers */
1109 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1110 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1111 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1112 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1114 Error ("Illegal storage class");
1115 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1118 /* Allow parameters without a name, but remember if we had some to
1119 * eventually print an error message later.
1121 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1122 if (Decl.Ident[0] == '\0') {
1124 /* Unnamed symbol. Generate a name that is not user accessible,
1125 * then handle the symbol normal.
1127 AnonName (Decl.Ident, "param");
1128 F->Flags |= FD_UNNAMED_PARAMS;
1130 /* Clear defined bit on nonames */
1131 Decl.StorageClass &= ~SC_DEF;
1134 /* Parse an attribute ### */
1135 ParseAttribute (&Decl, &Attr);
1137 /* Create a symbol table entry */
1138 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1140 /* Count arguments */
1143 /* Check for more parameters */
1144 if (CurTok.Tok == TOK_COMMA) {
1151 /* Skip right paren. We must explicitly check for one here, since some of
1152 * the breaks above bail out without checking.
1156 /* Check if this is a function definition */
1157 if (CurTok.Tok == TOK_LCURLY) {
1158 /* Print an error if we have unnamed parameters and cc65 extensions
1161 if (IS_Get (&Standard) != STD_CC65 &&
1162 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
1163 Error ("Parameter name omitted");
1170 static FuncDesc* ParseFuncDecl (void)
1171 /* Parse the argument list of a function. */
1176 /* Create a new function descriptor */
1177 FuncDesc* F = NewFuncDesc ();
1179 /* Enter a new lexical level */
1180 EnterFunctionLevel ();
1182 /* Check for several special parameter lists */
1183 if (CurTok.Tok == TOK_RPAREN) {
1184 /* Parameter list is empty */
1185 F->Flags |= (FD_EMPTY | FD_VARIADIC);
1186 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1187 /* Parameter list declared as void */
1189 F->Flags |= FD_VOID_PARAM;
1190 } else if (CurTok.Tok == TOK_IDENT &&
1191 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1192 /* If the identifier is a typedef, we have a new style parameter list,
1193 * if it's some other identifier, it's an old style parameter list.
1195 Sym = FindSym (CurTok.Ident);
1196 if (Sym == 0 || !SymIsTypeDef (Sym)) {
1197 /* Old style (K&R) function. */
1198 F->Flags |= FD_OLDSTYLE;
1203 if ((F->Flags & FD_OLDSTYLE) == 0) {
1204 /* New style function */
1205 ParseAnsiParamList (F);
1207 /* Old style function */
1208 ParseOldStyleParamList (F);
1211 /* Remember the last function parameter. We need it later for several
1212 * purposes, for example when passing stuff to fastcall functions. Since
1213 * more symbols are added to the table, it is easier if we remember it
1214 * now, since it is currently the last entry in the symbol table.
1216 F->LastParam = GetSymTab()->SymTail;
1218 /* Assign offsets. If the function has a variable parameter list,
1219 * there's one additional byte (the arg size).
1221 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1224 unsigned Size = CheckedSizeOf (Sym->Type);
1225 if (SymIsRegVar (Sym)) {
1226 Sym->V.R.SaveOffs = Offs;
1231 F->ParamSize += Size;
1235 /* Leave the lexical level remembering the symbol tables */
1236 RememberFunctionLevel (F);
1238 /* Return the function descriptor */
1244 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1245 /* Recursively process declarators. Build a type array in reverse order. */
1247 /* Read optional function or pointer qualifiers. These modify the
1248 * identifier or token to the right. For convenience, we allow the fastcall
1249 * qualifier also for pointers here. If it is a pointer-to-function, the
1250 * qualifier will later be transfered to the function itself. If it's a
1251 * pointer to something else, it will be flagged as an error.
1253 TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL);
1255 /* Pointer to something */
1256 if (CurTok.Tok == TOK_STAR) {
1261 /* Allow const, restrict and volatile qualifiers */
1262 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1264 /* Parse the type, the pointer points to */
1265 Declarator (Spec, D, Mode);
1268 AddTypeToDeclaration (D, T_PTR | Qualifiers);
1272 if (CurTok.Tok == TOK_LPAREN) {
1274 Declarator (Spec, D, Mode);
1277 /* Things depend on Mode now:
1278 * - Mode == DM_NEED_IDENT means:
1279 * we *must* have a type and a variable identifer.
1280 * - Mode == DM_NO_IDENT means:
1281 * we must have a type but no variable identifer
1282 * (if there is one, it's not read).
1283 * - Mode == DM_ACCEPT_IDENT means:
1284 * we *may* have an identifier. If there is an identifier,
1285 * it is read, but it is no error, if there is none.
1287 if (Mode == DM_NO_IDENT) {
1289 } else if (CurTok.Tok == TOK_IDENT) {
1290 strcpy (D->Ident, CurTok.Ident);
1293 if (Mode == DM_NEED_IDENT) {
1294 Error ("Identifier expected");
1300 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1301 if (CurTok.Tok == TOK_LPAREN) {
1303 /* Function declaration */
1306 /* Skip the opening paren */
1309 /* Parse the function declaration */
1310 F = ParseFuncDecl ();
1312 /* We cannot specify fastcall for variadic functions */
1313 if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1314 Error ("Variadic functions cannot be `__fastcall'");
1315 Qualifiers &= ~T_QUAL_FASTCALL;
1318 /* Add the function type. Be sure to bounds check the type buffer */
1319 NeedTypeSpace (D, 1);
1320 D->Type[D->Index].C = T_FUNC | Qualifiers;
1321 D->Type[D->Index].A.P = F;
1324 /* Qualifiers now used */
1325 Qualifiers = T_QUAL_NONE;
1328 /* Array declaration. */
1329 long Size = UNSPECIFIED;
1331 /* We cannot have any qualifiers for an array */
1332 if (Qualifiers != T_QUAL_NONE) {
1333 Error ("Invalid qualifiers for array");
1334 Qualifiers = T_QUAL_NONE;
1337 /* Skip the left bracket */
1340 /* Read the size if it is given */
1341 if (CurTok.Tok != TOK_RBRACK) {
1343 ConstAbsIntExpr (hie1, &Expr);
1344 if (Expr.IVal <= 0) {
1345 if (D->Ident[0] != '\0') {
1346 Error ("Size of array `%s' is invalid", D->Ident);
1348 Error ("Size of array is invalid");
1355 /* Skip the right bracket */
1358 /* Add the array type with the size to the type */
1359 NeedTypeSpace (D, 1);
1360 D->Type[D->Index].C = T_ARRAY;
1361 D->Type[D->Index].A.L = Size;
1366 /* If we have remaining qualifiers, flag them as invalid */
1367 if (Qualifiers & T_QUAL_NEAR) {
1368 Error ("Invalid `__near__' qualifier");
1370 if (Qualifiers & T_QUAL_FAR) {
1371 Error ("Invalid `__far__' qualifier");
1373 if (Qualifiers & T_QUAL_FASTCALL) {
1374 Error ("Invalid `__fastcall__' qualifier");
1380 /*****************************************************************************/
1382 /*****************************************************************************/
1386 Type* ParseType (Type* T)
1387 /* Parse a complete type specification */
1392 /* Get a type without a default */
1393 InitDeclSpec (&Spec);
1394 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1396 /* Parse additional declarators */
1397 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1399 /* Copy the type to the target buffer */
1400 TypeCopy (T, Decl.Type);
1402 /* Return a pointer to the target buffer */
1408 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1409 /* Parse a variable, type or function declaration */
1411 /* Initialize the Declaration struct */
1412 InitDeclaration (D);
1414 /* Get additional declarators and the identifier */
1415 Declarator (Spec, D, Mode);
1417 /* Add the base type. */
1418 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1419 TypeCopy (D->Type + D->Index, Spec->Type);
1421 /* Use the storage class from the declspec */
1422 D->StorageClass = Spec->StorageClass;
1424 /* Do several fixes on qualifiers */
1425 FixQualifiers (D->Type);
1427 /* If we have a function, add a special storage class */
1428 if (IsTypeFunc (D->Type)) {
1429 D->StorageClass |= SC_FUNC;
1432 /* Check several things for function or function pointer types */
1433 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1435 /* A function. Check the return type */
1436 Type* RetType = GetFuncReturn (D->Type);
1438 /* Functions may not return functions or arrays */
1439 if (IsTypeFunc (RetType)) {
1440 Error ("Functions are not allowed to return functions");
1441 } else if (IsTypeArray (RetType)) {
1442 Error ("Functions are not allowed to return arrays");
1445 /* The return type must not be qualified */
1446 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1448 if (GetType (RetType) == T_TYPE_VOID) {
1449 /* A qualified void type is always an error */
1450 Error ("function definition has qualified void return type");
1452 /* For others, qualifiers are ignored */
1453 Warning ("type qualifiers ignored on function return type");
1454 RetType[0].C = UnqualifiedType (RetType[0].C);
1458 /* Warn about an implicit int return in the function */
1459 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1460 RetType[0].C == T_INT && RetType[1].C == T_END) {
1461 /* Function has an implicit int return. Output a warning if we don't
1462 * have the C89 standard enabled explicitly.
1464 if (IS_Get (&Standard) >= STD_C99) {
1465 Warning ("Implicit `int' return type is an obsolete feature");
1467 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1472 /* For anthing that is not a function or typedef, check for an implicit
1475 if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1476 (D->StorageClass & SC_TYPEDEF) != SC_TYPEDEF) {
1477 /* If the standard was not set explicitly to C89, print a warning
1478 * for variables with implicit int type.
1480 if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1481 Warning ("Implicit `int' is an obsolete feature");
1485 /* Check the size of the generated type */
1486 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1487 unsigned Size = SizeOf (D->Type);
1488 if (Size >= 0x10000) {
1489 if (D->Ident[0] != '\0') {
1490 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1492 Error ("Invalid size in declaration (0x%06X)", Size);
1501 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1502 /* Parse a declaration specification */
1504 TypeCode Qualifiers;
1506 /* Initialize the DeclSpec struct */
1509 /* There may be qualifiers *before* the storage class specifier */
1510 Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1512 /* Now get the storage class specifier for this declaration */
1513 ParseStorageClass (D, DefStorage);
1515 /* Parse the type specifiers passing any initial type qualifiers */
1516 ParseTypeSpec (D, DefType, Qualifiers);
1521 void CheckEmptyDecl (const DeclSpec* D)
1522 /* Called after an empty type declaration (that is, a type declaration without
1523 * a variable). Checks if the declaration does really make sense and issues a
1527 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1528 Warning ("Useless declaration");
1534 static void SkipInitializer (unsigned BracesExpected)
1535 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1536 * smart so we don't have too many following errors.
1539 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1540 switch (CurTok.Tok) {
1541 case TOK_RCURLY: --BracesExpected; break;
1542 case TOK_LCURLY: ++BracesExpected; break;
1551 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1552 /* Accept any number of opening curly braces around an initialization, skip
1553 * them and return the number. If the number of curly braces is less than
1554 * BracesNeeded, issue a warning.
1557 unsigned BraceCount = 0;
1558 while (CurTok.Tok == TOK_LCURLY) {
1562 if (BraceCount < BracesNeeded) {
1563 Error ("`{' expected");
1570 static void ClosingCurlyBraces (unsigned BracesExpected)
1571 /* Accept and skip the given number of closing curly braces together with
1572 * an optional comma. Output an error messages, if the input does not contain
1573 * the expected number of braces.
1576 while (BracesExpected) {
1577 if (CurTok.Tok == TOK_RCURLY) {
1579 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1583 Error ("`}' expected");
1592 static void DefineData (ExprDesc* Expr)
1593 /* Output a data definition for the given expression */
1595 switch (ED_GetLoc (Expr)) {
1598 /* Absolute: numeric address or const */
1599 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1603 /* Global variable */
1604 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1609 /* Static variable or literal in the literal pool */
1610 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1613 case E_LOC_REGISTER:
1614 /* Register variable. Taking the address is usually not
1617 if (IS_Get (&AllowRegVarAddr) == 0) {
1618 Error ("Cannot take the address of a register variable");
1620 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1626 Error ("Non constant initializer");
1630 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1636 static unsigned ParseScalarInit (Type* T)
1637 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1641 /* Optional opening brace */
1642 unsigned BraceCount = OpeningCurlyBraces (0);
1644 /* We warn if an initializer for a scalar contains braces, because this is
1645 * quite unusual and often a sign for some problem in the input.
1647 if (BraceCount > 0) {
1648 Warning ("Braces around scalar initializer");
1651 /* Get the expression and convert it to the target type */
1652 ConstExpr (hie1, &ED);
1653 TypeConversion (&ED, T);
1655 /* Output the data */
1658 /* Close eventually opening braces */
1659 ClosingCurlyBraces (BraceCount);
1667 static unsigned ParsePointerInit (Type* T)
1668 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1670 /* Optional opening brace */
1671 unsigned BraceCount = OpeningCurlyBraces (0);
1675 ConstExpr (hie1, &ED);
1676 TypeConversion (&ED, T);
1678 /* Output the data */
1681 /* Close eventually opening braces */
1682 ClosingCurlyBraces (BraceCount);
1690 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1691 /* Parse initializaton for arrays. Return the number of data bytes. */
1695 /* Get the array data */
1696 Type* ElementType = GetElementType (T);
1697 unsigned ElementSize = CheckedSizeOf (ElementType);
1698 long ElementCount = GetElementCount (T);
1700 /* Special handling for a character array initialized by a literal */
1701 if (IsTypeChar (ElementType) &&
1702 (CurTok.Tok == TOK_SCONST ||
1703 (CurTok.Tok == TOK_LCURLY && NextTok.Tok == TOK_SCONST))) {
1705 /* Char array initialized by string constant */
1709 /* If we initializer is enclosed in brackets, remember this fact and
1710 * skip the opening bracket.
1712 NeedParen = (CurTok.Tok == TOK_LCURLY);
1717 /* Get the initializer string and its size */
1718 Str = GetLiteral (CurTok.IVal);
1719 Count = GetLiteralPoolOffs () - CurTok.IVal;
1721 /* Translate into target charset */
1722 TranslateLiteralPool (CurTok.IVal);
1724 /* If the array is one too small for the string literal, omit the
1727 if (ElementCount != UNSPECIFIED &&
1728 ElementCount != FLEXIBLE &&
1729 Count == ElementCount + 1) {
1730 /* Omit the trailing zero */
1734 /* Output the data */
1735 g_defbytes (Str, Count);
1737 /* Remove string from pool */
1738 ResetLiteralPoolOffs (CurTok.IVal);
1741 /* If the initializer was enclosed in curly braces, we need a closing
1753 /* Initialize the array members */
1755 while (CurTok.Tok != TOK_RCURLY) {
1756 /* Flexible array members may not be initialized within
1757 * an array (because the size of each element may differ
1760 ParseInitInternal (ElementType, 0);
1762 if (CurTok.Tok != TOK_COMMA)
1767 /* Closing curly braces */
1771 if (ElementCount == UNSPECIFIED) {
1772 /* Number of elements determined by initializer */
1773 SetElementCount (T, Count);
1774 ElementCount = Count;
1775 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1776 /* In non ANSI mode, allow initialization of flexible array
1779 ElementCount = Count;
1780 } else if (Count < ElementCount) {
1781 g_zerobytes ((ElementCount - Count) * ElementSize);
1782 } else if (Count > ElementCount) {
1783 Error ("Too many initializers");
1785 return ElementCount * ElementSize;
1790 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1791 /* Parse initialization of a struct or union. Return the number of data bytes. */
1795 unsigned StructSize;
1799 /* Consume the opening curly brace */
1802 /* Get a pointer to the struct entry from the type */
1803 Entry = GetSymEntry (T);
1805 /* Get the size of the struct from the symbol table entry */
1806 StructSize = Entry->V.S.Size;
1808 /* Check if this struct definition has a field table. If it doesn't, it
1809 * is an incomplete definition.
1811 Tab = Entry->V.S.SymTab;
1813 Error ("Cannot initialize variables with incomplete type");
1814 /* Try error recovery */
1815 SkipInitializer (1);
1816 /* Nothing initialized */
1820 /* Get a pointer to the list of symbols */
1821 Entry = Tab->SymHead;
1823 /* Initialize fields */
1825 while (CurTok.Tok != TOK_RCURLY) {
1827 Error ("Too many initializers");
1828 SkipInitializer (1);
1831 /* Parse initialization of one field. Flexible array members may
1832 * only be initialized if they are the last field (or part of the
1833 * last struct field).
1835 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1836 Entry = Entry->NextSym;
1837 if (CurTok.Tok != TOK_COMMA)
1842 /* Consume the closing curly brace */
1845 /* If there are struct fields left, reserve additional storage */
1846 if (Size < StructSize) {
1847 g_zerobytes (StructSize - Size);
1851 /* Return the actual number of bytes initialized. This number may be
1852 * larger than StructSize if flexible array members are present and were
1853 * initialized (possible in non ANSI mode).
1860 static unsigned ParseVoidInit (void)
1861 /* Parse an initialization of a void variable (special cc65 extension).
1862 * Return the number of bytes initialized.
1871 /* Allow an arbitrary list of values */
1874 ConstExpr (hie1, &Expr);
1875 switch (UnqualifiedType (Expr.Type[0].C)) {
1879 if (ED_IsConstAbsInt (&Expr)) {
1880 /* Make it byte sized */
1884 Size += SIZEOF_CHAR;
1893 if (ED_IsConstAbsInt (&Expr)) {
1894 /* Make it word sized */
1895 Expr.IVal &= 0xFFFF;
1903 if (ED_IsConstAbsInt (&Expr)) {
1904 /* Make it dword sized */
1905 Expr.IVal &= 0xFFFFFFFF;
1908 Size += SIZEOF_LONG;
1912 Error ("Illegal type in initialization");
1917 if (CurTok.Tok != TOK_COMMA) {
1922 } while (CurTok.Tok != TOK_RCURLY);
1927 /* Return the number of bytes initialized */
1933 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
1934 /* Parse initialization of variables. Return the number of data bytes. */
1936 switch (UnqualifiedType (T->C)) {
1948 return ParseScalarInit (T);
1951 return ParsePointerInit (T);
1954 return ParseArrayInit (T, AllowFlexibleMembers);
1958 return ParseStructInit (T, AllowFlexibleMembers);
1961 if (IS_Get (&Standard) == STD_CC65) {
1962 /* Special cc65 extension in non ANSI mode */
1963 return ParseVoidInit ();
1968 Error ("Illegal type");
1976 unsigned ParseInit (Type* T)
1977 /* Parse initialization of variables. Return the number of data bytes. */
1979 /* Parse the initialization. Flexible array members can only be initialized
1982 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
1984 /* The initialization may not generate code on global level, because code
1985 * outside function scope will never get executed.
1987 if (HaveGlobalCode ()) {
1988 Error ("Non constant initializers");
1989 RemoveGlobalCode ();
1992 /* Return the size needed for the initialization */