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_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 if (FieldWidth < 0) {
560 /* A non bit-field without a name is legal but useless */
561 Warning ("Declaration does not declare anything");
564 /* A bit-field without a name does nothing in a union */
570 FieldSize = CheckedSizeOf (Decl.Type);
571 if (FieldSize > UnionSize) {
572 UnionSize = FieldSize;
575 /* Add a field entry to the table */
576 if (FieldWidth > 0) {
577 AddBitField (Decl.Ident, 0, 0, FieldWidth);
579 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, 0);
582 NextMember: if (CurTok.Tok != TOK_COMMA) {
590 /* Skip the closing brace */
593 /* Remember the symbol table and leave the struct level */
594 FieldTab = GetSymTab ();
597 /* Make a real entry from the forward decl and return it */
598 return AddStructSym (Name, UnionSize, FieldTab);
603 static SymEntry* ParseStructDecl (const char* Name)
604 /* Parse a struct declaration. */
610 int BitOffs; /* Bit offset for bit-fields */
611 int FieldWidth; /* Width in bits, -1 if not a bit-field */
616 if (CurTok.Tok != TOK_LCURLY) {
617 /* Just a forward declaration. */
618 return StructOrUnionForwardDecl (Name);
621 /* Add a forward declaration for the struct in the current lexical level */
622 Entry = AddStructSym (Name, 0, 0);
624 /* Skip the curly brace */
627 /* Enter a new lexical level for the struct */
630 /* Parse struct fields */
634 while (CurTok.Tok != TOK_RCURLY) {
636 /* Get the type of the entry */
638 InitDeclSpec (&Spec);
639 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
641 /* Read fields with this type */
646 /* If we had a flexible array member before, no other fields can
649 if (FlexibleMember) {
650 Error ("Flexible array member must be last field");
651 FlexibleMember = 0; /* Avoid further errors */
654 /* Get type and name of the struct field */
655 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
657 /* Check for a bit-field declaration */
658 FieldWidth = ParseFieldWidth (&Decl);
660 /* If this is not a bit field, or the bit field is too large for
661 * the remainder of the current member, or we have a bit field
662 * with width zero, align the struct to the next member
665 if (FieldWidth <= 0 || (BitOffs + FieldWidth) > INT_BITS) {
666 StructSize += SIZEOF_INT;
671 /* Apart from the above, a bit field with width 0 is not processed
674 if (FieldWidth == 0) {
678 /* Check for fields without names */
679 if (Decl.Ident[0] == '\0') {
680 if (FieldWidth < 0) {
681 /* A non bit-field without a name is legal but useless */
682 Warning ("Declaration does not declare anything");
685 /* A bit-field without a name will just increase the
688 BitOffs += FieldWidth;
693 /* Byte offset of this member is the current struct size plus any
694 * full bytes from the bit offset in case of bit-fields.
696 Offs = StructSize + (BitOffs >> 3);
698 /* Check if this field is a flexible array member, and
699 * calculate the size of the field.
701 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
702 /* Array with unspecified size */
703 if (StructSize == 0) {
704 Error ("Flexible array member cannot be first struct field");
707 /* Assume zero for size calculations */
708 SetElementCount (Decl.Type, FLEXIBLE);
709 } else if (FieldWidth < 0) {
710 StructSize += CheckedSizeOf (Decl.Type);
713 /* Add a field entry to the table */
714 if (FieldWidth > 0) {
715 AddBitField (Decl.Ident, Offs, BitOffs & 0x07, FieldWidth);
716 BitOffs += FieldWidth;
718 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
721 NextMember: if (CurTok.Tok != TOK_COMMA) {
729 /* If we have bits from bit-fields left, add them to the size. */
731 StructSize += ((BitOffs + CHAR_BITS - 1) >> 3);
734 /* Skip the closing brace */
737 /* Remember the symbol table and leave the struct level */
738 FieldTab = GetSymTab ();
741 /* Make a real entry from the forward decl and return it */
742 return AddStructSym (Name, StructSize, FieldTab);
747 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
748 /* Parse a type specificier */
753 /* Assume we have an explicit type */
754 D->Flags &= ~DS_DEF_TYPE;
756 /* Read type qualifiers if we have any */
757 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
759 /* Look at the data type */
760 switch (CurTok.Tok) {
764 D->Type[0].C = T_VOID;
765 D->Type[1].C = T_END;
770 D->Type[0].C = GetDefaultChar();
771 D->Type[1].C = T_END;
776 if (CurTok.Tok == TOK_UNSIGNED) {
779 D->Type[0].C = T_ULONG;
780 D->Type[1].C = T_END;
784 D->Type[0].C = T_LONG;
785 D->Type[1].C = T_END;
791 if (CurTok.Tok == TOK_UNSIGNED) {
794 D->Type[0].C = T_USHORT;
795 D->Type[1].C = T_END;
799 D->Type[0].C = T_SHORT;
800 D->Type[1].C = T_END;
806 D->Type[0].C = T_INT;
807 D->Type[1].C = T_END;
812 switch (CurTok.Tok) {
816 D->Type[0].C = T_SCHAR;
817 D->Type[1].C = T_END;
823 D->Type[0].C = T_SHORT;
824 D->Type[1].C = T_END;
830 D->Type[0].C = T_LONG;
831 D->Type[1].C = T_END;
839 D->Type[0].C = T_INT;
840 D->Type[1].C = T_END;
847 switch (CurTok.Tok) {
851 D->Type[0].C = T_UCHAR;
852 D->Type[1].C = T_END;
858 D->Type[0].C = T_USHORT;
859 D->Type[1].C = T_END;
865 D->Type[0].C = T_ULONG;
866 D->Type[1].C = T_END;
874 D->Type[0].C = T_UINT;
875 D->Type[1].C = T_END;
882 D->Type[0].C = T_FLOAT;
883 D->Type[1].C = T_END;
888 D->Type[0].C = T_DOUBLE;
889 D->Type[1].C = T_END;
895 if (CurTok.Tok == TOK_IDENT) {
896 strcpy (Ident, CurTok.Ident);
899 AnonName (Ident, "union");
901 /* Remember we have an extra type decl */
902 D->Flags |= DS_EXTRA_TYPE;
903 /* Declare the union in the current scope */
904 Entry = ParseUnionDecl (Ident);
905 /* Encode the union entry into the type */
906 D->Type[0].C = T_UNION;
907 SetSymEntry (D->Type, Entry);
908 D->Type[1].C = T_END;
914 if (CurTok.Tok == TOK_IDENT) {
915 strcpy (Ident, CurTok.Ident);
918 AnonName (Ident, "struct");
920 /* Remember we have an extra type decl */
921 D->Flags |= DS_EXTRA_TYPE;
922 /* Declare the struct in the current scope */
923 Entry = ParseStructDecl (Ident);
924 /* Encode the struct entry into the type */
925 D->Type[0].C = T_STRUCT;
926 SetSymEntry (D->Type, Entry);
927 D->Type[1].C = T_END;
932 if (CurTok.Tok != TOK_LCURLY) {
934 if (CurTok.Tok == TOK_IDENT) {
935 /* Find an entry with this name */
936 Entry = FindTagSym (CurTok.Ident);
938 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
939 Error ("Symbol `%s' is already different kind", Entry->Name);
942 /* Insert entry into table ### */
944 /* Skip the identifier */
947 Error ("Identifier expected");
950 /* Remember we have an extra type decl */
951 D->Flags |= DS_EXTRA_TYPE;
952 /* Parse the enum decl */
954 D->Type[0].C = T_INT;
955 D->Type[1].C = T_END;
959 Entry = FindSym (CurTok.Ident);
960 if (Entry && SymIsTypeDef (Entry)) {
963 TypeCopy (D->Type, Entry->Type);
970 Error ("Type expected");
971 D->Type[0].C = T_INT;
972 D->Type[1].C = T_END;
974 D->Flags |= DS_DEF_TYPE;
975 D->Type[0].C = (TypeCode) Default;
976 D->Type[1].C = T_END;
981 /* There may also be qualifiers *after* the initial type */
982 D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
987 static Type* ParamTypeCvt (Type* T)
988 /* If T is an array, convert it to a pointer else do nothing. Return the
992 if (IsTypeArray (T)) {
1000 static void ParseOldStyleParamList (FuncDesc* F)
1001 /* Parse an old style (K&R) parameter list */
1004 while (CurTok.Tok != TOK_RPAREN) {
1006 /* List of identifiers expected */
1007 if (CurTok.Tok != TOK_IDENT) {
1008 Error ("Identifier expected");
1011 /* Create a symbol table entry with type int */
1012 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1014 /* Count arguments */
1017 /* Skip the identifier */
1020 /* Check for more parameters */
1021 if (CurTok.Tok == TOK_COMMA) {
1028 /* Skip right paren. We must explicitly check for one here, since some of
1029 * the breaks above bail out without checking.
1033 /* An optional list of type specifications follows */
1034 while (CurTok.Tok != TOK_LCURLY) {
1038 /* Read the declaration specifier */
1039 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1041 /* We accept only auto and register as storage class specifiers, but
1042 * we ignore all this, since we use auto anyway.
1044 if ((Spec.StorageClass & SC_AUTO) == 0 &&
1045 (Spec.StorageClass & SC_REGISTER) == 0) {
1046 Error ("Illegal storage class");
1049 /* Parse a comma separated variable list */
1054 /* Read the parameter */
1055 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1056 if (Decl.Ident[0] != '\0') {
1058 /* We have a name given. Search for the symbol */
1059 SymEntry* Sym = FindLocalSym (Decl.Ident);
1061 /* Check if we already changed the type for this
1064 if (Sym->Flags & SC_DEFTYPE) {
1065 /* Found it, change the default type to the one given */
1066 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1067 /* Reset the "default type" flag */
1068 Sym->Flags &= ~SC_DEFTYPE;
1070 /* Type has already been changed */
1071 Error ("Redefinition for parameter `%s'", Sym->Name);
1074 Error ("Unknown identifier: `%s'", Decl.Ident);
1078 if (CurTok.Tok == TOK_COMMA) {
1086 /* Variable list must be semicolon terminated */
1093 static void ParseAnsiParamList (FuncDesc* F)
1094 /* Parse a new style (ANSI) parameter list */
1097 while (CurTok.Tok != TOK_RPAREN) {
1103 /* Allow an ellipsis as last parameter */
1104 if (CurTok.Tok == TOK_ELLIPSIS) {
1106 F->Flags |= FD_VARIADIC;
1110 /* Read the declaration specifier */
1111 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1113 /* We accept only auto and register as storage class specifiers */
1114 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1115 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1116 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1117 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1119 Error ("Illegal storage class");
1120 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1123 /* Allow parameters without a name, but remember if we had some to
1124 * eventually print an error message later.
1126 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1127 if (Decl.Ident[0] == '\0') {
1129 /* Unnamed symbol. Generate a name that is not user accessible,
1130 * then handle the symbol normal.
1132 AnonName (Decl.Ident, "param");
1133 F->Flags |= FD_UNNAMED_PARAMS;
1135 /* Clear defined bit on nonames */
1136 Decl.StorageClass &= ~SC_DEF;
1139 /* Parse an attribute ### */
1140 ParseAttribute (&Decl, &Attr);
1142 /* Create a symbol table entry */
1143 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1145 /* Count arguments */
1148 /* Check for more parameters */
1149 if (CurTok.Tok == TOK_COMMA) {
1156 /* Skip right paren. We must explicitly check for one here, since some of
1157 * the breaks above bail out without checking.
1161 /* Check if this is a function definition */
1162 if (CurTok.Tok == TOK_LCURLY) {
1163 /* Print an error if we have unnamed parameters and cc65 extensions
1166 if (IS_Get (&Standard) != STD_CC65 &&
1167 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
1168 Error ("Parameter name omitted");
1175 static FuncDesc* ParseFuncDecl (void)
1176 /* Parse the argument list of a function. */
1181 /* Create a new function descriptor */
1182 FuncDesc* F = NewFuncDesc ();
1184 /* Enter a new lexical level */
1185 EnterFunctionLevel ();
1187 /* Check for several special parameter lists */
1188 if (CurTok.Tok == TOK_RPAREN) {
1189 /* Parameter list is empty */
1190 F->Flags |= (FD_EMPTY | FD_VARIADIC);
1191 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1192 /* Parameter list declared as void */
1194 F->Flags |= FD_VOID_PARAM;
1195 } else if (CurTok.Tok == TOK_IDENT &&
1196 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1197 /* If the identifier is a typedef, we have a new style parameter list,
1198 * if it's some other identifier, it's an old style parameter list.
1200 Sym = FindSym (CurTok.Ident);
1201 if (Sym == 0 || !SymIsTypeDef (Sym)) {
1202 /* Old style (K&R) function. */
1203 F->Flags |= FD_OLDSTYLE;
1208 if ((F->Flags & FD_OLDSTYLE) == 0) {
1209 /* New style function */
1210 ParseAnsiParamList (F);
1212 /* Old style function */
1213 ParseOldStyleParamList (F);
1216 /* Remember the last function parameter. We need it later for several
1217 * purposes, for example when passing stuff to fastcall functions. Since
1218 * more symbols are added to the table, it is easier if we remember it
1219 * now, since it is currently the last entry in the symbol table.
1221 F->LastParam = GetSymTab()->SymTail;
1223 /* Assign offsets. If the function has a variable parameter list,
1224 * there's one additional byte (the arg size).
1226 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1229 unsigned Size = CheckedSizeOf (Sym->Type);
1230 if (SymIsRegVar (Sym)) {
1231 Sym->V.R.SaveOffs = Offs;
1236 F->ParamSize += Size;
1240 /* Leave the lexical level remembering the symbol tables */
1241 RememberFunctionLevel (F);
1243 /* Return the function descriptor */
1249 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1250 /* Recursively process declarators. Build a type array in reverse order. */
1252 /* Read optional function or pointer qualifiers. These modify the
1253 * identifier or token to the right. For convenience, we allow the fastcall
1254 * qualifier also for pointers here. If it is a pointer-to-function, the
1255 * qualifier will later be transfered to the function itself. If it's a
1256 * pointer to something else, it will be flagged as an error.
1258 TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL);
1260 /* Pointer to something */
1261 if (CurTok.Tok == TOK_STAR) {
1266 /* Allow const, restrict and volatile qualifiers */
1267 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1269 /* Parse the type, the pointer points to */
1270 Declarator (Spec, D, Mode);
1273 AddTypeToDeclaration (D, T_PTR | Qualifiers);
1277 if (CurTok.Tok == TOK_LPAREN) {
1279 Declarator (Spec, D, Mode);
1282 /* Things depend on Mode now:
1283 * - Mode == DM_NEED_IDENT means:
1284 * we *must* have a type and a variable identifer.
1285 * - Mode == DM_NO_IDENT means:
1286 * we must have a type but no variable identifer
1287 * (if there is one, it's not read).
1288 * - Mode == DM_ACCEPT_IDENT means:
1289 * we *may* have an identifier. If there is an identifier,
1290 * it is read, but it is no error, if there is none.
1292 if (Mode == DM_NO_IDENT) {
1294 } else if (CurTok.Tok == TOK_IDENT) {
1295 strcpy (D->Ident, CurTok.Ident);
1298 if (Mode == DM_NEED_IDENT) {
1299 Error ("Identifier expected");
1305 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1306 if (CurTok.Tok == TOK_LPAREN) {
1308 /* Function declaration */
1311 /* Skip the opening paren */
1314 /* Parse the function declaration */
1315 F = ParseFuncDecl ();
1317 /* We cannot specify fastcall for variadic functions */
1318 if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1319 Error ("Variadic functions cannot be `__fastcall'");
1320 Qualifiers &= ~T_QUAL_FASTCALL;
1323 /* Add the function type. Be sure to bounds check the type buffer */
1324 NeedTypeSpace (D, 1);
1325 D->Type[D->Index].C = T_FUNC | Qualifiers;
1326 D->Type[D->Index].A.P = F;
1329 /* Qualifiers now used */
1330 Qualifiers = T_QUAL_NONE;
1333 /* Array declaration. */
1334 long Size = UNSPECIFIED;
1336 /* We cannot have any qualifiers for an array */
1337 if (Qualifiers != T_QUAL_NONE) {
1338 Error ("Invalid qualifiers for array");
1339 Qualifiers = T_QUAL_NONE;
1342 /* Skip the left bracket */
1345 /* Read the size if it is given */
1346 if (CurTok.Tok != TOK_RBRACK) {
1348 ConstAbsIntExpr (hie1, &Expr);
1349 if (Expr.IVal <= 0) {
1350 if (D->Ident[0] != '\0') {
1351 Error ("Size of array `%s' is invalid", D->Ident);
1353 Error ("Size of array is invalid");
1360 /* Skip the right bracket */
1363 /* Add the array type with the size to the type */
1364 NeedTypeSpace (D, 1);
1365 D->Type[D->Index].C = T_ARRAY;
1366 D->Type[D->Index].A.L = Size;
1371 /* If we have remaining qualifiers, flag them as invalid */
1372 if (Qualifiers & T_QUAL_NEAR) {
1373 Error ("Invalid `__near__' qualifier");
1375 if (Qualifiers & T_QUAL_FAR) {
1376 Error ("Invalid `__far__' qualifier");
1378 if (Qualifiers & T_QUAL_FASTCALL) {
1379 Error ("Invalid `__fastcall__' qualifier");
1385 /*****************************************************************************/
1387 /*****************************************************************************/
1391 Type* ParseType (Type* T)
1392 /* Parse a complete type specification */
1397 /* Get a type without a default */
1398 InitDeclSpec (&Spec);
1399 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1401 /* Parse additional declarators */
1402 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1404 /* Copy the type to the target buffer */
1405 TypeCopy (T, Decl.Type);
1407 /* Return a pointer to the target buffer */
1413 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1414 /* Parse a variable, type or function declaration */
1416 /* Initialize the Declaration struct */
1417 InitDeclaration (D);
1419 /* Get additional declarators and the identifier */
1420 Declarator (Spec, D, Mode);
1422 /* Add the base type. */
1423 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1424 TypeCopy (D->Type + D->Index, Spec->Type);
1426 /* Use the storage class from the declspec */
1427 D->StorageClass = Spec->StorageClass;
1429 /* Do several fixes on qualifiers */
1430 FixQualifiers (D->Type);
1432 /* If we have a function, add a special storage class */
1433 if (IsTypeFunc (D->Type)) {
1434 D->StorageClass |= SC_FUNC;
1437 /* Check several things for function or function pointer types */
1438 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1440 /* A function. Check the return type */
1441 Type* RetType = GetFuncReturn (D->Type);
1443 /* Functions may not return functions or arrays */
1444 if (IsTypeFunc (RetType)) {
1445 Error ("Functions are not allowed to return functions");
1446 } else if (IsTypeArray (RetType)) {
1447 Error ("Functions are not allowed to return arrays");
1450 /* The return type must not be qualified */
1451 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1453 if (GetType (RetType) == T_TYPE_VOID) {
1454 /* A qualified void type is always an error */
1455 Error ("function definition has qualified void return type");
1457 /* For others, qualifiers are ignored */
1458 Warning ("type qualifiers ignored on function return type");
1459 RetType[0].C = UnqualifiedType (RetType[0].C);
1463 /* Warn about an implicit int return in the function */
1464 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1465 RetType[0].C == T_INT && RetType[1].C == T_END) {
1466 /* Function has an implicit int return. Output a warning if we don't
1467 * have the C89 standard enabled explicitly.
1469 if (IS_Get (&Standard) >= STD_C99) {
1470 Warning ("Implicit `int' return type is an obsolete feature");
1472 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1477 /* For anthing that is not a function or typedef, check for an implicit
1480 if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1481 (D->StorageClass & SC_TYPEDEF) != SC_TYPEDEF) {
1482 /* If the standard was not set explicitly to C89, print a warning
1483 * for variables with implicit int type.
1485 if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1486 Warning ("Implicit `int' is an obsolete feature");
1490 /* Check the size of the generated type */
1491 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1492 unsigned Size = SizeOf (D->Type);
1493 if (Size >= 0x10000) {
1494 if (D->Ident[0] != '\0') {
1495 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1497 Error ("Invalid size in declaration (0x%06X)", Size);
1506 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1507 /* Parse a declaration specification */
1509 TypeCode Qualifiers;
1511 /* Initialize the DeclSpec struct */
1514 /* There may be qualifiers *before* the storage class specifier */
1515 Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1517 /* Now get the storage class specifier for this declaration */
1518 ParseStorageClass (D, DefStorage);
1520 /* Parse the type specifiers passing any initial type qualifiers */
1521 ParseTypeSpec (D, DefType, Qualifiers);
1526 void CheckEmptyDecl (const DeclSpec* D)
1527 /* Called after an empty type declaration (that is, a type declaration without
1528 * a variable). Checks if the declaration does really make sense and issues a
1532 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1533 Warning ("Useless declaration");
1539 static void SkipInitializer (unsigned BracesExpected)
1540 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1541 * smart so we don't have too many following errors.
1544 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1545 switch (CurTok.Tok) {
1546 case TOK_RCURLY: --BracesExpected; break;
1547 case TOK_LCURLY: ++BracesExpected; break;
1556 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1557 /* Accept any number of opening curly braces around an initialization, skip
1558 * them and return the number. If the number of curly braces is less than
1559 * BracesNeeded, issue a warning.
1562 unsigned BraceCount = 0;
1563 while (CurTok.Tok == TOK_LCURLY) {
1567 if (BraceCount < BracesNeeded) {
1568 Error ("`{' expected");
1575 static void ClosingCurlyBraces (unsigned BracesExpected)
1576 /* Accept and skip the given number of closing curly braces together with
1577 * an optional comma. Output an error messages, if the input does not contain
1578 * the expected number of braces.
1581 while (BracesExpected) {
1582 if (CurTok.Tok == TOK_RCURLY) {
1584 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1588 Error ("`}' expected");
1597 static void DefineData (ExprDesc* Expr)
1598 /* Output a data definition for the given expression */
1600 switch (ED_GetLoc (Expr)) {
1603 /* Absolute: numeric address or const */
1604 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1608 /* Global variable */
1609 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1614 /* Static variable or literal in the literal pool */
1615 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1618 case E_LOC_REGISTER:
1619 /* Register variable. Taking the address is usually not
1622 if (IS_Get (&AllowRegVarAddr) == 0) {
1623 Error ("Cannot take the address of a register variable");
1625 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1631 Error ("Non constant initializer");
1635 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1641 static unsigned ParseScalarInit (Type* T)
1642 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1646 /* Optional opening brace */
1647 unsigned BraceCount = OpeningCurlyBraces (0);
1649 /* We warn if an initializer for a scalar contains braces, because this is
1650 * quite unusual and often a sign for some problem in the input.
1652 if (BraceCount > 0) {
1653 Warning ("Braces around scalar initializer");
1656 /* Get the expression and convert it to the target type */
1657 ConstExpr (hie1, &ED);
1658 TypeConversion (&ED, T);
1660 /* Output the data */
1663 /* Close eventually opening braces */
1664 ClosingCurlyBraces (BraceCount);
1672 static unsigned ParsePointerInit (Type* T)
1673 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1675 /* Optional opening brace */
1676 unsigned BraceCount = OpeningCurlyBraces (0);
1680 ConstExpr (hie1, &ED);
1681 TypeConversion (&ED, T);
1683 /* Output the data */
1686 /* Close eventually opening braces */
1687 ClosingCurlyBraces (BraceCount);
1695 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1696 /* Parse initializaton for arrays. Return the number of data bytes. */
1700 /* Get the array data */
1701 Type* ElementType = GetElementType (T);
1702 unsigned ElementSize = CheckedSizeOf (ElementType);
1703 long ElementCount = GetElementCount (T);
1705 /* Special handling for a character array initialized by a literal */
1706 if (IsTypeChar (ElementType) &&
1707 (CurTok.Tok == TOK_SCONST ||
1708 (CurTok.Tok == TOK_LCURLY && NextTok.Tok == TOK_SCONST))) {
1710 /* Char array initialized by string constant */
1714 /* If we initializer is enclosed in brackets, remember this fact and
1715 * skip the opening bracket.
1717 NeedParen = (CurTok.Tok == TOK_LCURLY);
1722 /* Get the initializer string and its size */
1723 Str = GetLiteral (CurTok.IVal);
1724 Count = GetLiteralPoolOffs () - CurTok.IVal;
1726 /* Translate into target charset */
1727 TranslateLiteralPool (CurTok.IVal);
1729 /* If the array is one too small for the string literal, omit the
1732 if (ElementCount != UNSPECIFIED &&
1733 ElementCount != FLEXIBLE &&
1734 Count == ElementCount + 1) {
1735 /* Omit the trailing zero */
1739 /* Output the data */
1740 g_defbytes (Str, Count);
1742 /* Remove string from pool */
1743 ResetLiteralPoolOffs (CurTok.IVal);
1746 /* If the initializer was enclosed in curly braces, we need a closing
1758 /* Initialize the array members */
1760 while (CurTok.Tok != TOK_RCURLY) {
1761 /* Flexible array members may not be initialized within
1762 * an array (because the size of each element may differ
1765 ParseInitInternal (ElementType, 0);
1767 if (CurTok.Tok != TOK_COMMA)
1772 /* Closing curly braces */
1776 if (ElementCount == UNSPECIFIED) {
1777 /* Number of elements determined by initializer */
1778 SetElementCount (T, Count);
1779 ElementCount = Count;
1780 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1781 /* In non ANSI mode, allow initialization of flexible array
1784 ElementCount = Count;
1785 } else if (Count < ElementCount) {
1786 g_zerobytes ((ElementCount - Count) * ElementSize);
1787 } else if (Count > ElementCount) {
1788 Error ("Too many initializers");
1790 return ElementCount * ElementSize;
1795 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1796 /* Parse initialization of a struct or union. Return the number of data bytes. */
1800 unsigned StructSize;
1804 /* Consume the opening curly brace */
1807 /* Get a pointer to the struct entry from the type */
1808 Entry = GetSymEntry (T);
1810 /* Get the size of the struct from the symbol table entry */
1811 StructSize = Entry->V.S.Size;
1813 /* Check if this struct definition has a field table. If it doesn't, it
1814 * is an incomplete definition.
1816 Tab = Entry->V.S.SymTab;
1818 Error ("Cannot initialize variables with incomplete type");
1819 /* Try error recovery */
1820 SkipInitializer (1);
1821 /* Nothing initialized */
1825 /* Get a pointer to the list of symbols */
1826 Entry = Tab->SymHead;
1828 /* Initialize fields */
1830 while (CurTok.Tok != TOK_RCURLY) {
1832 Error ("Too many initializers");
1833 SkipInitializer (1);
1836 /* Parse initialization of one field. Flexible array members may
1837 * only be initialized if they are the last field (or part of the
1838 * last struct field).
1840 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1841 Entry = Entry->NextSym;
1842 if (CurTok.Tok != TOK_COMMA)
1847 /* Consume the closing curly brace */
1850 /* If there are struct fields left, reserve additional storage */
1851 if (Size < StructSize) {
1852 g_zerobytes (StructSize - Size);
1856 /* Return the actual number of bytes initialized. This number may be
1857 * larger than StructSize if flexible array members are present and were
1858 * initialized (possible in non ANSI mode).
1865 static unsigned ParseVoidInit (void)
1866 /* Parse an initialization of a void variable (special cc65 extension).
1867 * Return the number of bytes initialized.
1876 /* Allow an arbitrary list of values */
1879 ConstExpr (hie1, &Expr);
1880 switch (UnqualifiedType (Expr.Type[0].C)) {
1884 if (ED_IsConstAbsInt (&Expr)) {
1885 /* Make it byte sized */
1889 Size += SIZEOF_CHAR;
1898 if (ED_IsConstAbsInt (&Expr)) {
1899 /* Make it word sized */
1900 Expr.IVal &= 0xFFFF;
1908 if (ED_IsConstAbsInt (&Expr)) {
1909 /* Make it dword sized */
1910 Expr.IVal &= 0xFFFFFFFF;
1913 Size += SIZEOF_LONG;
1917 Error ("Illegal type in initialization");
1922 if (CurTok.Tok != TOK_COMMA) {
1927 } while (CurTok.Tok != TOK_RCURLY);
1932 /* Return the number of bytes initialized */
1938 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
1939 /* Parse initialization of variables. Return the number of data bytes. */
1941 switch (UnqualifiedType (T->C)) {
1953 return ParseScalarInit (T);
1956 return ParsePointerInit (T);
1959 return ParseArrayInit (T, AllowFlexibleMembers);
1963 return ParseStructInit (T, AllowFlexibleMembers);
1966 if (IS_Get (&Standard) == STD_CC65) {
1967 /* Special cc65 extension in non ANSI mode */
1968 return ParseVoidInit ();
1973 Error ("Illegal type");
1981 unsigned ParseInit (Type* T)
1982 /* Parse initialization of variables. Return the number of data bytes. */
1984 /* Parse the initialization. Flexible array members can only be initialized
1987 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
1989 /* The initialization may not generate code on global level, because code
1990 * outside function scope will never get executed.
1992 if (HaveGlobalCode ()) {
1993 Error ("Non constant initializers");
1994 RemoveGlobalCode ();
1997 /* Return the size needed for the initialization */