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;
260 static void NeedTypeSpace (Declaration* D, unsigned Count)
261 /* Check if there is enough space for Count type specifiers within D */
263 if (D->Index + Count >= MAXTYPELEN) {
264 /* We must call Fatal() here, since calling Error() will try to
265 * continue, and the declaration type is not correctly terminated
266 * in case we come here.
268 Fatal ("Too many type specifiers");
274 static void AddTypeToDeclaration (Declaration* D, TypeCode T)
275 /* Add a type specifier to the type of a declaration */
277 NeedTypeSpace (D, 1);
278 D->Type[D->Index++].C = T;
283 static void FixQualifiers (Type* DataType)
284 /* Apply several fixes to qualifiers */
289 /* Using typedefs, it is possible to generate declarations that have
290 * type qualifiers attached to an array, not the element type. Go and
295 while (T->C != T_END) {
296 if (IsTypeArray (T)) {
297 /* Extract any type qualifiers */
298 Q |= GetQualifier (T);
299 T->C = UnqualifiedType (T->C);
301 /* Add extracted type qualifiers here */
307 /* Q must be empty now */
308 CHECK (Q == T_QUAL_NONE);
310 /* Do some fixes on pointers and functions. */
312 while (T->C != T_END) {
315 /* Fastcall qualifier on the pointer? */
316 if (IsQualFastcall (T)) {
317 /* Pointer to function which is not fastcall? */
318 if (IsTypeFunc (T+1) && !IsQualFastcall (T+1)) {
319 /* Move the fastcall qualifier from the pointer to
322 T[0].C &= ~T_QUAL_FASTCALL;
323 T[1].C |= T_QUAL_FASTCALL;
325 Error ("Invalid `_fastcall__' qualifier for pointer");
329 /* Apply the default far and near qualifiers if none are given */
330 Q = (T[0].C & T_QUAL_ADDRSIZE);
331 if (Q == T_QUAL_NONE) {
332 /* No address size qualifiers specified */
333 if (IsTypeFunc (T+1)) {
334 /* Pointer to function. Use the qualifier from the function
335 * or the default if the function don't has one.
337 Q = (T[1].C & T_QUAL_ADDRSIZE);
338 if (Q == T_QUAL_NONE) {
339 Q = CodeAddrSizeQualifier ();
342 Q = DataAddrSizeQualifier ();
346 /* We have address size qualifiers. If followed by a function,
347 * apply these also to the function.
349 if (IsTypeFunc (T+1)) {
350 TypeCode FQ = (T[1].C & T_QUAL_ADDRSIZE);
351 if (FQ == T_QUAL_NONE) {
353 } else if (FQ != Q) {
354 Error ("Address size qualifier mismatch");
355 T[1].C = (T[1].C & ~T_QUAL_ADDRSIZE) | Q;
360 } else if (IsTypeFunc (T)) {
362 /* Apply the default far and near qualifiers if none are given */
363 if ((T[0].C & T_QUAL_ADDRSIZE) == 0) {
364 T[0].C |= CodeAddrSizeQualifier ();
374 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
375 /* Parse a storage class */
377 /* Assume we're using an explicit storage class */
378 D->Flags &= ~DS_DEF_STORAGE;
380 /* Check the storage class given */
381 switch (CurTok.Tok) {
384 D->StorageClass = SC_EXTERN | SC_STATIC;
389 D->StorageClass = SC_STATIC;
394 D->StorageClass = SC_REGISTER | SC_STATIC;
399 D->StorageClass = SC_AUTO;
404 D->StorageClass = SC_TYPEDEF;
409 /* No storage class given, use default */
410 D->Flags |= DS_DEF_STORAGE;
411 D->StorageClass = DefStorage;
418 static void ParseEnumDecl (void)
419 /* Process an enum declaration . */
424 /* Accept forward definitions */
425 if (CurTok.Tok != TOK_LCURLY) {
429 /* Skip the opening curly brace */
432 /* Read the enum tags */
434 while (CurTok.Tok != TOK_RCURLY) {
436 /* We expect an identifier */
437 if (CurTok.Tok != TOK_IDENT) {
438 Error ("Identifier expected");
442 /* Remember the identifier and skip it */
443 strcpy (Ident, CurTok.Ident);
446 /* Check for an assigned value */
447 if (CurTok.Tok == TOK_ASSIGN) {
450 ConstAbsIntExpr (hie1, &Expr);
454 /* Add an entry to the symbol table */
455 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
457 /* Check for end of definition */
458 if (CurTok.Tok != TOK_COMMA)
467 static int ParseFieldWidth (Declaration* Decl)
468 /* Parse an optional field width. Returns -1 if no field width is speficied,
469 * otherwise the width of the field.
474 if (CurTok.Tok != TOK_COLON) {
475 /* No bit-field declaration */
481 ConstAbsIntExpr (hie1, &Expr);
483 Error ("Negative width in bit-field");
486 if (Expr.IVal > (int) INT_BITS) {
487 Error ("Width of bit-field exceeds its type");
490 if (Expr.IVal == 0 && Decl->Ident[0] != '\0') {
491 Error ("Zero width for named bit-field");
494 if (!IsTypeInt (Decl->Type)) {
495 /* Only integer types may be used for bit-fields */
496 Error ("Bit-field has invalid type");
500 /* Return the field width */
501 return (int) Expr.IVal;
506 static SymEntry* StructOrUnionForwardDecl (const char* Name)
507 /* Handle a struct or union forward decl */
509 /* Try to find a struct with the given name. If there is none,
510 * insert a forward declaration into the current lexical level.
512 SymEntry* Entry = FindTagSym (Name);
514 Entry = AddStructSym (Name, 0, 0);
515 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) != SC_STRUCT) {
516 /* Already defined in the level, but no struct */
517 Error ("Symbol `%s' is already different kind", Name);
524 static SymEntry* ParseUnionDecl (const char* Name)
525 /* Parse a union declaration. */
530 int FieldWidth; /* Width in bits, -1 if not a bit-field */
535 if (CurTok.Tok != TOK_LCURLY) {
536 /* Just a forward declaration. */
537 return StructOrUnionForwardDecl (Name);
540 /* Add a forward declaration for the struct in the current lexical level */
541 Entry = AddStructSym (Name, 0, 0);
543 /* Skip the curly brace */
546 /* Enter a new lexical level for the struct */
549 /* Parse union fields */
551 while (CurTok.Tok != TOK_RCURLY) {
553 /* Get the type of the entry */
555 InitDeclSpec (&Spec);
556 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
558 /* Read fields with this type */
563 /* Get type and name of the struct field */
564 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
566 /* Check for a bit-field declaration */
567 FieldWidth = ParseFieldWidth (&Decl);
569 /* Ignore zero sized bit fields in a union */
570 if (FieldWidth == 0) {
574 /* Check for fields without a name */
575 if (Decl.Ident[0] == '\0') {
576 /* Any field without a name is legal but useless in a union */
577 Warning ("Declaration does not declare anything");
582 FieldSize = CheckedSizeOf (Decl.Type);
583 if (FieldSize > UnionSize) {
584 UnionSize = FieldSize;
587 /* Add a field entry to the table. */
588 if (FieldWidth > 0) {
589 AddBitField (Decl.Ident, 0, 0, FieldWidth);
591 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, 0);
594 NextMember: if (CurTok.Tok != TOK_COMMA) {
602 /* Skip the closing brace */
605 /* Remember the symbol table and leave the struct level */
606 FieldTab = GetSymTab ();
609 /* Make a real entry from the forward decl and return it */
610 return AddStructSym (Name, UnionSize, FieldTab);
615 static SymEntry* ParseStructDecl (const char* Name)
616 /* Parse a struct declaration. */
621 int BitOffs; /* Bit offset for bit-fields */
622 int FieldWidth; /* Width in bits, -1 if not a bit-field */
627 if (CurTok.Tok != TOK_LCURLY) {
628 /* Just a forward declaration. */
629 return StructOrUnionForwardDecl (Name);
632 /* Add a forward declaration for the struct in the current lexical level */
633 Entry = AddStructSym (Name, 0, 0);
635 /* Skip the curly brace */
638 /* Enter a new lexical level for the struct */
641 /* Parse struct fields */
645 while (CurTok.Tok != TOK_RCURLY) {
647 /* Get the type of the entry */
649 InitDeclSpec (&Spec);
650 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
652 /* Read fields with this type */
658 /* If we had a flexible array member before, no other fields can
661 if (FlexibleMember) {
662 Error ("Flexible array member must be last field");
663 FlexibleMember = 0; /* Avoid further errors */
666 /* Get type and name of the struct field */
667 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
669 /* Check for a bit-field declaration */
670 FieldWidth = ParseFieldWidth (&Decl);
672 /* If this is not a bit field, or the bit field is too large for
673 * the remainder of the current member, or we have a bit field
674 * with width zero, align the struct to the next member by adding
675 * a member with an anonymous name.
678 if (FieldWidth <= 0 || (BitOffs + FieldWidth) > (int) INT_BITS) {
680 /* We need an anonymous name */
681 AnonName (Ident, "bit-field");
683 /* Add an anonymous bit-field that aligns to the next
686 AddBitField (Ident, StructSize, BitOffs, INT_BITS - BitOffs);
689 StructSize += SIZEOF_INT;
694 /* Apart from the above, a bit field with width 0 is not processed
697 if (FieldWidth == 0) {
701 /* Check for fields without names */
702 if (Decl.Ident[0] == '\0') {
703 if (FieldWidth < 0) {
704 /* A non bit-field without a name is legal but useless */
705 Warning ("Declaration does not declare anything");
708 /* A bit-field without a name will get an anonymous one */
709 AnonName (Decl.Ident, "bit-field");
713 /* Check if this field is a flexible array member, and
714 * calculate the size of the field.
716 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
717 /* Array with unspecified size */
718 if (StructSize == 0) {
719 Error ("Flexible array member cannot be first struct field");
722 /* Assume zero for size calculations */
723 SetElementCount (Decl.Type, FLEXIBLE);
726 /* Add a field entry to the table */
727 if (FieldWidth > 0) {
728 /* Add full byte from the bit offset to the variable offset.
729 * This simplifies handling he bit-field as a char type
732 unsigned Offs = StructSize + (BitOffs / CHAR_BITS);
733 AddBitField (Decl.Ident, Offs, BitOffs % CHAR_BITS, FieldWidth);
734 BitOffs += FieldWidth;
735 CHECK (BitOffs <= (int) INT_BITS);
736 if (BitOffs == INT_BITS) {
737 StructSize += SIZEOF_INT;
741 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, StructSize);
742 if (!FlexibleMember) {
743 StructSize += CheckedSizeOf (Decl.Type);
747 NextMember: if (CurTok.Tok != TOK_COMMA) {
755 /* If we have bits from bit-fields left, add them to the size. */
757 StructSize += ((BitOffs + CHAR_BITS - 1) / CHAR_BITS);
760 /* Skip the closing brace */
763 /* Remember the symbol table and leave the struct level */
764 FieldTab = GetSymTab ();
767 /* Make a real entry from the forward decl and return it */
768 return AddStructSym (Name, StructSize, FieldTab);
773 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
774 /* Parse a type specificier */
779 /* Assume we have an explicit type */
780 D->Flags &= ~DS_DEF_TYPE;
782 /* Read type qualifiers if we have any */
783 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
785 /* Look at the data type */
786 switch (CurTok.Tok) {
790 D->Type[0].C = T_VOID;
791 D->Type[1].C = T_END;
796 D->Type[0].C = GetDefaultChar();
797 D->Type[1].C = T_END;
802 if (CurTok.Tok == TOK_UNSIGNED) {
805 D->Type[0].C = T_ULONG;
806 D->Type[1].C = T_END;
810 D->Type[0].C = T_LONG;
811 D->Type[1].C = T_END;
817 if (CurTok.Tok == TOK_UNSIGNED) {
820 D->Type[0].C = T_USHORT;
821 D->Type[1].C = T_END;
825 D->Type[0].C = T_SHORT;
826 D->Type[1].C = T_END;
832 D->Type[0].C = T_INT;
833 D->Type[1].C = T_END;
838 switch (CurTok.Tok) {
842 D->Type[0].C = T_SCHAR;
843 D->Type[1].C = T_END;
849 D->Type[0].C = T_SHORT;
850 D->Type[1].C = T_END;
856 D->Type[0].C = T_LONG;
857 D->Type[1].C = T_END;
865 D->Type[0].C = T_INT;
866 D->Type[1].C = T_END;
873 switch (CurTok.Tok) {
877 D->Type[0].C = T_UCHAR;
878 D->Type[1].C = T_END;
884 D->Type[0].C = T_USHORT;
885 D->Type[1].C = T_END;
891 D->Type[0].C = T_ULONG;
892 D->Type[1].C = T_END;
900 D->Type[0].C = T_UINT;
901 D->Type[1].C = T_END;
908 D->Type[0].C = T_FLOAT;
909 D->Type[1].C = T_END;
914 D->Type[0].C = T_DOUBLE;
915 D->Type[1].C = T_END;
921 if (CurTok.Tok == TOK_IDENT) {
922 strcpy (Ident, CurTok.Ident);
925 AnonName (Ident, "union");
927 /* Remember we have an extra type decl */
928 D->Flags |= DS_EXTRA_TYPE;
929 /* Declare the union in the current scope */
930 Entry = ParseUnionDecl (Ident);
931 /* Encode the union entry into the type */
932 D->Type[0].C = T_UNION;
933 SetSymEntry (D->Type, Entry);
934 D->Type[1].C = T_END;
940 if (CurTok.Tok == TOK_IDENT) {
941 strcpy (Ident, CurTok.Ident);
944 AnonName (Ident, "struct");
946 /* Remember we have an extra type decl */
947 D->Flags |= DS_EXTRA_TYPE;
948 /* Declare the struct in the current scope */
949 Entry = ParseStructDecl (Ident);
950 /* Encode the struct entry into the type */
951 D->Type[0].C = T_STRUCT;
952 SetSymEntry (D->Type, Entry);
953 D->Type[1].C = T_END;
958 if (CurTok.Tok != TOK_LCURLY) {
960 if (CurTok.Tok == TOK_IDENT) {
961 /* Find an entry with this name */
962 Entry = FindTagSym (CurTok.Ident);
964 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
965 Error ("Symbol `%s' is already different kind", Entry->Name);
968 /* Insert entry into table ### */
970 /* Skip the identifier */
973 Error ("Identifier expected");
976 /* Remember we have an extra type decl */
977 D->Flags |= DS_EXTRA_TYPE;
978 /* Parse the enum decl */
980 D->Type[0].C = T_INT;
981 D->Type[1].C = T_END;
985 Entry = FindSym (CurTok.Ident);
986 if (Entry && SymIsTypeDef (Entry)) {
989 TypeCopy (D->Type, Entry->Type);
996 Error ("Type expected");
997 D->Type[0].C = T_INT;
998 D->Type[1].C = T_END;
1000 D->Flags |= DS_DEF_TYPE;
1001 D->Type[0].C = (TypeCode) Default;
1002 D->Type[1].C = T_END;
1007 /* There may also be qualifiers *after* the initial type */
1008 D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
1013 static Type* ParamTypeCvt (Type* T)
1014 /* If T is an array, convert it to a pointer else do nothing. Return the
1018 if (IsTypeArray (T)) {
1026 static void ParseOldStyleParamList (FuncDesc* F)
1027 /* Parse an old style (K&R) parameter list */
1030 while (CurTok.Tok != TOK_RPAREN) {
1032 /* List of identifiers expected */
1033 if (CurTok.Tok != TOK_IDENT) {
1034 Error ("Identifier expected");
1037 /* Create a symbol table entry with type int */
1038 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
1040 /* Count arguments */
1043 /* Skip the identifier */
1046 /* Check for more parameters */
1047 if (CurTok.Tok == TOK_COMMA) {
1054 /* Skip right paren. We must explicitly check for one here, since some of
1055 * the breaks above bail out without checking.
1059 /* An optional list of type specifications follows */
1060 while (CurTok.Tok != TOK_LCURLY) {
1064 /* Read the declaration specifier */
1065 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1067 /* We accept only auto and register as storage class specifiers, but
1068 * we ignore all this, since we use auto anyway.
1070 if ((Spec.StorageClass & SC_AUTO) == 0 &&
1071 (Spec.StorageClass & SC_REGISTER) == 0) {
1072 Error ("Illegal storage class");
1075 /* Parse a comma separated variable list */
1080 /* Read the parameter */
1081 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
1082 if (Decl.Ident[0] != '\0') {
1084 /* We have a name given. Search for the symbol */
1085 SymEntry* Sym = FindLocalSym (Decl.Ident);
1087 /* Check if we already changed the type for this
1090 if (Sym->Flags & SC_DEFTYPE) {
1091 /* Found it, change the default type to the one given */
1092 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
1093 /* Reset the "default type" flag */
1094 Sym->Flags &= ~SC_DEFTYPE;
1096 /* Type has already been changed */
1097 Error ("Redefinition for parameter `%s'", Sym->Name);
1100 Error ("Unknown identifier: `%s'", Decl.Ident);
1104 if (CurTok.Tok == TOK_COMMA) {
1112 /* Variable list must be semicolon terminated */
1119 static void ParseAnsiParamList (FuncDesc* F)
1120 /* Parse a new style (ANSI) parameter list */
1123 while (CurTok.Tok != TOK_RPAREN) {
1129 /* Allow an ellipsis as last parameter */
1130 if (CurTok.Tok == TOK_ELLIPSIS) {
1132 F->Flags |= FD_VARIADIC;
1136 /* Read the declaration specifier */
1137 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1139 /* We accept only auto and register as storage class specifiers */
1140 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1141 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1142 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1143 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1145 Error ("Illegal storage class");
1146 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1149 /* Allow parameters without a name, but remember if we had some to
1150 * eventually print an error message later.
1152 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1153 if (Decl.Ident[0] == '\0') {
1155 /* Unnamed symbol. Generate a name that is not user accessible,
1156 * then handle the symbol normal.
1158 AnonName (Decl.Ident, "param");
1159 F->Flags |= FD_UNNAMED_PARAMS;
1161 /* Clear defined bit on nonames */
1162 Decl.StorageClass &= ~SC_DEF;
1165 /* Parse attributes for this parameter */
1166 ParseAttribute (&Decl);
1168 /* Create a symbol table entry */
1169 Sym = AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1171 /* Add attributes if we have any */
1172 SymUseAttr (Sym, &Decl);
1174 /* If the parameter is a struct or union, emit a warning */
1175 if (IsClassStruct (Decl.Type)) {
1176 if (IS_Get (&WarnStructParam)) {
1177 Warning ("Passing struct by value for parameter `%s'", Decl.Ident);
1181 /* Count arguments */
1184 /* Check for more parameters */
1185 if (CurTok.Tok == TOK_COMMA) {
1192 /* Skip right paren. We must explicitly check for one here, since some of
1193 * the breaks above bail out without checking.
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) {
1235 /* New style function */
1236 ParseAnsiParamList (F);
1239 /* Old style function */
1240 ParseOldStyleParamList (F);
1243 /* Remember the last function parameter. We need it later for several
1244 * purposes, for example when passing stuff to fastcall functions. Since
1245 * more symbols are added to the table, it is easier if we remember it
1246 * now, since it is currently the last entry in the symbol table.
1248 F->LastParam = GetSymTab()->SymTail;
1250 /* Assign offsets. If the function has a variable parameter list,
1251 * there's one additional byte (the arg size).
1253 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1256 unsigned Size = CheckedSizeOf (Sym->Type);
1257 if (SymIsRegVar (Sym)) {
1258 Sym->V.R.SaveOffs = Offs;
1263 F->ParamSize += Size;
1267 /* Leave the lexical level remembering the symbol tables */
1268 RememberFunctionLevel (F);
1270 /* Return the function descriptor */
1276 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1277 /* Recursively process declarators. Build a type array in reverse order. */
1279 /* Read optional function or pointer qualifiers. These modify the
1280 * identifier or token to the right. For convenience, we allow the fastcall
1281 * qualifier also for pointers here. If it is a pointer-to-function, the
1282 * qualifier will later be transfered to the function itself. If it's a
1283 * pointer to something else, it will be flagged as an error.
1285 TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL);
1287 /* Pointer to something */
1288 if (CurTok.Tok == TOK_STAR) {
1293 /* Allow const, restrict and volatile qualifiers */
1294 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1296 /* Parse the type, the pointer points to */
1297 Declarator (Spec, D, Mode);
1300 AddTypeToDeclaration (D, T_PTR | Qualifiers);
1304 if (CurTok.Tok == TOK_LPAREN) {
1306 Declarator (Spec, D, Mode);
1309 /* Things depend on Mode now:
1310 * - Mode == DM_NEED_IDENT means:
1311 * we *must* have a type and a variable identifer.
1312 * - Mode == DM_NO_IDENT means:
1313 * we must have a type but no variable identifer
1314 * (if there is one, it's not read).
1315 * - Mode == DM_ACCEPT_IDENT means:
1316 * we *may* have an identifier. If there is an identifier,
1317 * it is read, but it is no error, if there is none.
1319 if (Mode == DM_NO_IDENT) {
1321 } else if (CurTok.Tok == TOK_IDENT) {
1322 strcpy (D->Ident, CurTok.Ident);
1325 if (Mode == DM_NEED_IDENT) {
1326 Error ("Identifier expected");
1332 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1333 if (CurTok.Tok == TOK_LPAREN) {
1335 /* Function declaration */
1338 /* Skip the opening paren */
1341 /* Parse the function declaration */
1342 F = ParseFuncDecl ();
1344 /* We cannot specify fastcall for variadic functions */
1345 if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1346 Error ("Variadic functions cannot be `__fastcall'");
1347 Qualifiers &= ~T_QUAL_FASTCALL;
1350 /* Add the function type. Be sure to bounds check the type buffer */
1351 NeedTypeSpace (D, 1);
1352 D->Type[D->Index].C = T_FUNC | Qualifiers;
1353 D->Type[D->Index].A.P = F;
1356 /* Qualifiers now used */
1357 Qualifiers = T_QUAL_NONE;
1360 /* Array declaration. */
1361 long Size = UNSPECIFIED;
1363 /* We cannot have any qualifiers for an array */
1364 if (Qualifiers != T_QUAL_NONE) {
1365 Error ("Invalid qualifiers for array");
1366 Qualifiers = T_QUAL_NONE;
1369 /* Skip the left bracket */
1372 /* Read the size if it is given */
1373 if (CurTok.Tok != TOK_RBRACK) {
1375 ConstAbsIntExpr (hie1, &Expr);
1376 if (Expr.IVal <= 0) {
1377 if (D->Ident[0] != '\0') {
1378 Error ("Size of array `%s' is invalid", D->Ident);
1380 Error ("Size of array is invalid");
1387 /* Skip the right bracket */
1390 /* Add the array type with the size to the type */
1391 NeedTypeSpace (D, 1);
1392 D->Type[D->Index].C = T_ARRAY;
1393 D->Type[D->Index].A.L = Size;
1398 /* If we have remaining qualifiers, flag them as invalid */
1399 if (Qualifiers & T_QUAL_NEAR) {
1400 Error ("Invalid `__near__' qualifier");
1402 if (Qualifiers & T_QUAL_FAR) {
1403 Error ("Invalid `__far__' qualifier");
1405 if (Qualifiers & T_QUAL_FASTCALL) {
1406 Error ("Invalid `__fastcall__' qualifier");
1412 /*****************************************************************************/
1414 /*****************************************************************************/
1418 Type* ParseType (Type* T)
1419 /* Parse a complete type specification */
1424 /* Get a type without a default */
1425 InitDeclSpec (&Spec);
1426 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1428 /* Parse additional declarators */
1429 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1431 /* Copy the type to the target buffer */
1432 TypeCopy (T, Decl.Type);
1434 /* Return a pointer to the target buffer */
1440 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1441 /* Parse a variable, type or function declaration */
1443 /* Initialize the Declaration struct */
1444 InitDeclaration (D);
1446 /* Get additional declarators and the identifier */
1447 Declarator (Spec, D, Mode);
1449 /* Add the base type. */
1450 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1451 TypeCopy (D->Type + D->Index, Spec->Type);
1453 /* Use the storage class from the declspec */
1454 D->StorageClass = Spec->StorageClass;
1456 /* Do several fixes on qualifiers */
1457 FixQualifiers (D->Type);
1459 /* If we have a function, add a special storage class */
1460 if (IsTypeFunc (D->Type)) {
1461 D->StorageClass |= SC_FUNC;
1464 /* Parse attributes for this declaration */
1467 /* Check several things for function or function pointer types */
1468 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1470 /* A function. Check the return type */
1471 Type* RetType = GetFuncReturn (D->Type);
1473 /* Functions may not return functions or arrays */
1474 if (IsTypeFunc (RetType)) {
1475 Error ("Functions are not allowed to return functions");
1476 } else if (IsTypeArray (RetType)) {
1477 Error ("Functions are not allowed to return arrays");
1480 /* The return type must not be qualified */
1481 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1483 if (GetType (RetType) == T_TYPE_VOID) {
1484 /* A qualified void type is always an error */
1485 Error ("function definition has qualified void return type");
1487 /* For others, qualifiers are ignored */
1488 Warning ("type qualifiers ignored on function return type");
1489 RetType[0].C = UnqualifiedType (RetType[0].C);
1493 /* Warn about an implicit int return in the function */
1494 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1495 RetType[0].C == T_INT && RetType[1].C == T_END) {
1496 /* Function has an implicit int return. Output a warning if we don't
1497 * have the C89 standard enabled explicitly.
1499 if (IS_Get (&Standard) >= STD_C99) {
1500 Warning ("Implicit `int' return type is an obsolete feature");
1502 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1507 /* For anthing that is not a function or typedef, check for an implicit
1510 if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1511 (D->StorageClass & SC_TYPEDEF) != SC_TYPEDEF) {
1512 /* If the standard was not set explicitly to C89, print a warning
1513 * for variables with implicit int type.
1515 if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1516 Warning ("Implicit `int' is an obsolete feature");
1520 /* Check the size of the generated type */
1521 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1522 unsigned Size = SizeOf (D->Type);
1523 if (Size >= 0x10000) {
1524 if (D->Ident[0] != '\0') {
1525 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1527 Error ("Invalid size in declaration (0x%06X)", Size);
1536 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1537 /* Parse a declaration specification */
1539 TypeCode Qualifiers;
1541 /* Initialize the DeclSpec struct */
1544 /* There may be qualifiers *before* the storage class specifier */
1545 Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1547 /* Now get the storage class specifier for this declaration */
1548 ParseStorageClass (D, DefStorage);
1550 /* Parse the type specifiers passing any initial type qualifiers */
1551 ParseTypeSpec (D, DefType, Qualifiers);
1556 void CheckEmptyDecl (const DeclSpec* D)
1557 /* Called after an empty type declaration (that is, a type declaration without
1558 * a variable). Checks if the declaration does really make sense and issues a
1562 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1563 Warning ("Useless declaration");
1569 static void SkipInitializer (unsigned BracesExpected)
1570 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1571 * smart so we don't have too many following errors.
1574 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1575 switch (CurTok.Tok) {
1576 case TOK_RCURLY: --BracesExpected; break;
1577 case TOK_LCURLY: ++BracesExpected; break;
1586 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1587 /* Accept any number of opening curly braces around an initialization, skip
1588 * them and return the number. If the number of curly braces is less than
1589 * BracesNeeded, issue a warning.
1592 unsigned BraceCount = 0;
1593 while (CurTok.Tok == TOK_LCURLY) {
1597 if (BraceCount < BracesNeeded) {
1598 Error ("`{' expected");
1605 static void ClosingCurlyBraces (unsigned BracesExpected)
1606 /* Accept and skip the given number of closing curly braces together with
1607 * an optional comma. Output an error messages, if the input does not contain
1608 * the expected number of braces.
1611 while (BracesExpected) {
1612 if (CurTok.Tok == TOK_RCURLY) {
1614 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1618 Error ("`}' expected");
1627 static void DefineData (ExprDesc* Expr)
1628 /* Output a data definition for the given expression */
1630 switch (ED_GetLoc (Expr)) {
1633 /* Absolute: numeric address or const */
1634 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1638 /* Global variable */
1639 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1644 /* Static variable or literal in the literal pool */
1645 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1648 case E_LOC_REGISTER:
1649 /* Register variable. Taking the address is usually not
1652 if (IS_Get (&AllowRegVarAddr) == 0) {
1653 Error ("Cannot take the address of a register variable");
1655 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1661 Error ("Non constant initializer");
1665 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1671 static void OutputBitFieldData (StructInitData* SI)
1672 /* Output bit field data */
1674 /* Ignore if we have no data */
1675 if (SI->ValBits > 0) {
1677 /* Output the data */
1678 g_defdata (CF_INT | CF_UNSIGNED | CF_CONST, SI->BitVal, 0);
1680 /* Clear the data from SI and account for the size */
1683 SI->Offs += SIZEOF_INT;
1689 static void ParseScalarInitInternal (Type* T, ExprDesc* ED)
1690 /* Parse initializaton for scalar data types. This function will not output the
1691 * data but return it in ED.
1694 /* Optional opening brace */
1695 unsigned BraceCount = OpeningCurlyBraces (0);
1697 /* We warn if an initializer for a scalar contains braces, because this is
1698 * quite unusual and often a sign for some problem in the input.
1700 if (BraceCount > 0) {
1701 Warning ("Braces around scalar initializer");
1704 /* Get the expression and convert it to the target type */
1705 ConstExpr (hie1, ED);
1706 TypeConversion (ED, T);
1708 /* Close eventually opening braces */
1709 ClosingCurlyBraces (BraceCount);
1714 static unsigned ParseScalarInit (Type* T)
1715 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1719 /* Parse initialization */
1720 ParseScalarInitInternal (T, &ED);
1722 /* Output the data */
1731 static unsigned ParsePointerInit (Type* T)
1732 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1734 /* Optional opening brace */
1735 unsigned BraceCount = OpeningCurlyBraces (0);
1739 ConstExpr (hie1, &ED);
1740 TypeConversion (&ED, T);
1742 /* Output the data */
1745 /* Close eventually opening braces */
1746 ClosingCurlyBraces (BraceCount);
1754 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1755 /* Parse initializaton for arrays. Return the number of data bytes. */
1759 /* Get the array data */
1760 Type* ElementType = GetElementType (T);
1761 unsigned ElementSize = CheckedSizeOf (ElementType);
1762 long ElementCount = GetElementCount (T);
1764 /* Special handling for a character array initialized by a literal */
1765 if (IsTypeChar (ElementType) &&
1766 (CurTok.Tok == TOK_SCONST || CurTok.Tok == TOK_WCSCONST ||
1767 (CurTok.Tok == TOK_LCURLY &&
1768 (NextTok.Tok == TOK_SCONST || NextTok.Tok == TOK_WCSCONST)))) {
1770 /* Char array initialized by string constant */
1774 /* If we initializer is enclosed in brackets, remember this fact and
1775 * skip the opening bracket.
1777 NeedParen = (CurTok.Tok == TOK_LCURLY);
1782 /* Get the initializer string and its size */
1783 Str = GetLiteral (CurTok.IVal);
1784 Count = GetLiteralPoolOffs () - CurTok.IVal;
1786 /* Translate into target charset */
1787 TranslateLiteralPool (CurTok.IVal);
1789 /* If the array is one too small for the string literal, omit the
1792 if (ElementCount != UNSPECIFIED &&
1793 ElementCount != FLEXIBLE &&
1794 Count == ElementCount + 1) {
1795 /* Omit the trailing zero */
1799 /* Output the data */
1800 g_defbytes (Str, Count);
1802 /* Remove string from pool */
1803 ResetLiteralPoolOffs (CurTok.IVal);
1806 /* If the initializer was enclosed in curly braces, we need a closing
1818 /* Initialize the array members */
1820 while (CurTok.Tok != TOK_RCURLY) {
1821 /* Flexible array members may not be initialized within
1822 * an array (because the size of each element may differ
1825 ParseInitInternal (ElementType, 0);
1827 if (CurTok.Tok != TOK_COMMA)
1832 /* Closing curly braces */
1836 if (ElementCount == UNSPECIFIED) {
1837 /* Number of elements determined by initializer */
1838 SetElementCount (T, Count);
1839 ElementCount = Count;
1840 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1841 /* In non ANSI mode, allow initialization of flexible array
1844 ElementCount = Count;
1845 } else if (Count < ElementCount) {
1846 g_zerobytes ((ElementCount - Count) * ElementSize);
1847 } else if (Count > ElementCount) {
1848 Error ("Too many initializers");
1850 return ElementCount * ElementSize;
1855 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1856 /* Parse initialization of a struct or union. Return the number of data bytes. */
1863 /* Consume the opening curly brace */
1866 /* Get a pointer to the struct entry from the type */
1867 Entry = GetSymEntry (T);
1869 /* Get the size of the struct from the symbol table entry */
1870 SI.Size = Entry->V.S.Size;
1872 /* Check if this struct definition has a field table. If it doesn't, it
1873 * is an incomplete definition.
1875 Tab = Entry->V.S.SymTab;
1877 Error ("Cannot initialize variables with incomplete type");
1878 /* Try error recovery */
1879 SkipInitializer (1);
1880 /* Nothing initialized */
1884 /* Get a pointer to the list of symbols */
1885 Entry = Tab->SymHead;
1887 /* Initialize fields */
1891 while (CurTok.Tok != TOK_RCURLY) {
1895 Error ("Too many initializers");
1896 SkipInitializer (1);
1900 /* Parse initialization of one field. Bit-fields need a special
1903 if (SymIsBitField (Entry)) {
1909 /* Calculate the bitmask from the bit-field data */
1910 unsigned Mask = (1U << Entry->V.B.BitWidth) - 1U;
1913 CHECK (Entry->V.B.Offs * CHAR_BITS + Entry->V.B.BitOffs ==
1914 SI.Offs * CHAR_BITS + SI.ValBits);
1916 /* This may be an anonymous bit-field, in which case it doesn't
1917 * have an initializer.
1919 if (IsAnonName (Entry->Name)) {
1920 /* Account for the data and output it if we have a full word */
1921 SI.ValBits += Entry->V.B.BitWidth;
1922 CHECK (SI.ValBits <= INT_BITS);
1923 if (SI.ValBits == INT_BITS) {
1924 OutputBitFieldData (&SI);
1928 /* Read the data, check for a constant integer, do a range
1931 ParseScalarInitInternal (type_uint, &ED);
1932 if (!ED_IsConstAbsInt (&ED)) {
1933 Error ("Constant initializer expected");
1934 ED_MakeConstAbsInt (&ED, 1);
1936 if (ED.IVal > (long) Mask) {
1937 Warning ("Truncating value in bit-field initializer");
1938 ED.IVal &= (long) Mask;
1940 Val = (unsigned) ED.IVal;
1943 /* Add the value to the currently stored bit-field value */
1944 Shift = (Entry->V.B.Offs - SI.Offs) * CHAR_BITS + Entry->V.B.BitOffs;
1945 SI.BitVal |= (Val << Shift);
1947 /* Account for the data and output it if we have a full word */
1948 SI.ValBits += Entry->V.B.BitWidth;
1949 CHECK (SI.ValBits <= INT_BITS);
1950 if (SI.ValBits == INT_BITS) {
1951 OutputBitFieldData (&SI);
1956 /* Standard member. We should never have stuff from a
1959 CHECK (SI.ValBits == 0);
1961 /* Flexible array members may only be initialized if they are
1962 * the last field (or part of the last struct field).
1964 SI.Offs += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1967 /* More initializers? */
1968 if (CurTok.Tok != TOK_COMMA) {
1972 /* Skip the comma */
1976 /* Next member. For unions, only the first one can be initialized */
1977 if (IsTypeUnion (T)) {
1982 Entry = Entry->NextSym;
1986 /* Consume the closing curly brace */
1989 /* If we have data from a bit-field left, output it now */
1990 OutputBitFieldData (&SI);
1992 /* If there are struct fields left, reserve additional storage */
1993 if (SI.Offs < SI.Size) {
1994 g_zerobytes (SI.Size - SI.Offs);
1998 /* Return the actual number of bytes initialized. This number may be
1999 * larger than sizeof (Struct) if flexible array members are present and
2000 * were initialized (possible in non ANSI mode).
2007 static unsigned ParseVoidInit (void)
2008 /* Parse an initialization of a void variable (special cc65 extension).
2009 * Return the number of bytes initialized.
2018 /* Allow an arbitrary list of values */
2021 ConstExpr (hie1, &Expr);
2022 switch (UnqualifiedType (Expr.Type[0].C)) {
2026 if (ED_IsConstAbsInt (&Expr)) {
2027 /* Make it byte sized */
2031 Size += SIZEOF_CHAR;
2040 if (ED_IsConstAbsInt (&Expr)) {
2041 /* Make it word sized */
2042 Expr.IVal &= 0xFFFF;
2050 if (ED_IsConstAbsInt (&Expr)) {
2051 /* Make it dword sized */
2052 Expr.IVal &= 0xFFFFFFFF;
2055 Size += SIZEOF_LONG;
2059 Error ("Illegal type in initialization");
2064 if (CurTok.Tok != TOK_COMMA) {
2069 } while (CurTok.Tok != TOK_RCURLY);
2074 /* Return the number of bytes initialized */
2080 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
2081 /* Parse initialization of variables. Return the number of data bytes. */
2083 switch (UnqualifiedType (T->C)) {
2095 return ParseScalarInit (T);
2098 return ParsePointerInit (T);
2101 return ParseArrayInit (T, AllowFlexibleMembers);
2105 return ParseStructInit (T, AllowFlexibleMembers);
2108 if (IS_Get (&Standard) == STD_CC65) {
2109 /* Special cc65 extension in non ANSI mode */
2110 return ParseVoidInit ();
2115 Error ("Illegal type");
2123 unsigned ParseInit (Type* T)
2124 /* Parse initialization of variables. Return the number of data bytes. */
2126 /* Parse the initialization. Flexible array members can only be initialized
2129 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
2131 /* The initialization may not generate code on global level, because code
2132 * outside function scope will never get executed.
2134 if (HaveGlobalCode ()) {
2135 Error ("Non constant initializers");
2136 RemoveGlobalCode ();
2139 /* Return the size needed for the initialization */