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 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;
198 /* We cannot have more than one address size far qualifier */
199 switch (Q & T_QUAL_ADDRSIZE) {
207 Error ("Cannot specify more than one address size qualifier");
208 Q &= ~T_QUAL_ADDRSIZE;
211 /* Return the qualifiers read */
217 static void OptionalInt (void)
218 /* Eat an optional "int" token */
220 if (CurTok.Tok == TOK_INT) {
228 static void OptionalSigned (void)
229 /* Eat an optional "signed" token */
231 if (CurTok.Tok == TOK_SIGNED) {
239 static void InitDeclSpec (DeclSpec* D)
240 /* Initialize the DeclSpec struct for use */
243 D->Type[0].C = T_END;
249 static void InitDeclaration (Declaration* D)
250 /* Initialize the Declaration struct for use */
253 D->Type[0].C = T_END;
259 static void NeedTypeSpace (Declaration* D, unsigned Count)
260 /* Check if there is enough space for Count type specifiers within D */
262 if (D->Index + Count >= MAXTYPELEN) {
263 /* We must call Fatal() here, since calling Error() will try to
264 * continue, and the declaration type is not correctly terminated
265 * in case we come here.
267 Fatal ("Too many type specifiers");
273 static void AddTypeToDeclaration (Declaration* D, TypeCode T)
274 /* Add a type specifier to the type of a declaration */
276 NeedTypeSpace (D, 1);
277 D->Type[D->Index++].C = T;
282 static void FixQualifiers (Type* DataType)
283 /* Apply several fixes to qualifiers */
288 /* Using typedefs, it is possible to generate declarations that have
289 * type qualifiers attached to an array, not the element type. Go and
294 while (T->C != T_END) {
295 if (IsTypeArray (T)) {
296 /* Extract any type qualifiers */
297 Q |= T->C & T_MASK_QUAL;
298 T->C = UnqualifiedType (T->C);
300 /* Add extracted type qualifiers here */
306 /* Q must be empty now */
307 CHECK (Q == T_QUAL_NONE);
309 /* Do some fixes on pointers and functions. */
311 while (T->C != T_END) {
314 /* Fastcall qualifier on the pointer? */
315 if (IsQualFastcall (T)) {
316 /* Pointer to function which is not fastcall? */
317 if (IsTypeFunc (T+1) && !IsQualFastcall (T+1)) {
318 /* Move the fastcall qualifier from the pointer to
321 T[0].C &= ~T_QUAL_FASTCALL;
322 T[1].C |= T_QUAL_FASTCALL;
324 Error ("Invalid `_fastcall__' qualifier for pointer");
328 /* Apply the default far and near qualifiers if none are given */
329 Q = (T[0].C & T_QUAL_ADDRSIZE);
330 if (Q == T_QUAL_NONE) {
331 /* No address size qualifiers specified */
332 if (IsTypeFunc (T+1)) {
333 /* Pointer to function. Use the qualifier from the function
334 * or the default if the function don't has one.
336 Q = (T[1].C & T_QUAL_ADDRSIZE);
337 if (Q == T_QUAL_NONE) {
338 Q = CodeAddrSizeQualifier ();
341 Q = DataAddrSizeQualifier ();
345 /* We have address size qualifiers. If followed by a function,
346 * apply these also to the function.
348 if (IsTypeFunc (T+1)) {
349 TypeCode FQ = (T[1].C & T_QUAL_ADDRSIZE);
350 if (FQ == T_QUAL_NONE) {
352 } else if (FQ != Q) {
353 Error ("Address size qualifier mismatch");
354 T[1].C = (T[1].C & ~T_QUAL_ADDRSIZE) | Q;
359 } else if (IsTypeFunc (T)) {
361 /* Apply the default far and near qualifiers if none are given */
362 if ((T[0].C & T_QUAL_ADDRSIZE) == 0) {
363 T[0].C |= CodeAddrSizeQualifier ();
373 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
374 /* Parse a storage class */
376 /* Assume we're using an explicit storage class */
377 D->Flags &= ~DS_DEF_STORAGE;
379 /* Check the storage class given */
380 switch (CurTok.Tok) {
383 D->StorageClass = SC_EXTERN | SC_STATIC;
388 D->StorageClass = SC_STATIC;
393 D->StorageClass = SC_REGISTER | SC_STATIC;
398 D->StorageClass = SC_AUTO;
403 D->StorageClass = SC_TYPEDEF;
408 /* No storage class given, use default */
409 D->Flags |= DS_DEF_STORAGE;
410 D->StorageClass = DefStorage;
417 static void ParseEnumDecl (void)
418 /* Process an enum declaration . */
423 /* Accept forward definitions */
424 if (CurTok.Tok != TOK_LCURLY) {
428 /* Skip the opening curly brace */
431 /* Read the enum tags */
433 while (CurTok.Tok != TOK_RCURLY) {
435 /* We expect an identifier */
436 if (CurTok.Tok != TOK_IDENT) {
437 Error ("Identifier expected");
441 /* Remember the identifier and skip it */
442 strcpy (Ident, CurTok.Ident);
445 /* Check for an assigned value */
446 if (CurTok.Tok == TOK_ASSIGN) {
449 ConstAbsIntExpr (hie1, &Expr);
453 /* Add an entry to the symbol table */
454 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
456 /* Check for end of definition */
457 if (CurTok.Tok != TOK_COMMA)
466 static int ParseFieldWidth (Declaration* Decl)
467 /* Parse an optional field width. Returns -1 if no field width is speficied,
468 * otherwise the width of the field.
473 if (CurTok.Tok != TOK_COLON) {
474 /* No bit-field declaration */
480 ConstAbsIntExpr (hie1, &Expr);
482 Error ("Negative width in bit-field");
485 if (Expr.IVal > (int) INT_BITS) {
486 Error ("Width of bit-field exceeds its type");
489 if (Expr.IVal == 0 && Decl->Ident[0] != '\0') {
490 Error ("Zero width for named bit-field");
493 if (!IsTypeInt (Decl->Type)) {
494 /* Only integer types may be used for bit-fields */
495 Error ("Bit-field has invalid type");
499 /* Return the field width */
500 return (int) Expr.IVal;
505 static SymEntry* StructOrUnionForwardDecl (const char* Name)
506 /* Handle a struct or union forward decl */
508 /* Try to find a struct with the given name. If there is none,
509 * insert a forward declaration into the current lexical level.
511 SymEntry* Entry = FindTagSym (Name);
513 Entry = AddStructSym (Name, 0, 0);
514 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) != SC_STRUCT) {
515 /* Already defined in the level, but no struct */
516 Error ("Symbol `%s' is already different kind", Name);
523 static SymEntry* ParseUnionDecl (const char* Name)
524 /* Parse a union declaration. */
529 int FieldWidth; /* Width in bits, -1 if not a bit-field */
534 if (CurTok.Tok != TOK_LCURLY) {
535 /* Just a forward declaration. */
536 return StructOrUnionForwardDecl (Name);
539 /* Add a forward declaration for the struct in the current lexical level */
540 Entry = AddStructSym (Name, 0, 0);
542 /* Skip the curly brace */
545 /* Enter a new lexical level for the struct */
548 /* Parse union fields */
550 while (CurTok.Tok != TOK_RCURLY) {
552 /* Get the type of the entry */
554 InitDeclSpec (&Spec);
555 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
557 /* Read fields with this type */
562 /* Get type and name of the struct field */
563 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
565 /* Check for a bit-field declaration */
566 FieldWidth = ParseFieldWidth (&Decl);
568 /* Ignore zero sized bit fields in a union */
569 if (FieldWidth == 0) {
573 /* Check for fields without a name */
574 if (Decl.Ident[0] == '\0') {
575 /* Any field without a name is legal but useless in a union */
576 Warning ("Declaration does not declare anything");
581 FieldSize = CheckedSizeOf (Decl.Type);
582 if (FieldSize > UnionSize) {
583 UnionSize = FieldSize;
586 /* Add a field entry to the table. */
587 if (FieldWidth > 0) {
588 AddBitField (Decl.Ident, 0, 0, FieldWidth);
590 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, 0);
593 NextMember: if (CurTok.Tok != TOK_COMMA) {
601 /* Skip the closing brace */
604 /* Remember the symbol table and leave the struct level */
605 FieldTab = GetSymTab ();
608 /* Make a real entry from the forward decl and return it */
609 return AddStructSym (Name, UnionSize, FieldTab);
614 static SymEntry* ParseStructDecl (const char* Name)
615 /* Parse a struct declaration. */
620 int BitOffs; /* Bit offset for bit-fields */
621 int FieldWidth; /* Width in bits, -1 if not a bit-field */
626 if (CurTok.Tok != TOK_LCURLY) {
627 /* Just a forward declaration. */
628 return StructOrUnionForwardDecl (Name);
631 /* Add a forward declaration for the struct in the current lexical level */
632 Entry = AddStructSym (Name, 0, 0);
634 /* Skip the curly brace */
637 /* Enter a new lexical level for the struct */
640 /* Parse struct fields */
644 while (CurTok.Tok != TOK_RCURLY) {
646 /* Get the type of the entry */
648 InitDeclSpec (&Spec);
649 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
651 /* Read fields with this type */
657 /* If we had a flexible array member before, no other fields can
660 if (FlexibleMember) {
661 Error ("Flexible array member must be last field");
662 FlexibleMember = 0; /* Avoid further errors */
665 /* Get type and name of the struct field */
666 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
668 /* Check for a bit-field declaration */
669 FieldWidth = ParseFieldWidth (&Decl);
671 /* If this is not a bit field, or the bit field is too large for
672 * the remainder of the current member, or we have a bit field
673 * with width zero, align the struct to the next member by adding
674 * a member with an anonymous name.
677 if (FieldWidth <= 0 || (BitOffs + FieldWidth) > (int) INT_BITS) {
679 /* We need an anonymous name */
680 AnonName (Ident, "bit-field");
682 /* Add an anonymous bit-field that aligns to the next
685 AddBitField (Ident, StructSize, BitOffs, INT_BITS - BitOffs);
688 StructSize += SIZEOF_INT;
693 /* Apart from the above, a bit field with width 0 is not processed
696 if (FieldWidth == 0) {
700 /* Check for fields without names */
701 if (Decl.Ident[0] == '\0') {
702 if (FieldWidth < 0) {
703 /* A non bit-field without a name is legal but useless */
704 Warning ("Declaration does not declare anything");
707 /* A bit-field without a name will get an anonymous one */
708 AnonName (Decl.Ident, "bit-field");
712 /* Check if this field is a flexible array member, and
713 * calculate the size of the field.
715 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
716 /* Array with unspecified size */
717 if (StructSize == 0) {
718 Error ("Flexible array member cannot be first struct field");
721 /* Assume zero for size calculations */
722 SetElementCount (Decl.Type, FLEXIBLE);
725 /* Add a field entry to the table */
726 if (FieldWidth > 0) {
727 /* Add full byte from the bit offset to the variable offset.
728 * This simplifies handling he bit-field as a char type
731 unsigned Offs = StructSize + (BitOffs / CHAR_BITS);
732 AddBitField (Decl.Ident, Offs, BitOffs % CHAR_BITS, FieldWidth);
733 BitOffs += FieldWidth;
734 CHECK (BitOffs <= (int) INT_BITS);
735 if (BitOffs == INT_BITS) {
736 StructSize += SIZEOF_INT;
740 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, StructSize);
741 StructSize += CheckedSizeOf (Decl.Type);
744 NextMember: if (CurTok.Tok != TOK_COMMA) {
752 /* If we have bits from bit-fields left, add them to the size. */
754 StructSize += ((BitOffs + CHAR_BITS - 1) / CHAR_BITS);
757 /* Skip the closing brace */
760 /* Remember the symbol table and leave the struct level */
761 FieldTab = GetSymTab ();
764 /* Make a real entry from the forward decl and return it */
765 return AddStructSym (Name, StructSize, FieldTab);
770 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
771 /* Parse a type specificier */
776 /* Assume we have an explicit type */
777 D->Flags &= ~DS_DEF_TYPE;
779 /* Read type qualifiers if we have any */
780 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
782 /* Look at the data type */
783 switch (CurTok.Tok) {
787 D->Type[0].C = T_VOID;
788 D->Type[1].C = T_END;
793 D->Type[0].C = GetDefaultChar();
794 D->Type[1].C = T_END;
799 if (CurTok.Tok == TOK_UNSIGNED) {
802 D->Type[0].C = T_ULONG;
803 D->Type[1].C = T_END;
807 D->Type[0].C = T_LONG;
808 D->Type[1].C = T_END;
814 if (CurTok.Tok == TOK_UNSIGNED) {
817 D->Type[0].C = T_USHORT;
818 D->Type[1].C = T_END;
822 D->Type[0].C = T_SHORT;
823 D->Type[1].C = T_END;
829 D->Type[0].C = T_INT;
830 D->Type[1].C = T_END;
835 switch (CurTok.Tok) {
839 D->Type[0].C = T_SCHAR;
840 D->Type[1].C = T_END;
846 D->Type[0].C = T_SHORT;
847 D->Type[1].C = T_END;
853 D->Type[0].C = T_LONG;
854 D->Type[1].C = T_END;
862 D->Type[0].C = T_INT;
863 D->Type[1].C = T_END;
870 switch (CurTok.Tok) {
874 D->Type[0].C = T_UCHAR;
875 D->Type[1].C = T_END;
881 D->Type[0].C = T_USHORT;
882 D->Type[1].C = T_END;
888 D->Type[0].C = T_ULONG;
889 D->Type[1].C = T_END;
897 D->Type[0].C = T_UINT;
898 D->Type[1].C = T_END;
905 D->Type[0].C = T_FLOAT;
906 D->Type[1].C = T_END;
911 D->Type[0].C = T_DOUBLE;
912 D->Type[1].C = T_END;
918 if (CurTok.Tok == TOK_IDENT) {
919 strcpy (Ident, CurTok.Ident);
922 AnonName (Ident, "union");
924 /* Remember we have an extra type decl */
925 D->Flags |= DS_EXTRA_TYPE;
926 /* Declare the union in the current scope */
927 Entry = ParseUnionDecl (Ident);
928 /* Encode the union entry into the type */
929 D->Type[0].C = T_UNION;
930 SetSymEntry (D->Type, Entry);
931 D->Type[1].C = T_END;
937 if (CurTok.Tok == TOK_IDENT) {
938 strcpy (Ident, CurTok.Ident);
941 AnonName (Ident, "struct");
943 /* Remember we have an extra type decl */
944 D->Flags |= DS_EXTRA_TYPE;
945 /* Declare the struct in the current scope */
946 Entry = ParseStructDecl (Ident);
947 /* Encode the struct entry into the type */
948 D->Type[0].C = T_STRUCT;
949 SetSymEntry (D->Type, Entry);
950 D->Type[1].C = T_END;
955 if (CurTok.Tok != TOK_LCURLY) {
957 if (CurTok.Tok == TOK_IDENT) {
958 /* Find an entry with this name */
959 Entry = FindTagSym (CurTok.Ident);
961 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
962 Error ("Symbol `%s' is already different kind", Entry->Name);
965 /* Insert entry into table ### */
967 /* Skip the identifier */
970 Error ("Identifier expected");
973 /* Remember we have an extra type decl */
974 D->Flags |= DS_EXTRA_TYPE;
975 /* Parse the enum decl */
977 D->Type[0].C = T_INT;
978 D->Type[1].C = T_END;
982 Entry = FindSym (CurTok.Ident);
983 if (Entry && SymIsTypeDef (Entry)) {
986 TypeCopy (D->Type, Entry->Type);
993 Error ("Type expected");
994 D->Type[0].C = T_INT;
995 D->Type[1].C = T_END;
997 D->Flags |= DS_DEF_TYPE;
998 D->Type[0].C = (TypeCode) Default;
999 D->Type[1].C = T_END;
1004 /* There may also be qualifiers *after* the initial type */
1005 D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
1010 static Type* ParamTypeCvt (Type* T)
1011 /* If T is an array, convert it to a pointer else do nothing. Return the
1015 if (IsTypeArray (T)) {
1023 static void ParseOldStyleParamList (FuncDesc* F)
1024 /* Parse an old style (K&R) parameter list */
1027 while (CurTok.Tok != TOK_RPAREN) {
1029 /* List of identifiers expected */
1030 if (CurTok.Tok != TOK_IDENT) {
1031 Error ("Identifier expected");
1034 /* Create a symbol table entry with type int */
1035 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1037 /* Count arguments */
1040 /* Skip the identifier */
1043 /* Check for more parameters */
1044 if (CurTok.Tok == TOK_COMMA) {
1051 /* Skip right paren. We must explicitly check for one here, since some of
1052 * the breaks above bail out without checking.
1056 /* An optional list of type specifications follows */
1057 while (CurTok.Tok != TOK_LCURLY) {
1061 /* Read the declaration specifier */
1062 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1064 /* We accept only auto and register as storage class specifiers, but
1065 * we ignore all this, since we use auto anyway.
1067 if ((Spec.StorageClass & SC_AUTO) == 0 &&
1068 (Spec.StorageClass & SC_REGISTER) == 0) {
1069 Error ("Illegal storage class");
1072 /* Parse a comma separated variable list */
1077 /* Read the parameter */
1078 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1079 if (Decl.Ident[0] != '\0') {
1081 /* We have a name given. Search for the symbol */
1082 SymEntry* Sym = FindLocalSym (Decl.Ident);
1084 /* Check if we already changed the type for this
1087 if (Sym->Flags & SC_DEFTYPE) {
1088 /* Found it, change the default type to the one given */
1089 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1090 /* Reset the "default type" flag */
1091 Sym->Flags &= ~SC_DEFTYPE;
1093 /* Type has already been changed */
1094 Error ("Redefinition for parameter `%s'", Sym->Name);
1097 Error ("Unknown identifier: `%s'", Decl.Ident);
1101 if (CurTok.Tok == TOK_COMMA) {
1109 /* Variable list must be semicolon terminated */
1116 static void ParseAnsiParamList (FuncDesc* F)
1117 /* Parse a new style (ANSI) parameter list */
1120 while (CurTok.Tok != TOK_RPAREN) {
1126 /* Allow an ellipsis as last parameter */
1127 if (CurTok.Tok == TOK_ELLIPSIS) {
1129 F->Flags |= FD_VARIADIC;
1133 /* Read the declaration specifier */
1134 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1136 /* We accept only auto and register as storage class specifiers */
1137 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1138 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1139 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1140 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1142 Error ("Illegal storage class");
1143 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1146 /* Allow parameters without a name, but remember if we had some to
1147 * eventually print an error message later.
1149 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1150 if (Decl.Ident[0] == '\0') {
1152 /* Unnamed symbol. Generate a name that is not user accessible,
1153 * then handle the symbol normal.
1155 AnonName (Decl.Ident, "param");
1156 F->Flags |= FD_UNNAMED_PARAMS;
1158 /* Clear defined bit on nonames */
1159 Decl.StorageClass &= ~SC_DEF;
1162 /* Parse an attribute ### */
1163 ParseAttribute (&Decl, &Attr);
1165 /* Create a symbol table entry */
1166 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1168 /* Count arguments */
1171 /* Check for more parameters */
1172 if (CurTok.Tok == TOK_COMMA) {
1179 /* Skip right paren. We must explicitly check for one here, since some of
1180 * the breaks above bail out without checking.
1184 /* Check if this is a function definition */
1185 if (CurTok.Tok == TOK_LCURLY) {
1186 /* Print an error if we have unnamed parameters and cc65 extensions
1189 if (IS_Get (&Standard) != STD_CC65 &&
1190 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
1191 Error ("Parameter name omitted");
1198 static FuncDesc* ParseFuncDecl (void)
1199 /* Parse the argument list of a function. */
1204 /* Create a new function descriptor */
1205 FuncDesc* F = NewFuncDesc ();
1207 /* Enter a new lexical level */
1208 EnterFunctionLevel ();
1210 /* Check for several special parameter lists */
1211 if (CurTok.Tok == TOK_RPAREN) {
1212 /* Parameter list is empty */
1213 F->Flags |= (FD_EMPTY | FD_VARIADIC);
1214 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1215 /* Parameter list declared as void */
1217 F->Flags |= FD_VOID_PARAM;
1218 } else if (CurTok.Tok == TOK_IDENT &&
1219 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1220 /* If the identifier is a typedef, we have a new style parameter list,
1221 * if it's some other identifier, it's an old style parameter list.
1223 Sym = FindSym (CurTok.Ident);
1224 if (Sym == 0 || !SymIsTypeDef (Sym)) {
1225 /* Old style (K&R) function. */
1226 F->Flags |= FD_OLDSTYLE;
1231 if ((F->Flags & FD_OLDSTYLE) == 0) {
1232 /* New style function */
1233 ParseAnsiParamList (F);
1235 /* Old style function */
1236 ParseOldStyleParamList (F);
1239 /* Remember the last function parameter. We need it later for several
1240 * purposes, for example when passing stuff to fastcall functions. Since
1241 * more symbols are added to the table, it is easier if we remember it
1242 * now, since it is currently the last entry in the symbol table.
1244 F->LastParam = GetSymTab()->SymTail;
1246 /* Assign offsets. If the function has a variable parameter list,
1247 * there's one additional byte (the arg size).
1249 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1252 unsigned Size = CheckedSizeOf (Sym->Type);
1253 if (SymIsRegVar (Sym)) {
1254 Sym->V.R.SaveOffs = Offs;
1259 F->ParamSize += Size;
1263 /* Leave the lexical level remembering the symbol tables */
1264 RememberFunctionLevel (F);
1266 /* Return the function descriptor */
1272 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1273 /* Recursively process declarators. Build a type array in reverse order. */
1275 /* Read optional function or pointer qualifiers. These modify the
1276 * identifier or token to the right. For convenience, we allow the fastcall
1277 * qualifier also for pointers here. If it is a pointer-to-function, the
1278 * qualifier will later be transfered to the function itself. If it's a
1279 * pointer to something else, it will be flagged as an error.
1281 TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL);
1283 /* Pointer to something */
1284 if (CurTok.Tok == TOK_STAR) {
1289 /* Allow const, restrict and volatile qualifiers */
1290 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1292 /* Parse the type, the pointer points to */
1293 Declarator (Spec, D, Mode);
1296 AddTypeToDeclaration (D, T_PTR | Qualifiers);
1300 if (CurTok.Tok == TOK_LPAREN) {
1302 Declarator (Spec, D, Mode);
1305 /* Things depend on Mode now:
1306 * - Mode == DM_NEED_IDENT means:
1307 * we *must* have a type and a variable identifer.
1308 * - Mode == DM_NO_IDENT means:
1309 * we must have a type but no variable identifer
1310 * (if there is one, it's not read).
1311 * - Mode == DM_ACCEPT_IDENT means:
1312 * we *may* have an identifier. If there is an identifier,
1313 * it is read, but it is no error, if there is none.
1315 if (Mode == DM_NO_IDENT) {
1317 } else if (CurTok.Tok == TOK_IDENT) {
1318 strcpy (D->Ident, CurTok.Ident);
1321 if (Mode == DM_NEED_IDENT) {
1322 Error ("Identifier expected");
1328 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1329 if (CurTok.Tok == TOK_LPAREN) {
1331 /* Function declaration */
1334 /* Skip the opening paren */
1337 /* Parse the function declaration */
1338 F = ParseFuncDecl ();
1340 /* We cannot specify fastcall for variadic functions */
1341 if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1342 Error ("Variadic functions cannot be `__fastcall'");
1343 Qualifiers &= ~T_QUAL_FASTCALL;
1346 /* Add the function type. Be sure to bounds check the type buffer */
1347 NeedTypeSpace (D, 1);
1348 D->Type[D->Index].C = T_FUNC | Qualifiers;
1349 D->Type[D->Index].A.P = F;
1352 /* Qualifiers now used */
1353 Qualifiers = T_QUAL_NONE;
1356 /* Array declaration. */
1357 long Size = UNSPECIFIED;
1359 /* We cannot have any qualifiers for an array */
1360 if (Qualifiers != T_QUAL_NONE) {
1361 Error ("Invalid qualifiers for array");
1362 Qualifiers = T_QUAL_NONE;
1365 /* Skip the left bracket */
1368 /* Read the size if it is given */
1369 if (CurTok.Tok != TOK_RBRACK) {
1371 ConstAbsIntExpr (hie1, &Expr);
1372 if (Expr.IVal <= 0) {
1373 if (D->Ident[0] != '\0') {
1374 Error ("Size of array `%s' is invalid", D->Ident);
1376 Error ("Size of array is invalid");
1383 /* Skip the right bracket */
1386 /* Add the array type with the size to the type */
1387 NeedTypeSpace (D, 1);
1388 D->Type[D->Index].C = T_ARRAY;
1389 D->Type[D->Index].A.L = Size;
1394 /* If we have remaining qualifiers, flag them as invalid */
1395 if (Qualifiers & T_QUAL_NEAR) {
1396 Error ("Invalid `__near__' qualifier");
1398 if (Qualifiers & T_QUAL_FAR) {
1399 Error ("Invalid `__far__' qualifier");
1401 if (Qualifiers & T_QUAL_FASTCALL) {
1402 Error ("Invalid `__fastcall__' qualifier");
1408 /*****************************************************************************/
1410 /*****************************************************************************/
1414 Type* ParseType (Type* T)
1415 /* Parse a complete type specification */
1420 /* Get a type without a default */
1421 InitDeclSpec (&Spec);
1422 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1424 /* Parse additional declarators */
1425 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1427 /* Copy the type to the target buffer */
1428 TypeCopy (T, Decl.Type);
1430 /* Return a pointer to the target buffer */
1436 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1437 /* Parse a variable, type or function declaration */
1439 /* Initialize the Declaration struct */
1440 InitDeclaration (D);
1442 /* Get additional declarators and the identifier */
1443 Declarator (Spec, D, Mode);
1445 /* Add the base type. */
1446 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1447 TypeCopy (D->Type + D->Index, Spec->Type);
1449 /* Use the storage class from the declspec */
1450 D->StorageClass = Spec->StorageClass;
1452 /* Do several fixes on qualifiers */
1453 FixQualifiers (D->Type);
1455 /* If we have a function, add a special storage class */
1456 if (IsTypeFunc (D->Type)) {
1457 D->StorageClass |= SC_FUNC;
1460 /* Check several things for function or function pointer types */
1461 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1463 /* A function. Check the return type */
1464 Type* RetType = GetFuncReturn (D->Type);
1466 /* Functions may not return functions or arrays */
1467 if (IsTypeFunc (RetType)) {
1468 Error ("Functions are not allowed to return functions");
1469 } else if (IsTypeArray (RetType)) {
1470 Error ("Functions are not allowed to return arrays");
1473 /* The return type must not be qualified */
1474 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1476 if (GetType (RetType) == T_TYPE_VOID) {
1477 /* A qualified void type is always an error */
1478 Error ("function definition has qualified void return type");
1480 /* For others, qualifiers are ignored */
1481 Warning ("type qualifiers ignored on function return type");
1482 RetType[0].C = UnqualifiedType (RetType[0].C);
1486 /* Warn about an implicit int return in the function */
1487 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1488 RetType[0].C == T_INT && RetType[1].C == T_END) {
1489 /* Function has an implicit int return. Output a warning if we don't
1490 * have the C89 standard enabled explicitly.
1492 if (IS_Get (&Standard) >= STD_C99) {
1493 Warning ("Implicit `int' return type is an obsolete feature");
1495 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1500 /* For anthing that is not a function or typedef, check for an implicit
1503 if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1504 (D->StorageClass & SC_TYPEDEF) != SC_TYPEDEF) {
1505 /* If the standard was not set explicitly to C89, print a warning
1506 * for variables with implicit int type.
1508 if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1509 Warning ("Implicit `int' is an obsolete feature");
1513 /* Check the size of the generated type */
1514 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1515 unsigned Size = SizeOf (D->Type);
1516 if (Size >= 0x10000) {
1517 if (D->Ident[0] != '\0') {
1518 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1520 Error ("Invalid size in declaration (0x%06X)", Size);
1529 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1530 /* Parse a declaration specification */
1532 TypeCode Qualifiers;
1534 /* Initialize the DeclSpec struct */
1537 /* There may be qualifiers *before* the storage class specifier */
1538 Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1540 /* Now get the storage class specifier for this declaration */
1541 ParseStorageClass (D, DefStorage);
1543 /* Parse the type specifiers passing any initial type qualifiers */
1544 ParseTypeSpec (D, DefType, Qualifiers);
1549 void CheckEmptyDecl (const DeclSpec* D)
1550 /* Called after an empty type declaration (that is, a type declaration without
1551 * a variable). Checks if the declaration does really make sense and issues a
1555 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1556 Warning ("Useless declaration");
1562 static void SkipInitializer (unsigned BracesExpected)
1563 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1564 * smart so we don't have too many following errors.
1567 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1568 switch (CurTok.Tok) {
1569 case TOK_RCURLY: --BracesExpected; break;
1570 case TOK_LCURLY: ++BracesExpected; break;
1579 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1580 /* Accept any number of opening curly braces around an initialization, skip
1581 * them and return the number. If the number of curly braces is less than
1582 * BracesNeeded, issue a warning.
1585 unsigned BraceCount = 0;
1586 while (CurTok.Tok == TOK_LCURLY) {
1590 if (BraceCount < BracesNeeded) {
1591 Error ("`{' expected");
1598 static void ClosingCurlyBraces (unsigned BracesExpected)
1599 /* Accept and skip the given number of closing curly braces together with
1600 * an optional comma. Output an error messages, if the input does not contain
1601 * the expected number of braces.
1604 while (BracesExpected) {
1605 if (CurTok.Tok == TOK_RCURLY) {
1607 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1611 Error ("`}' expected");
1620 static void DefineData (ExprDesc* Expr)
1621 /* Output a data definition for the given expression */
1623 switch (ED_GetLoc (Expr)) {
1626 /* Absolute: numeric address or const */
1627 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1631 /* Global variable */
1632 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1637 /* Static variable or literal in the literal pool */
1638 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1641 case E_LOC_REGISTER:
1642 /* Register variable. Taking the address is usually not
1645 if (IS_Get (&AllowRegVarAddr) == 0) {
1646 Error ("Cannot take the address of a register variable");
1648 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1654 Error ("Non constant initializer");
1658 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1664 static void OutputBitFieldData (StructInitData* SI)
1665 /* Output bit field data */
1667 /* Ignore if we have no data */
1668 if (SI->ValBits > 0) {
1670 /* Output the data */
1671 g_defdata (CF_INT | CF_UNSIGNED | CF_CONST, SI->BitVal, 0);
1673 /* Clear the data from SI and account for the size */
1676 SI->Offs += SIZEOF_INT;
1682 static void ParseScalarInitInternal (Type* T, ExprDesc* ED)
1683 /* Parse initializaton for scalar data types. This function will not output the
1684 * data but return it in ED.
1687 /* Optional opening brace */
1688 unsigned BraceCount = OpeningCurlyBraces (0);
1690 /* We warn if an initializer for a scalar contains braces, because this is
1691 * quite unusual and often a sign for some problem in the input.
1693 if (BraceCount > 0) {
1694 Warning ("Braces around scalar initializer");
1697 /* Get the expression and convert it to the target type */
1698 ConstExpr (hie1, ED);
1699 TypeConversion (ED, T);
1701 /* Close eventually opening braces */
1702 ClosingCurlyBraces (BraceCount);
1707 static unsigned ParseScalarInit (Type* T)
1708 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1712 /* Parse initialization */
1713 ParseScalarInitInternal (T, &ED);
1715 /* Output the data */
1724 static unsigned ParsePointerInit (Type* T)
1725 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1727 /* Optional opening brace */
1728 unsigned BraceCount = OpeningCurlyBraces (0);
1732 ConstExpr (hie1, &ED);
1733 TypeConversion (&ED, T);
1735 /* Output the data */
1738 /* Close eventually opening braces */
1739 ClosingCurlyBraces (BraceCount);
1747 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1748 /* Parse initializaton for arrays. Return the number of data bytes. */
1752 /* Get the array data */
1753 Type* ElementType = GetElementType (T);
1754 unsigned ElementSize = CheckedSizeOf (ElementType);
1755 long ElementCount = GetElementCount (T);
1757 /* Special handling for a character array initialized by a literal */
1758 if (IsTypeChar (ElementType) &&
1759 (CurTok.Tok == TOK_SCONST ||
1760 (CurTok.Tok == TOK_LCURLY && NextTok.Tok == TOK_SCONST))) {
1762 /* Char array initialized by string constant */
1766 /* If we initializer is enclosed in brackets, remember this fact and
1767 * skip the opening bracket.
1769 NeedParen = (CurTok.Tok == TOK_LCURLY);
1774 /* Get the initializer string and its size */
1775 Str = GetLiteral (CurTok.IVal);
1776 Count = GetLiteralPoolOffs () - CurTok.IVal;
1778 /* Translate into target charset */
1779 TranslateLiteralPool (CurTok.IVal);
1781 /* If the array is one too small for the string literal, omit the
1784 if (ElementCount != UNSPECIFIED &&
1785 ElementCount != FLEXIBLE &&
1786 Count == ElementCount + 1) {
1787 /* Omit the trailing zero */
1791 /* Output the data */
1792 g_defbytes (Str, Count);
1794 /* Remove string from pool */
1795 ResetLiteralPoolOffs (CurTok.IVal);
1798 /* If the initializer was enclosed in curly braces, we need a closing
1810 /* Initialize the array members */
1812 while (CurTok.Tok != TOK_RCURLY) {
1813 /* Flexible array members may not be initialized within
1814 * an array (because the size of each element may differ
1817 ParseInitInternal (ElementType, 0);
1819 if (CurTok.Tok != TOK_COMMA)
1824 /* Closing curly braces */
1828 if (ElementCount == UNSPECIFIED) {
1829 /* Number of elements determined by initializer */
1830 SetElementCount (T, Count);
1831 ElementCount = Count;
1832 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1833 /* In non ANSI mode, allow initialization of flexible array
1836 ElementCount = Count;
1837 } else if (Count < ElementCount) {
1838 g_zerobytes ((ElementCount - Count) * ElementSize);
1839 } else if (Count > ElementCount) {
1840 Error ("Too many initializers");
1842 return ElementCount * ElementSize;
1847 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1848 /* Parse initialization of a struct or union. Return the number of data bytes. */
1855 /* Consume the opening curly brace */
1858 /* Get a pointer to the struct entry from the type */
1859 Entry = GetSymEntry (T);
1861 /* Get the size of the struct from the symbol table entry */
1862 SI.Size = Entry->V.S.Size;
1864 /* Check if this struct definition has a field table. If it doesn't, it
1865 * is an incomplete definition.
1867 Tab = Entry->V.S.SymTab;
1869 Error ("Cannot initialize variables with incomplete type");
1870 /* Try error recovery */
1871 SkipInitializer (1);
1872 /* Nothing initialized */
1876 /* Get a pointer to the list of symbols */
1877 Entry = Tab->SymHead;
1879 /* Initialize fields */
1883 while (CurTok.Tok != TOK_RCURLY) {
1887 Error ("Too many initializers");
1888 SkipInitializer (1);
1892 /* Parse initialization of one field. Bit-fields need a special
1895 if (SymIsBitField (Entry)) {
1901 /* Calculate the bitmask from the bit-field data */
1902 unsigned Mask = (1U << Entry->V.B.BitWidth) - 1U;
1905 CHECK (Entry->V.B.Offs * CHAR_BITS + Entry->V.B.BitOffs ==
1906 SI.Offs * CHAR_BITS + SI.ValBits);
1908 /* This may be an anonymous bit-field, in which case it doesn't
1909 * have an initializer.
1911 if (IsAnonName (Entry->Name)) {
1912 /* Account for the data and output it if we have a full word */
1913 SI.ValBits += Entry->V.B.BitWidth;
1914 CHECK (SI.ValBits <= INT_BITS);
1915 if (SI.ValBits == INT_BITS) {
1916 OutputBitFieldData (&SI);
1920 /* Read the data, check for a constant integer, do a range
1923 ParseScalarInitInternal (type_uint, &ED);
1924 if (!ED_IsConstAbsInt (&ED)) {
1925 Error ("Constant initializer expected");
1926 ED_MakeConstAbsInt (&ED, 1);
1928 if (ED.IVal > (long) Mask) {
1929 Warning ("Truncating value in bit-field initializer");
1930 ED.IVal &= (long) Mask;
1932 Val = (unsigned) ED.IVal;
1935 /* Add the value to the currently stored bit-field value */
1936 Shift = (Entry->V.B.Offs - SI.Offs) * CHAR_BITS + Entry->V.B.BitOffs;
1937 SI.BitVal |= (Val << Shift);
1939 /* Account for the data and output it if we have a full word */
1940 SI.ValBits += Entry->V.B.BitWidth;
1941 CHECK (SI.ValBits <= INT_BITS);
1942 if (SI.ValBits == INT_BITS) {
1943 OutputBitFieldData (&SI);
1948 /* Standard member. We should never have stuff from a
1951 CHECK (SI.ValBits == 0);
1953 /* Flexible array members may only be initialized if they are
1954 * the last field (or part of the last struct field).
1956 SI.Offs += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1959 /* More initializers? */
1960 if (CurTok.Tok != TOK_COMMA) {
1964 /* Skip the comma */
1968 /* Next member. For unions, only the first one can be initialized */
1969 if (IsTypeUnion (T)) {
1974 Entry = Entry->NextSym;
1978 /* Consume the closing curly brace */
1981 /* If we have data from a bit-field left, output it now */
1982 OutputBitFieldData (&SI);
1984 /* If there are struct fields left, reserve additional storage */
1985 if (SI.Offs < SI.Size) {
1986 g_zerobytes (SI.Size - SI.Offs);
1990 /* Return the actual number of bytes initialized. This number may be
1991 * larger than sizeof (Struct) if flexible array members are present and
1992 * were initialized (possible in non ANSI mode).
1999 static unsigned ParseVoidInit (void)
2000 /* Parse an initialization of a void variable (special cc65 extension).
2001 * Return the number of bytes initialized.
2010 /* Allow an arbitrary list of values */
2013 ConstExpr (hie1, &Expr);
2014 switch (UnqualifiedType (Expr.Type[0].C)) {
2018 if (ED_IsConstAbsInt (&Expr)) {
2019 /* Make it byte sized */
2023 Size += SIZEOF_CHAR;
2032 if (ED_IsConstAbsInt (&Expr)) {
2033 /* Make it word sized */
2034 Expr.IVal &= 0xFFFF;
2042 if (ED_IsConstAbsInt (&Expr)) {
2043 /* Make it dword sized */
2044 Expr.IVal &= 0xFFFFFFFF;
2047 Size += SIZEOF_LONG;
2051 Error ("Illegal type in initialization");
2056 if (CurTok.Tok != TOK_COMMA) {
2061 } while (CurTok.Tok != TOK_RCURLY);
2066 /* Return the number of bytes initialized */
2072 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
2073 /* Parse initialization of variables. Return the number of data bytes. */
2075 switch (UnqualifiedType (T->C)) {
2087 return ParseScalarInit (T);
2090 return ParsePointerInit (T);
2093 return ParseArrayInit (T, AllowFlexibleMembers);
2097 return ParseStructInit (T, AllowFlexibleMembers);
2100 if (IS_Get (&Standard) == STD_CC65) {
2101 /* Special cc65 extension in non ANSI mode */
2102 return ParseVoidInit ();
2107 Error ("Illegal type");
2115 unsigned ParseInit (Type* T)
2116 /* Parse initialization of variables. Return the number of data bytes. */
2118 /* Parse the initialization. Flexible array members can only be initialized
2121 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
2123 /* The initialization may not generate code on global level, because code
2124 * outside function scope will never get executed.
2126 if (HaveGlobalCode ()) {
2127 Error ("Non constant initializers");
2128 RemoveGlobalCode ();
2131 /* Return the size needed for the initialization */