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 |= GetQualifier (T);
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 if (!FlexibleMember) {
742 StructSize += CheckedSizeOf (Decl.Type);
746 NextMember: if (CurTok.Tok != TOK_COMMA) {
754 /* If we have bits from bit-fields left, add them to the size. */
756 StructSize += ((BitOffs + CHAR_BITS - 1) / CHAR_BITS);
759 /* Skip the closing brace */
762 /* Remember the symbol table and leave the struct level */
763 FieldTab = GetSymTab ();
766 /* Make a real entry from the forward decl and return it */
767 return AddStructSym (Name, StructSize, FieldTab);
772 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
773 /* Parse a type specificier */
778 /* Assume we have an explicit type */
779 D->Flags &= ~DS_DEF_TYPE;
781 /* Read type qualifiers if we have any */
782 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
784 /* Look at the data type */
785 switch (CurTok.Tok) {
789 D->Type[0].C = T_VOID;
790 D->Type[1].C = T_END;
795 D->Type[0].C = GetDefaultChar();
796 D->Type[1].C = T_END;
801 if (CurTok.Tok == TOK_UNSIGNED) {
804 D->Type[0].C = T_ULONG;
805 D->Type[1].C = T_END;
809 D->Type[0].C = T_LONG;
810 D->Type[1].C = T_END;
816 if (CurTok.Tok == TOK_UNSIGNED) {
819 D->Type[0].C = T_USHORT;
820 D->Type[1].C = T_END;
824 D->Type[0].C = T_SHORT;
825 D->Type[1].C = T_END;
831 D->Type[0].C = T_INT;
832 D->Type[1].C = T_END;
837 switch (CurTok.Tok) {
841 D->Type[0].C = T_SCHAR;
842 D->Type[1].C = T_END;
848 D->Type[0].C = T_SHORT;
849 D->Type[1].C = T_END;
855 D->Type[0].C = T_LONG;
856 D->Type[1].C = T_END;
864 D->Type[0].C = T_INT;
865 D->Type[1].C = T_END;
872 switch (CurTok.Tok) {
876 D->Type[0].C = T_UCHAR;
877 D->Type[1].C = T_END;
883 D->Type[0].C = T_USHORT;
884 D->Type[1].C = T_END;
890 D->Type[0].C = T_ULONG;
891 D->Type[1].C = T_END;
899 D->Type[0].C = T_UINT;
900 D->Type[1].C = T_END;
907 D->Type[0].C = T_FLOAT;
908 D->Type[1].C = T_END;
913 D->Type[0].C = T_DOUBLE;
914 D->Type[1].C = T_END;
920 if (CurTok.Tok == TOK_IDENT) {
921 strcpy (Ident, CurTok.Ident);
924 AnonName (Ident, "union");
926 /* Remember we have an extra type decl */
927 D->Flags |= DS_EXTRA_TYPE;
928 /* Declare the union in the current scope */
929 Entry = ParseUnionDecl (Ident);
930 /* Encode the union entry into the type */
931 D->Type[0].C = T_UNION;
932 SetSymEntry (D->Type, Entry);
933 D->Type[1].C = T_END;
939 if (CurTok.Tok == TOK_IDENT) {
940 strcpy (Ident, CurTok.Ident);
943 AnonName (Ident, "struct");
945 /* Remember we have an extra type decl */
946 D->Flags |= DS_EXTRA_TYPE;
947 /* Declare the struct in the current scope */
948 Entry = ParseStructDecl (Ident);
949 /* Encode the struct entry into the type */
950 D->Type[0].C = T_STRUCT;
951 SetSymEntry (D->Type, Entry);
952 D->Type[1].C = T_END;
957 if (CurTok.Tok != TOK_LCURLY) {
959 if (CurTok.Tok == TOK_IDENT) {
960 /* Find an entry with this name */
961 Entry = FindTagSym (CurTok.Ident);
963 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
964 Error ("Symbol `%s' is already different kind", Entry->Name);
967 /* Insert entry into table ### */
969 /* Skip the identifier */
972 Error ("Identifier expected");
975 /* Remember we have an extra type decl */
976 D->Flags |= DS_EXTRA_TYPE;
977 /* Parse the enum decl */
979 D->Type[0].C = T_INT;
980 D->Type[1].C = T_END;
984 Entry = FindSym (CurTok.Ident);
985 if (Entry && SymIsTypeDef (Entry)) {
988 TypeCopy (D->Type, Entry->Type);
995 Error ("Type expected");
996 D->Type[0].C = T_INT;
997 D->Type[1].C = T_END;
999 D->Flags |= DS_DEF_TYPE;
1000 D->Type[0].C = (TypeCode) Default;
1001 D->Type[1].C = T_END;
1006 /* There may also be qualifiers *after* the initial type */
1007 D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
1012 static Type* ParamTypeCvt (Type* T)
1013 /* If T is an array, convert it to a pointer else do nothing. Return the
1017 if (IsTypeArray (T)) {
1025 static void ParseOldStyleParamList (FuncDesc* F)
1026 /* Parse an old style (K&R) parameter list */
1029 while (CurTok.Tok != TOK_RPAREN) {
1031 /* List of identifiers expected */
1032 if (CurTok.Tok != TOK_IDENT) {
1033 Error ("Identifier expected");
1036 /* Create a symbol table entry with type int */
1037 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1039 /* Count arguments */
1042 /* Skip the identifier */
1045 /* Check for more parameters */
1046 if (CurTok.Tok == TOK_COMMA) {
1053 /* Skip right paren. We must explicitly check for one here, since some of
1054 * the breaks above bail out without checking.
1058 /* An optional list of type specifications follows */
1059 while (CurTok.Tok != TOK_LCURLY) {
1063 /* Read the declaration specifier */
1064 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1066 /* We accept only auto and register as storage class specifiers, but
1067 * we ignore all this, since we use auto anyway.
1069 if ((Spec.StorageClass & SC_AUTO) == 0 &&
1070 (Spec.StorageClass & SC_REGISTER) == 0) {
1071 Error ("Illegal storage class");
1074 /* Parse a comma separated variable list */
1079 /* Read the parameter */
1080 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1081 if (Decl.Ident[0] != '\0') {
1083 /* We have a name given. Search for the symbol */
1084 SymEntry* Sym = FindLocalSym (Decl.Ident);
1086 /* Check if we already changed the type for this
1089 if (Sym->Flags & SC_DEFTYPE) {
1090 /* Found it, change the default type to the one given */
1091 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1092 /* Reset the "default type" flag */
1093 Sym->Flags &= ~SC_DEFTYPE;
1095 /* Type has already been changed */
1096 Error ("Redefinition for parameter `%s'", Sym->Name);
1099 Error ("Unknown identifier: `%s'", Decl.Ident);
1103 if (CurTok.Tok == TOK_COMMA) {
1111 /* Variable list must be semicolon terminated */
1118 static void ParseAnsiParamList (FuncDesc* F)
1119 /* Parse a new style (ANSI) parameter list */
1122 while (CurTok.Tok != TOK_RPAREN) {
1128 /* Allow an ellipsis as last parameter */
1129 if (CurTok.Tok == TOK_ELLIPSIS) {
1131 F->Flags |= FD_VARIADIC;
1135 /* Read the declaration specifier */
1136 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1138 /* We accept only auto and register as storage class specifiers */
1139 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1140 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1141 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1142 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1144 Error ("Illegal storage class");
1145 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1148 /* Allow parameters without a name, but remember if we had some to
1149 * eventually print an error message later.
1151 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1152 if (Decl.Ident[0] == '\0') {
1154 /* Unnamed symbol. Generate a name that is not user accessible,
1155 * then handle the symbol normal.
1157 AnonName (Decl.Ident, "param");
1158 F->Flags |= FD_UNNAMED_PARAMS;
1160 /* Clear defined bit on nonames */
1161 Decl.StorageClass &= ~SC_DEF;
1164 /* Parse an attribute ### */
1165 ParseAttribute (&Decl, &Attr);
1167 /* Create a symbol table entry */
1168 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1170 /* Count arguments */
1173 /* Check for more parameters */
1174 if (CurTok.Tok == TOK_COMMA) {
1181 /* Skip right paren. We must explicitly check for one here, since some of
1182 * the breaks above bail out without checking.
1186 /* Check if this is a function definition */
1187 if (CurTok.Tok == TOK_LCURLY) {
1188 /* Print an error if we have unnamed parameters and cc65 extensions
1191 if (IS_Get (&Standard) != STD_CC65 &&
1192 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
1193 Error ("Parameter name omitted");
1200 static FuncDesc* ParseFuncDecl (void)
1201 /* Parse the argument list of a function. */
1206 /* Create a new function descriptor */
1207 FuncDesc* F = NewFuncDesc ();
1209 /* Enter a new lexical level */
1210 EnterFunctionLevel ();
1212 /* Check for several special parameter lists */
1213 if (CurTok.Tok == TOK_RPAREN) {
1214 /* Parameter list is empty */
1215 F->Flags |= (FD_EMPTY | FD_VARIADIC);
1216 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1217 /* Parameter list declared as void */
1219 F->Flags |= FD_VOID_PARAM;
1220 } else if (CurTok.Tok == TOK_IDENT &&
1221 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1222 /* If the identifier is a typedef, we have a new style parameter list,
1223 * if it's some other identifier, it's an old style parameter list.
1225 Sym = FindSym (CurTok.Ident);
1226 if (Sym == 0 || !SymIsTypeDef (Sym)) {
1227 /* Old style (K&R) function. */
1228 F->Flags |= FD_OLDSTYLE;
1233 if ((F->Flags & FD_OLDSTYLE) == 0) {
1234 /* New style function */
1235 ParseAnsiParamList (F);
1237 /* Old style function */
1238 ParseOldStyleParamList (F);
1241 /* Remember the last function parameter. We need it later for several
1242 * purposes, for example when passing stuff to fastcall functions. Since
1243 * more symbols are added to the table, it is easier if we remember it
1244 * now, since it is currently the last entry in the symbol table.
1246 F->LastParam = GetSymTab()->SymTail;
1248 /* Assign offsets. If the function has a variable parameter list,
1249 * there's one additional byte (the arg size).
1251 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1254 unsigned Size = CheckedSizeOf (Sym->Type);
1255 if (SymIsRegVar (Sym)) {
1256 Sym->V.R.SaveOffs = Offs;
1261 F->ParamSize += Size;
1265 /* Leave the lexical level remembering the symbol tables */
1266 RememberFunctionLevel (F);
1268 /* Return the function descriptor */
1274 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1275 /* Recursively process declarators. Build a type array in reverse order. */
1277 /* Read optional function or pointer qualifiers. These modify the
1278 * identifier or token to the right. For convenience, we allow the fastcall
1279 * qualifier also for pointers here. If it is a pointer-to-function, the
1280 * qualifier will later be transfered to the function itself. If it's a
1281 * pointer to something else, it will be flagged as an error.
1283 TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL);
1285 /* Pointer to something */
1286 if (CurTok.Tok == TOK_STAR) {
1291 /* Allow const, restrict and volatile qualifiers */
1292 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1294 /* Parse the type, the pointer points to */
1295 Declarator (Spec, D, Mode);
1298 AddTypeToDeclaration (D, T_PTR | Qualifiers);
1302 if (CurTok.Tok == TOK_LPAREN) {
1304 Declarator (Spec, D, Mode);
1307 /* Things depend on Mode now:
1308 * - Mode == DM_NEED_IDENT means:
1309 * we *must* have a type and a variable identifer.
1310 * - Mode == DM_NO_IDENT means:
1311 * we must have a type but no variable identifer
1312 * (if there is one, it's not read).
1313 * - Mode == DM_ACCEPT_IDENT means:
1314 * we *may* have an identifier. If there is an identifier,
1315 * it is read, but it is no error, if there is none.
1317 if (Mode == DM_NO_IDENT) {
1319 } else if (CurTok.Tok == TOK_IDENT) {
1320 strcpy (D->Ident, CurTok.Ident);
1323 if (Mode == DM_NEED_IDENT) {
1324 Error ("Identifier expected");
1330 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1331 if (CurTok.Tok == TOK_LPAREN) {
1333 /* Function declaration */
1336 /* Skip the opening paren */
1339 /* Parse the function declaration */
1340 F = ParseFuncDecl ();
1342 /* We cannot specify fastcall for variadic functions */
1343 if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1344 Error ("Variadic functions cannot be `__fastcall'");
1345 Qualifiers &= ~T_QUAL_FASTCALL;
1348 /* Add the function type. Be sure to bounds check the type buffer */
1349 NeedTypeSpace (D, 1);
1350 D->Type[D->Index].C = T_FUNC | Qualifiers;
1351 D->Type[D->Index].A.P = F;
1354 /* Qualifiers now used */
1355 Qualifiers = T_QUAL_NONE;
1358 /* Array declaration. */
1359 long Size = UNSPECIFIED;
1361 /* We cannot have any qualifiers for an array */
1362 if (Qualifiers != T_QUAL_NONE) {
1363 Error ("Invalid qualifiers for array");
1364 Qualifiers = T_QUAL_NONE;
1367 /* Skip the left bracket */
1370 /* Read the size if it is given */
1371 if (CurTok.Tok != TOK_RBRACK) {
1373 ConstAbsIntExpr (hie1, &Expr);
1374 if (Expr.IVal <= 0) {
1375 if (D->Ident[0] != '\0') {
1376 Error ("Size of array `%s' is invalid", D->Ident);
1378 Error ("Size of array is invalid");
1385 /* Skip the right bracket */
1388 /* Add the array type with the size to the type */
1389 NeedTypeSpace (D, 1);
1390 D->Type[D->Index].C = T_ARRAY;
1391 D->Type[D->Index].A.L = Size;
1396 /* If we have remaining qualifiers, flag them as invalid */
1397 if (Qualifiers & T_QUAL_NEAR) {
1398 Error ("Invalid `__near__' qualifier");
1400 if (Qualifiers & T_QUAL_FAR) {
1401 Error ("Invalid `__far__' qualifier");
1403 if (Qualifiers & T_QUAL_FASTCALL) {
1404 Error ("Invalid `__fastcall__' qualifier");
1410 /*****************************************************************************/
1412 /*****************************************************************************/
1416 Type* ParseType (Type* T)
1417 /* Parse a complete type specification */
1422 /* Get a type without a default */
1423 InitDeclSpec (&Spec);
1424 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1426 /* Parse additional declarators */
1427 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1429 /* Copy the type to the target buffer */
1430 TypeCopy (T, Decl.Type);
1432 /* Return a pointer to the target buffer */
1438 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1439 /* Parse a variable, type or function declaration */
1441 /* Initialize the Declaration struct */
1442 InitDeclaration (D);
1444 /* Get additional declarators and the identifier */
1445 Declarator (Spec, D, Mode);
1447 /* Add the base type. */
1448 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1449 TypeCopy (D->Type + D->Index, Spec->Type);
1451 /* Use the storage class from the declspec */
1452 D->StorageClass = Spec->StorageClass;
1454 /* Do several fixes on qualifiers */
1455 FixQualifiers (D->Type);
1457 /* If we have a function, add a special storage class */
1458 if (IsTypeFunc (D->Type)) {
1459 D->StorageClass |= SC_FUNC;
1462 /* Check several things for function or function pointer types */
1463 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1465 /* A function. Check the return type */
1466 Type* RetType = GetFuncReturn (D->Type);
1468 /* Functions may not return functions or arrays */
1469 if (IsTypeFunc (RetType)) {
1470 Error ("Functions are not allowed to return functions");
1471 } else if (IsTypeArray (RetType)) {
1472 Error ("Functions are not allowed to return arrays");
1475 /* The return type must not be qualified */
1476 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1478 if (GetType (RetType) == T_TYPE_VOID) {
1479 /* A qualified void type is always an error */
1480 Error ("function definition has qualified void return type");
1482 /* For others, qualifiers are ignored */
1483 Warning ("type qualifiers ignored on function return type");
1484 RetType[0].C = UnqualifiedType (RetType[0].C);
1488 /* Warn about an implicit int return in the function */
1489 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1490 RetType[0].C == T_INT && RetType[1].C == T_END) {
1491 /* Function has an implicit int return. Output a warning if we don't
1492 * have the C89 standard enabled explicitly.
1494 if (IS_Get (&Standard) >= STD_C99) {
1495 Warning ("Implicit `int' return type is an obsolete feature");
1497 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1502 /* For anthing that is not a function or typedef, check for an implicit
1505 if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1506 (D->StorageClass & SC_TYPEDEF) != SC_TYPEDEF) {
1507 /* If the standard was not set explicitly to C89, print a warning
1508 * for variables with implicit int type.
1510 if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1511 Warning ("Implicit `int' is an obsolete feature");
1515 /* Check the size of the generated type */
1516 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1517 unsigned Size = SizeOf (D->Type);
1518 if (Size >= 0x10000) {
1519 if (D->Ident[0] != '\0') {
1520 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1522 Error ("Invalid size in declaration (0x%06X)", Size);
1531 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1532 /* Parse a declaration specification */
1534 TypeCode Qualifiers;
1536 /* Initialize the DeclSpec struct */
1539 /* There may be qualifiers *before* the storage class specifier */
1540 Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1542 /* Now get the storage class specifier for this declaration */
1543 ParseStorageClass (D, DefStorage);
1545 /* Parse the type specifiers passing any initial type qualifiers */
1546 ParseTypeSpec (D, DefType, Qualifiers);
1551 void CheckEmptyDecl (const DeclSpec* D)
1552 /* Called after an empty type declaration (that is, a type declaration without
1553 * a variable). Checks if the declaration does really make sense and issues a
1557 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1558 Warning ("Useless declaration");
1564 static void SkipInitializer (unsigned BracesExpected)
1565 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1566 * smart so we don't have too many following errors.
1569 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1570 switch (CurTok.Tok) {
1571 case TOK_RCURLY: --BracesExpected; break;
1572 case TOK_LCURLY: ++BracesExpected; break;
1581 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1582 /* Accept any number of opening curly braces around an initialization, skip
1583 * them and return the number. If the number of curly braces is less than
1584 * BracesNeeded, issue a warning.
1587 unsigned BraceCount = 0;
1588 while (CurTok.Tok == TOK_LCURLY) {
1592 if (BraceCount < BracesNeeded) {
1593 Error ("`{' expected");
1600 static void ClosingCurlyBraces (unsigned BracesExpected)
1601 /* Accept and skip the given number of closing curly braces together with
1602 * an optional comma. Output an error messages, if the input does not contain
1603 * the expected number of braces.
1606 while (BracesExpected) {
1607 if (CurTok.Tok == TOK_RCURLY) {
1609 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1613 Error ("`}' expected");
1622 static void DefineData (ExprDesc* Expr)
1623 /* Output a data definition for the given expression */
1625 switch (ED_GetLoc (Expr)) {
1628 /* Absolute: numeric address or const */
1629 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1633 /* Global variable */
1634 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1639 /* Static variable or literal in the literal pool */
1640 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1643 case E_LOC_REGISTER:
1644 /* Register variable. Taking the address is usually not
1647 if (IS_Get (&AllowRegVarAddr) == 0) {
1648 Error ("Cannot take the address of a register variable");
1650 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1656 Error ("Non constant initializer");
1660 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1666 static void OutputBitFieldData (StructInitData* SI)
1667 /* Output bit field data */
1669 /* Ignore if we have no data */
1670 if (SI->ValBits > 0) {
1672 /* Output the data */
1673 g_defdata (CF_INT | CF_UNSIGNED | CF_CONST, SI->BitVal, 0);
1675 /* Clear the data from SI and account for the size */
1678 SI->Offs += SIZEOF_INT;
1684 static void ParseScalarInitInternal (Type* T, ExprDesc* ED)
1685 /* Parse initializaton for scalar data types. This function will not output the
1686 * data but return it in ED.
1689 /* Optional opening brace */
1690 unsigned BraceCount = OpeningCurlyBraces (0);
1692 /* We warn if an initializer for a scalar contains braces, because this is
1693 * quite unusual and often a sign for some problem in the input.
1695 if (BraceCount > 0) {
1696 Warning ("Braces around scalar initializer");
1699 /* Get the expression and convert it to the target type */
1700 ConstExpr (hie1, ED);
1701 TypeConversion (ED, T);
1703 /* Close eventually opening braces */
1704 ClosingCurlyBraces (BraceCount);
1709 static unsigned ParseScalarInit (Type* T)
1710 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1714 /* Parse initialization */
1715 ParseScalarInitInternal (T, &ED);
1717 /* Output the data */
1726 static unsigned ParsePointerInit (Type* T)
1727 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1729 /* Optional opening brace */
1730 unsigned BraceCount = OpeningCurlyBraces (0);
1734 ConstExpr (hie1, &ED);
1735 TypeConversion (&ED, T);
1737 /* Output the data */
1740 /* Close eventually opening braces */
1741 ClosingCurlyBraces (BraceCount);
1749 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1750 /* Parse initializaton for arrays. Return the number of data bytes. */
1754 /* Get the array data */
1755 Type* ElementType = GetElementType (T);
1756 unsigned ElementSize = CheckedSizeOf (ElementType);
1757 long ElementCount = GetElementCount (T);
1759 /* Special handling for a character array initialized by a literal */
1760 if (IsTypeChar (ElementType) &&
1761 (CurTok.Tok == TOK_SCONST || CurTok.Tok == TOK_WCSCONST ||
1762 (CurTok.Tok == TOK_LCURLY &&
1763 (NextTok.Tok == TOK_SCONST || NextTok.Tok == TOK_WCSCONST)))) {
1765 /* Char array initialized by string constant */
1769 /* If we initializer is enclosed in brackets, remember this fact and
1770 * skip the opening bracket.
1772 NeedParen = (CurTok.Tok == TOK_LCURLY);
1777 /* Get the initializer string and its size */
1778 Str = GetLiteral (CurTok.IVal);
1779 Count = GetLiteralPoolOffs () - CurTok.IVal;
1781 /* Translate into target charset */
1782 TranslateLiteralPool (CurTok.IVal);
1784 /* If the array is one too small for the string literal, omit the
1787 if (ElementCount != UNSPECIFIED &&
1788 ElementCount != FLEXIBLE &&
1789 Count == ElementCount + 1) {
1790 /* Omit the trailing zero */
1794 /* Output the data */
1795 g_defbytes (Str, Count);
1797 /* Remove string from pool */
1798 ResetLiteralPoolOffs (CurTok.IVal);
1801 /* If the initializer was enclosed in curly braces, we need a closing
1813 /* Initialize the array members */
1815 while (CurTok.Tok != TOK_RCURLY) {
1816 /* Flexible array members may not be initialized within
1817 * an array (because the size of each element may differ
1820 ParseInitInternal (ElementType, 0);
1822 if (CurTok.Tok != TOK_COMMA)
1827 /* Closing curly braces */
1831 if (ElementCount == UNSPECIFIED) {
1832 /* Number of elements determined by initializer */
1833 SetElementCount (T, Count);
1834 ElementCount = Count;
1835 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1836 /* In non ANSI mode, allow initialization of flexible array
1839 ElementCount = Count;
1840 } else if (Count < ElementCount) {
1841 g_zerobytes ((ElementCount - Count) * ElementSize);
1842 } else if (Count > ElementCount) {
1843 Error ("Too many initializers");
1845 return ElementCount * ElementSize;
1850 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1851 /* Parse initialization of a struct or union. Return the number of data bytes. */
1858 /* Consume the opening curly brace */
1861 /* Get a pointer to the struct entry from the type */
1862 Entry = GetSymEntry (T);
1864 /* Get the size of the struct from the symbol table entry */
1865 SI.Size = Entry->V.S.Size;
1867 /* Check if this struct definition has a field table. If it doesn't, it
1868 * is an incomplete definition.
1870 Tab = Entry->V.S.SymTab;
1872 Error ("Cannot initialize variables with incomplete type");
1873 /* Try error recovery */
1874 SkipInitializer (1);
1875 /* Nothing initialized */
1879 /* Get a pointer to the list of symbols */
1880 Entry = Tab->SymHead;
1882 /* Initialize fields */
1886 while (CurTok.Tok != TOK_RCURLY) {
1890 Error ("Too many initializers");
1891 SkipInitializer (1);
1895 /* Parse initialization of one field. Bit-fields need a special
1898 if (SymIsBitField (Entry)) {
1904 /* Calculate the bitmask from the bit-field data */
1905 unsigned Mask = (1U << Entry->V.B.BitWidth) - 1U;
1908 CHECK (Entry->V.B.Offs * CHAR_BITS + Entry->V.B.BitOffs ==
1909 SI.Offs * CHAR_BITS + SI.ValBits);
1911 /* This may be an anonymous bit-field, in which case it doesn't
1912 * have an initializer.
1914 if (IsAnonName (Entry->Name)) {
1915 /* Account for the data and output it if we have a full word */
1916 SI.ValBits += Entry->V.B.BitWidth;
1917 CHECK (SI.ValBits <= INT_BITS);
1918 if (SI.ValBits == INT_BITS) {
1919 OutputBitFieldData (&SI);
1923 /* Read the data, check for a constant integer, do a range
1926 ParseScalarInitInternal (type_uint, &ED);
1927 if (!ED_IsConstAbsInt (&ED)) {
1928 Error ("Constant initializer expected");
1929 ED_MakeConstAbsInt (&ED, 1);
1931 if (ED.IVal > (long) Mask) {
1932 Warning ("Truncating value in bit-field initializer");
1933 ED.IVal &= (long) Mask;
1935 Val = (unsigned) ED.IVal;
1938 /* Add the value to the currently stored bit-field value */
1939 Shift = (Entry->V.B.Offs - SI.Offs) * CHAR_BITS + Entry->V.B.BitOffs;
1940 SI.BitVal |= (Val << Shift);
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);
1951 /* Standard member. We should never have stuff from a
1954 CHECK (SI.ValBits == 0);
1956 /* Flexible array members may only be initialized if they are
1957 * the last field (or part of the last struct field).
1959 SI.Offs += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1962 /* More initializers? */
1963 if (CurTok.Tok != TOK_COMMA) {
1967 /* Skip the comma */
1971 /* Next member. For unions, only the first one can be initialized */
1972 if (IsTypeUnion (T)) {
1977 Entry = Entry->NextSym;
1981 /* Consume the closing curly brace */
1984 /* If we have data from a bit-field left, output it now */
1985 OutputBitFieldData (&SI);
1987 /* If there are struct fields left, reserve additional storage */
1988 if (SI.Offs < SI.Size) {
1989 g_zerobytes (SI.Size - SI.Offs);
1993 /* Return the actual number of bytes initialized. This number may be
1994 * larger than sizeof (Struct) if flexible array members are present and
1995 * were initialized (possible in non ANSI mode).
2002 static unsigned ParseVoidInit (void)
2003 /* Parse an initialization of a void variable (special cc65 extension).
2004 * Return the number of bytes initialized.
2013 /* Allow an arbitrary list of values */
2016 ConstExpr (hie1, &Expr);
2017 switch (UnqualifiedType (Expr.Type[0].C)) {
2021 if (ED_IsConstAbsInt (&Expr)) {
2022 /* Make it byte sized */
2026 Size += SIZEOF_CHAR;
2035 if (ED_IsConstAbsInt (&Expr)) {
2036 /* Make it word sized */
2037 Expr.IVal &= 0xFFFF;
2045 if (ED_IsConstAbsInt (&Expr)) {
2046 /* Make it dword sized */
2047 Expr.IVal &= 0xFFFFFFFF;
2050 Size += SIZEOF_LONG;
2054 Error ("Illegal type in initialization");
2059 if (CurTok.Tok != TOK_COMMA) {
2064 } while (CurTok.Tok != TOK_RCURLY);
2069 /* Return the number of bytes initialized */
2075 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
2076 /* Parse initialization of variables. Return the number of data bytes. */
2078 switch (UnqualifiedType (T->C)) {
2090 return ParseScalarInit (T);
2093 return ParsePointerInit (T);
2096 return ParseArrayInit (T, AllowFlexibleMembers);
2100 return ParseStructInit (T, AllowFlexibleMembers);
2103 if (IS_Get (&Standard) == STD_CC65) {
2104 /* Special cc65 extension in non ANSI mode */
2105 return ParseVoidInit ();
2110 Error ("Illegal type");
2118 unsigned ParseInit (Type* T)
2119 /* Parse initialization of variables. Return the number of data bytes. */
2121 /* Parse the initialization. Flexible array members can only be initialized
2124 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
2126 /* The initialization may not generate code on global level, because code
2127 * outside function scope will never get executed.
2129 if (HaveGlobalCode ()) {
2130 Error ("Non constant initializers");
2131 RemoveGlobalCode ();
2134 /* Return the size needed for the initialization */