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* ParseStructDecl (const char* Name, TypeCode StructType)
490 /* Parse a struct/union declaration. */
497 int BitOffs; /* Bit offset for bit-fields */
498 int FieldWidth; /* Width in bits, -1 if not a bit-field */
503 if (CurTok.Tok != TOK_LCURLY) {
504 /* Just a forward declaration. Try to find a struct with the given
505 * name. If there is none, insert a forward declaration into the
506 * current lexical level.
508 Entry = FindTagSym (Name);
510 Entry = AddStructSym (Name, 0, 0);
511 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
512 /* Already defined in the level but no struct */
513 Error ("Symbol `%s' is already different kind", Name);
518 /* Add a forward declaration for the struct in the current lexical level */
519 Entry = AddStructSym (Name, 0, 0);
521 /* Skip the curly brace */
524 /* Enter a new lexical level for the struct */
527 /* Parse struct fields */
531 while (CurTok.Tok != TOK_RCURLY) {
533 /* Get the type of the entry */
535 InitDeclSpec (&Spec);
536 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
538 /* Read fields with this type */
543 /* If we had a flexible array member before, no other fields can
546 if (FlexibleMember) {
547 Error ("Flexible array member must be last field");
548 FlexibleMember = 0; /* Avoid further errors */
551 /* Get type and name of the struct field */
552 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
554 /* Check for a bit-field declaration */
555 FieldWidth = ParseFieldWidth (&Decl);
557 /* A non bit-field without a name is legal but useless */
558 if (FieldWidth < 0 && Decl.Ident[0] == '\0') {
559 Warning ("Declaration does not declare anything");
563 /* If this is not a bit field, or the bit field is too large for
564 * the remainder of the current member, or we have a bit field
565 * with width zero, align the struct to the next member
568 if (FieldWidth <= 0 || (BitOffs + FieldWidth) > INT_BITS) {
569 /* BitOffs > 0, so this can only be a struct */
570 StructSize += SIZEOF_INT;
575 /* Apart from the above, a bit field with width 0 is not processed
576 * further. An unnamed bit field will just increase the bit offset.
578 if (FieldWidth == 0) {
580 } else if (FieldWidth > 0 && Decl.Ident[0] == '\0') {
581 if (StructType == T_STRUCT) {
582 BitOffs += FieldWidth;
587 /* Calculate the sizes, handle flexible array members */
588 if (StructType == T_STRUCT) {
590 /* It's a struct. Offset of this member is the current struct
591 * size plus any full bytes from the bit offset in case of
594 Offs = StructSize + (BitOffs >> 3);
596 /* Check if this field is a flexible array member, and
597 * calculate the size of the field.
599 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
600 /* Array with unspecified size */
601 if (StructSize == 0) {
602 Error ("Flexible array member cannot be first struct field");
605 /* Assume zero for size calculations */
606 SetElementCount (Decl.Type, FLEXIBLE);
607 } else if (FieldWidth < 0) {
608 StructSize += CheckedSizeOf (Decl.Type);
611 /* Add a field entry to the table */
612 if (FieldWidth > 0) {
613 AddBitField (Decl.Ident, Offs, BitOffs & 0x07, FieldWidth);
614 BitOffs += FieldWidth;
616 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
621 /* It's a union. Offset of this member is always zero */
623 FieldSize = CheckedSizeOf (Decl.Type);
624 if (FieldSize > StructSize) {
625 StructSize = FieldSize;
628 /* Add a field entry to the table */
629 if (FieldWidth > 0) {
630 AddBitField (Decl.Ident, 0, 0, FieldWidth);
632 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
636 NextMember: if (CurTok.Tok != TOK_COMMA) {
644 /* Skip the closing brace */
647 /* Remember the symbol table and leave the struct level */
648 FieldTab = GetSymTab ();
651 /* Make a real entry from the forward decl and return it */
652 return AddStructSym (Name, StructSize, FieldTab);
657 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
658 /* Parse a type specificier */
664 /* Assume we have an explicit type */
665 D->Flags &= ~DS_DEF_TYPE;
667 /* Read type qualifiers if we have any */
668 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
670 /* Look at the data type */
671 switch (CurTok.Tok) {
675 D->Type[0].C = T_VOID;
676 D->Type[1].C = T_END;
681 D->Type[0].C = GetDefaultChar();
682 D->Type[1].C = T_END;
687 if (CurTok.Tok == TOK_UNSIGNED) {
690 D->Type[0].C = T_ULONG;
691 D->Type[1].C = T_END;
695 D->Type[0].C = T_LONG;
696 D->Type[1].C = T_END;
702 if (CurTok.Tok == TOK_UNSIGNED) {
705 D->Type[0].C = T_USHORT;
706 D->Type[1].C = T_END;
710 D->Type[0].C = T_SHORT;
711 D->Type[1].C = T_END;
717 D->Type[0].C = T_INT;
718 D->Type[1].C = T_END;
723 switch (CurTok.Tok) {
727 D->Type[0].C = T_SCHAR;
728 D->Type[1].C = T_END;
734 D->Type[0].C = T_SHORT;
735 D->Type[1].C = T_END;
741 D->Type[0].C = T_LONG;
742 D->Type[1].C = T_END;
750 D->Type[0].C = T_INT;
751 D->Type[1].C = T_END;
758 switch (CurTok.Tok) {
762 D->Type[0].C = T_UCHAR;
763 D->Type[1].C = T_END;
769 D->Type[0].C = T_USHORT;
770 D->Type[1].C = T_END;
776 D->Type[0].C = T_ULONG;
777 D->Type[1].C = T_END;
785 D->Type[0].C = T_UINT;
786 D->Type[1].C = T_END;
793 D->Type[0].C = T_FLOAT;
794 D->Type[1].C = T_END;
799 D->Type[0].C = T_DOUBLE;
800 D->Type[1].C = T_END;
805 StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
808 if (CurTok.Tok == TOK_IDENT) {
809 strcpy (Ident, CurTok.Ident);
812 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
814 /* Remember we have an extra type decl */
815 D->Flags |= DS_EXTRA_TYPE;
816 /* Declare the struct in the current scope */
817 Entry = ParseStructDecl (Ident, StructType);
818 /* Encode the struct entry into the type */
819 D->Type[0].C = StructType;
820 SetSymEntry (D->Type, Entry);
821 D->Type[1].C = T_END;
826 if (CurTok.Tok != TOK_LCURLY) {
828 if (CurTok.Tok == TOK_IDENT) {
829 /* Find an entry with this name */
830 Entry = FindTagSym (CurTok.Ident);
832 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
833 Error ("Symbol `%s' is already different kind", Entry->Name);
836 /* Insert entry into table ### */
838 /* Skip the identifier */
841 Error ("Identifier expected");
844 /* Remember we have an extra type decl */
845 D->Flags |= DS_EXTRA_TYPE;
846 /* Parse the enum decl */
848 D->Type[0].C = T_INT;
849 D->Type[1].C = T_END;
853 Entry = FindSym (CurTok.Ident);
854 if (Entry && SymIsTypeDef (Entry)) {
857 TypeCopy (D->Type, Entry->Type);
864 Error ("Type expected");
865 D->Type[0].C = T_INT;
866 D->Type[1].C = T_END;
868 D->Flags |= DS_DEF_TYPE;
869 D->Type[0].C = (TypeCode) Default;
870 D->Type[1].C = T_END;
875 /* There may also be qualifiers *after* the initial type */
876 D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE));
881 static Type* ParamTypeCvt (Type* T)
882 /* If T is an array, convert it to a pointer else do nothing. Return the
886 if (IsTypeArray (T)) {
894 static void ParseOldStyleParamList (FuncDesc* F)
895 /* Parse an old style (K&R) parameter list */
898 while (CurTok.Tok != TOK_RPAREN) {
900 /* List of identifiers expected */
901 if (CurTok.Tok != TOK_IDENT) {
902 Error ("Identifier expected");
905 /* Create a symbol table entry with type int */
906 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0);
908 /* Count arguments */
911 /* Skip the identifier */
914 /* Check for more parameters */
915 if (CurTok.Tok == TOK_COMMA) {
922 /* Skip right paren. We must explicitly check for one here, since some of
923 * the breaks above bail out without checking.
927 /* An optional list of type specifications follows */
928 while (CurTok.Tok != TOK_LCURLY) {
932 /* Read the declaration specifier */
933 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
935 /* We accept only auto and register as storage class specifiers, but
936 * we ignore all this, since we use auto anyway.
938 if ((Spec.StorageClass & SC_AUTO) == 0 &&
939 (Spec.StorageClass & SC_REGISTER) == 0) {
940 Error ("Illegal storage class");
943 /* Parse a comma separated variable list */
948 /* Read the parameter */
949 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
950 if (Decl.Ident[0] != '\0') {
952 /* We have a name given. Search for the symbol */
953 SymEntry* Sym = FindLocalSym (Decl.Ident);
955 /* Check if we already changed the type for this
958 if (Sym->Flags & SC_DEFTYPE) {
959 /* Found it, change the default type to the one given */
960 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
961 /* Reset the "default type" flag */
962 Sym->Flags &= ~SC_DEFTYPE;
964 /* Type has already been changed */
965 Error ("Redefinition for parameter `%s'", Sym->Name);
968 Error ("Unknown identifier: `%s'", Decl.Ident);
972 if (CurTok.Tok == TOK_COMMA) {
980 /* Variable list must be semicolon terminated */
987 static void ParseAnsiParamList (FuncDesc* F)
988 /* Parse a new style (ANSI) parameter list */
991 while (CurTok.Tok != TOK_RPAREN) {
997 /* Allow an ellipsis as last parameter */
998 if (CurTok.Tok == TOK_ELLIPSIS) {
1000 F->Flags |= FD_VARIADIC;
1004 /* Read the declaration specifier */
1005 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
1007 /* We accept only auto and register as storage class specifiers */
1008 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
1009 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1010 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
1011 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
1013 Error ("Illegal storage class");
1014 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
1017 /* Allow parameters without a name, but remember if we had some to
1018 * eventually print an error message later.
1020 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
1021 if (Decl.Ident[0] == '\0') {
1023 /* Unnamed symbol. Generate a name that is not user accessible,
1024 * then handle the symbol normal.
1026 AnonName (Decl.Ident, "param");
1027 F->Flags |= FD_UNNAMED_PARAMS;
1029 /* Clear defined bit on nonames */
1030 Decl.StorageClass &= ~SC_DEF;
1033 /* Parse an attribute ### */
1034 ParseAttribute (&Decl, &Attr);
1036 /* Create a symbol table entry */
1037 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0);
1039 /* Count arguments */
1042 /* Check for more parameters */
1043 if (CurTok.Tok == TOK_COMMA) {
1050 /* Skip right paren. We must explicitly check for one here, since some of
1051 * the breaks above bail out without checking.
1055 /* Check if this is a function definition */
1056 if (CurTok.Tok == TOK_LCURLY) {
1057 /* Print an error if we have unnamed parameters and cc65 extensions
1060 if (IS_Get (&Standard) != STD_CC65 &&
1061 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
1062 Error ("Parameter name omitted");
1069 static FuncDesc* ParseFuncDecl (void)
1070 /* Parse the argument list of a function. */
1075 /* Create a new function descriptor */
1076 FuncDesc* F = NewFuncDesc ();
1078 /* Enter a new lexical level */
1079 EnterFunctionLevel ();
1081 /* Check for several special parameter lists */
1082 if (CurTok.Tok == TOK_RPAREN) {
1083 /* Parameter list is empty */
1084 F->Flags |= (FD_EMPTY | FD_VARIADIC);
1085 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
1086 /* Parameter list declared as void */
1088 F->Flags |= FD_VOID_PARAM;
1089 } else if (CurTok.Tok == TOK_IDENT &&
1090 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
1091 /* If the identifier is a typedef, we have a new style parameter list,
1092 * if it's some other identifier, it's an old style parameter list.
1094 Sym = FindSym (CurTok.Ident);
1095 if (Sym == 0 || !SymIsTypeDef (Sym)) {
1096 /* Old style (K&R) function. */
1097 F->Flags |= FD_OLDSTYLE;
1102 if ((F->Flags & FD_OLDSTYLE) == 0) {
1103 /* New style function */
1104 ParseAnsiParamList (F);
1106 /* Old style function */
1107 ParseOldStyleParamList (F);
1110 /* Remember the last function parameter. We need it later for several
1111 * purposes, for example when passing stuff to fastcall functions. Since
1112 * more symbols are added to the table, it is easier if we remember it
1113 * now, since it is currently the last entry in the symbol table.
1115 F->LastParam = GetSymTab()->SymTail;
1117 /* Assign offsets. If the function has a variable parameter list,
1118 * there's one additional byte (the arg size).
1120 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
1123 unsigned Size = CheckedSizeOf (Sym->Type);
1124 if (SymIsRegVar (Sym)) {
1125 Sym->V.R.SaveOffs = Offs;
1130 F->ParamSize += Size;
1134 /* Leave the lexical level remembering the symbol tables */
1135 RememberFunctionLevel (F);
1137 /* Return the function descriptor */
1143 static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1144 /* Recursively process declarators. Build a type array in reverse order. */
1146 /* Read optional function or pointer qualifiers. These modify the
1147 * identifier or token to the right. For convenience, we allow the fastcall
1148 * qualifier also for pointers here. If it is a pointer-to-function, the
1149 * qualifier will later be transfered to the function itself. If it's a
1150 * pointer to something else, it will be flagged as an error.
1152 TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL);
1154 /* Pointer to something */
1155 if (CurTok.Tok == TOK_STAR) {
1160 /* Allow const, restrict and volatile qualifiers */
1161 Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT);
1163 /* Parse the type, the pointer points to */
1164 Declarator (Spec, D, Mode);
1167 AddTypeToDeclaration (D, T_PTR | Qualifiers);
1171 if (CurTok.Tok == TOK_LPAREN) {
1173 Declarator (Spec, D, Mode);
1176 /* Things depend on Mode now:
1177 * - Mode == DM_NEED_IDENT means:
1178 * we *must* have a type and a variable identifer.
1179 * - Mode == DM_NO_IDENT means:
1180 * we must have a type but no variable identifer
1181 * (if there is one, it's not read).
1182 * - Mode == DM_ACCEPT_IDENT means:
1183 * we *may* have an identifier. If there is an identifier,
1184 * it is read, but it is no error, if there is none.
1186 if (Mode == DM_NO_IDENT) {
1188 } else if (CurTok.Tok == TOK_IDENT) {
1189 strcpy (D->Ident, CurTok.Ident);
1192 if (Mode == DM_NEED_IDENT) {
1193 Error ("Identifier expected");
1199 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1200 if (CurTok.Tok == TOK_LPAREN) {
1202 /* Function declaration */
1205 /* Skip the opening paren */
1208 /* Parse the function declaration */
1209 F = ParseFuncDecl ();
1211 /* We cannot specify fastcall for variadic functions */
1212 if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) {
1213 Error ("Variadic functions cannot be `__fastcall'");
1214 Qualifiers &= ~T_QUAL_FASTCALL;
1217 /* Add the function type. Be sure to bounds check the type buffer */
1218 NeedTypeSpace (D, 1);
1219 D->Type[D->Index].C = T_FUNC | Qualifiers;
1220 D->Type[D->Index].A.P = F;
1223 /* Qualifiers now used */
1224 Qualifiers = T_QUAL_NONE;
1227 /* Array declaration. */
1228 long Size = UNSPECIFIED;
1230 /* We cannot have any qualifiers for an array */
1231 if (Qualifiers != T_QUAL_NONE) {
1232 Error ("Invalid qualifiers for array");
1233 Qualifiers = T_QUAL_NONE;
1236 /* Skip the left bracket */
1239 /* Read the size if it is given */
1240 if (CurTok.Tok != TOK_RBRACK) {
1242 ConstAbsIntExpr (hie1, &Expr);
1243 if (Expr.IVal <= 0) {
1244 if (D->Ident[0] != '\0') {
1245 Error ("Size of array `%s' is invalid", D->Ident);
1247 Error ("Size of array is invalid");
1254 /* Skip the right bracket */
1257 /* Add the array type with the size to the type */
1258 NeedTypeSpace (D, 1);
1259 D->Type[D->Index].C = T_ARRAY;
1260 D->Type[D->Index].A.L = Size;
1265 /* If we have remaining qualifiers, flag them as invalid */
1266 if (Qualifiers & T_QUAL_NEAR) {
1267 Error ("Invalid `__near__' qualifier");
1269 if (Qualifiers & T_QUAL_FAR) {
1270 Error ("Invalid `__far__' qualifier");
1272 if (Qualifiers & T_QUAL_FASTCALL) {
1273 Error ("Invalid `__fastcall__' qualifier");
1279 /*****************************************************************************/
1281 /*****************************************************************************/
1285 Type* ParseType (Type* T)
1286 /* Parse a complete type specification */
1291 /* Get a type without a default */
1292 InitDeclSpec (&Spec);
1293 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1295 /* Parse additional declarators */
1296 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1298 /* Copy the type to the target buffer */
1299 TypeCopy (T, Decl.Type);
1301 /* Return a pointer to the target buffer */
1307 void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode)
1308 /* Parse a variable, type or function declaration */
1310 /* Initialize the Declaration struct */
1311 InitDeclaration (D);
1313 /* Get additional declarators and the identifier */
1314 Declarator (Spec, D, Mode);
1316 /* Add the base type. */
1317 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1318 TypeCopy (D->Type + D->Index, Spec->Type);
1320 /* Use the storage class from the declspec */
1321 D->StorageClass = Spec->StorageClass;
1323 /* Do several fixes on qualifiers */
1324 FixQualifiers (D->Type);
1326 /* If we have a function, add a special storage class */
1327 if (IsTypeFunc (D->Type)) {
1328 D->StorageClass |= SC_FUNC;
1331 /* Check several things for function or function pointer types */
1332 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1334 /* A function. Check the return type */
1335 Type* RetType = GetFuncReturn (D->Type);
1337 /* Functions may not return functions or arrays */
1338 if (IsTypeFunc (RetType)) {
1339 Error ("Functions are not allowed to return functions");
1340 } else if (IsTypeArray (RetType)) {
1341 Error ("Functions are not allowed to return arrays");
1344 /* The return type must not be qualified */
1345 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1347 if (GetType (RetType) == T_TYPE_VOID) {
1348 /* A qualified void type is always an error */
1349 Error ("function definition has qualified void return type");
1351 /* For others, qualifiers are ignored */
1352 Warning ("type qualifiers ignored on function return type");
1353 RetType[0].C = UnqualifiedType (RetType[0].C);
1357 /* Warn about an implicit int return in the function */
1358 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1359 RetType[0].C == T_INT && RetType[1].C == T_END) {
1360 /* Function has an implicit int return. Output a warning if we don't
1361 * have the C89 standard enabled explicitly.
1363 if (IS_Get (&Standard) >= STD_C99) {
1364 Warning ("Implicit `int' return type is an obsolete feature");
1366 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1371 /* For anthing that is not a function or typedef, check for an implicit
1374 if ((D->StorageClass & SC_FUNC) != SC_FUNC &&
1375 (D->StorageClass & SC_TYPEDEF) != SC_TYPEDEF) {
1376 /* If the standard was not set explicitly to C89, print a warning
1377 * for variables with implicit int type.
1379 if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) {
1380 Warning ("Implicit `int' is an obsolete feature");
1384 /* Check the size of the generated type */
1385 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1386 unsigned Size = SizeOf (D->Type);
1387 if (Size >= 0x10000) {
1388 if (D->Ident[0] != '\0') {
1389 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1391 Error ("Invalid size in declaration (0x%06X)", Size);
1400 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1401 /* Parse a declaration specification */
1403 TypeCode Qualifiers;
1405 /* Initialize the DeclSpec struct */
1408 /* There may be qualifiers *before* the storage class specifier */
1409 Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE);
1411 /* Now get the storage class specifier for this declaration */
1412 ParseStorageClass (D, DefStorage);
1414 /* Parse the type specifiers passing any initial type qualifiers */
1415 ParseTypeSpec (D, DefType, Qualifiers);
1420 void CheckEmptyDecl (const DeclSpec* D)
1421 /* Called after an empty type declaration (that is, a type declaration without
1422 * a variable). Checks if the declaration does really make sense and issues a
1426 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1427 Warning ("Useless declaration");
1433 static void SkipInitializer (unsigned BracesExpected)
1434 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1435 * smart so we don't have too many following errors.
1438 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1439 switch (CurTok.Tok) {
1440 case TOK_RCURLY: --BracesExpected; break;
1441 case TOK_LCURLY: ++BracesExpected; break;
1450 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1451 /* Accept any number of opening curly braces around an initialization, skip
1452 * them and return the number. If the number of curly braces is less than
1453 * BracesNeeded, issue a warning.
1456 unsigned BraceCount = 0;
1457 while (CurTok.Tok == TOK_LCURLY) {
1461 if (BraceCount < BracesNeeded) {
1462 Error ("`{' expected");
1469 static void ClosingCurlyBraces (unsigned BracesExpected)
1470 /* Accept and skip the given number of closing curly braces together with
1471 * an optional comma. Output an error messages, if the input does not contain
1472 * the expected number of braces.
1475 while (BracesExpected) {
1476 if (CurTok.Tok == TOK_RCURLY) {
1478 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1482 Error ("`}' expected");
1491 static void DefineData (ExprDesc* Expr)
1492 /* Output a data definition for the given expression */
1494 switch (ED_GetLoc (Expr)) {
1497 /* Absolute: numeric address or const */
1498 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1502 /* Global variable */
1503 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1508 /* Static variable or literal in the literal pool */
1509 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1512 case E_LOC_REGISTER:
1513 /* Register variable. Taking the address is usually not
1516 if (IS_Get (&AllowRegVarAddr) == 0) {
1517 Error ("Cannot take the address of a register variable");
1519 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1525 Error ("Non constant initializer");
1529 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1535 static unsigned ParseScalarInit (Type* T)
1536 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1540 /* Optional opening brace */
1541 unsigned BraceCount = OpeningCurlyBraces (0);
1543 /* We warn if an initializer for a scalar contains braces, because this is
1544 * quite unusual and often a sign for some problem in the input.
1546 if (BraceCount > 0) {
1547 Warning ("Braces around scalar initializer");
1550 /* Get the expression and convert it to the target type */
1551 ConstExpr (hie1, &ED);
1552 TypeConversion (&ED, T);
1554 /* Output the data */
1557 /* Close eventually opening braces */
1558 ClosingCurlyBraces (BraceCount);
1566 static unsigned ParsePointerInit (Type* T)
1567 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1569 /* Optional opening brace */
1570 unsigned BraceCount = OpeningCurlyBraces (0);
1574 ConstExpr (hie1, &ED);
1575 TypeConversion (&ED, T);
1577 /* Output the data */
1580 /* Close eventually opening braces */
1581 ClosingCurlyBraces (BraceCount);
1589 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1590 /* Parse initializaton for arrays. Return the number of data bytes. */
1594 /* Get the array data */
1595 Type* ElementType = GetElementType (T);
1596 unsigned ElementSize = CheckedSizeOf (ElementType);
1597 long ElementCount = GetElementCount (T);
1599 /* Special handling for a character array initialized by a literal */
1600 if (IsTypeChar (ElementType) &&
1601 (CurTok.Tok == TOK_SCONST ||
1602 (CurTok.Tok == TOK_LCURLY && NextTok.Tok == TOK_SCONST))) {
1604 /* Char array initialized by string constant */
1608 /* If we initializer is enclosed in brackets, remember this fact and
1609 * skip the opening bracket.
1611 NeedParen = (CurTok.Tok == TOK_LCURLY);
1616 /* Get the initializer string and its size */
1617 Str = GetLiteral (CurTok.IVal);
1618 Count = GetLiteralPoolOffs () - CurTok.IVal;
1620 /* Translate into target charset */
1621 TranslateLiteralPool (CurTok.IVal);
1623 /* If the array is one too small for the string literal, omit the
1626 if (ElementCount != UNSPECIFIED &&
1627 ElementCount != FLEXIBLE &&
1628 Count == ElementCount + 1) {
1629 /* Omit the trailing zero */
1633 /* Output the data */
1634 g_defbytes (Str, Count);
1636 /* Remove string from pool */
1637 ResetLiteralPoolOffs (CurTok.IVal);
1640 /* If the initializer was enclosed in curly braces, we need a closing
1652 /* Initialize the array members */
1654 while (CurTok.Tok != TOK_RCURLY) {
1655 /* Flexible array members may not be initialized within
1656 * an array (because the size of each element may differ
1659 ParseInitInternal (ElementType, 0);
1661 if (CurTok.Tok != TOK_COMMA)
1666 /* Closing curly braces */
1670 if (ElementCount == UNSPECIFIED) {
1671 /* Number of elements determined by initializer */
1672 SetElementCount (T, Count);
1673 ElementCount = Count;
1674 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1675 /* In non ANSI mode, allow initialization of flexible array
1678 ElementCount = Count;
1679 } else if (Count < ElementCount) {
1680 g_zerobytes ((ElementCount - Count) * ElementSize);
1681 } else if (Count > ElementCount) {
1682 Error ("Too many initializers");
1684 return ElementCount * ElementSize;
1689 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1690 /* Parse initialization of a struct or union. Return the number of data bytes. */
1694 unsigned StructSize;
1698 /* Consume the opening curly brace */
1701 /* Get a pointer to the struct entry from the type */
1702 Entry = GetSymEntry (T);
1704 /* Get the size of the struct from the symbol table entry */
1705 StructSize = Entry->V.S.Size;
1707 /* Check if this struct definition has a field table. If it doesn't, it
1708 * is an incomplete definition.
1710 Tab = Entry->V.S.SymTab;
1712 Error ("Cannot initialize variables with incomplete type");
1713 /* Try error recovery */
1714 SkipInitializer (1);
1715 /* Nothing initialized */
1719 /* Get a pointer to the list of symbols */
1720 Entry = Tab->SymHead;
1722 /* Initialize fields */
1724 while (CurTok.Tok != TOK_RCURLY) {
1726 Error ("Too many initializers");
1727 SkipInitializer (1);
1730 /* Parse initialization of one field. Flexible array members may
1731 * only be initialized if they are the last field (or part of the
1732 * last struct field).
1734 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1735 Entry = Entry->NextSym;
1736 if (CurTok.Tok != TOK_COMMA)
1741 /* Consume the closing curly brace */
1744 /* If there are struct fields left, reserve additional storage */
1745 if (Size < StructSize) {
1746 g_zerobytes (StructSize - Size);
1750 /* Return the actual number of bytes initialized. This number may be
1751 * larger than StructSize if flexible array members are present and were
1752 * initialized (possible in non ANSI mode).
1759 static unsigned ParseVoidInit (void)
1760 /* Parse an initialization of a void variable (special cc65 extension).
1761 * Return the number of bytes initialized.
1770 /* Allow an arbitrary list of values */
1773 ConstExpr (hie1, &Expr);
1774 switch (UnqualifiedType (Expr.Type[0].C)) {
1778 if (ED_IsConstAbsInt (&Expr)) {
1779 /* Make it byte sized */
1783 Size += SIZEOF_CHAR;
1792 if (ED_IsConstAbsInt (&Expr)) {
1793 /* Make it word sized */
1794 Expr.IVal &= 0xFFFF;
1802 if (ED_IsConstAbsInt (&Expr)) {
1803 /* Make it dword sized */
1804 Expr.IVal &= 0xFFFFFFFF;
1807 Size += SIZEOF_LONG;
1811 Error ("Illegal type in initialization");
1816 if (CurTok.Tok != TOK_COMMA) {
1821 } while (CurTok.Tok != TOK_RCURLY);
1826 /* Return the number of bytes initialized */
1832 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
1833 /* Parse initialization of variables. Return the number of data bytes. */
1835 switch (UnqualifiedType (T->C)) {
1847 return ParseScalarInit (T);
1850 return ParsePointerInit (T);
1853 return ParseArrayInit (T, AllowFlexibleMembers);
1857 return ParseStructInit (T, AllowFlexibleMembers);
1860 if (IS_Get (&Standard) == STD_CC65) {
1861 /* Special cc65 extension in non ANSI mode */
1862 return ParseVoidInit ();
1867 Error ("Illegal type");
1875 unsigned ParseInit (Type* T)
1876 /* Parse initialization of variables. Return the number of data bytes. */
1878 /* Parse the initialization. Flexible array members can only be initialized
1881 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
1883 /* The initialization may not generate code on global level, because code
1884 * outside function scope will never get executed.
1886 if (HaveGlobalCode ()) {
1887 Error ("Non constant initializers");
1888 RemoveGlobalCode ();
1891 /* Return the size needed for the initialization */