1 /*****************************************************************************/
5 /* Parse variable and function declarations */
9 /* (C) 1998-2005 Ullrich von Bassewitz */
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 TypeCode OptionalQualifiers (TypeCode Q)
86 /* Read type qualifiers if we have any */
88 while (TokIsTypeQual (&CurTok)) {
93 if (Q & T_QUAL_CONST) {
94 Error ("Duplicate qualifier: `const'");
100 if (Q & T_QUAL_VOLATILE) {
101 Error ("Duplicate qualifier: `volatile'");
103 Q |= T_QUAL_VOLATILE;
107 if (Q & T_QUAL_RESTRICT) {
108 Error ("Duplicate qualifier: `restrict'");
110 Q |= T_QUAL_RESTRICT;
114 Internal ("Unexpected type qualifier token: %d", CurTok.Tok);
122 /* Return the qualifiers read */
128 static void OptionalInt (void)
129 /* Eat an optional "int" token */
131 if (CurTok.Tok == TOK_INT) {
139 static void OptionalSigned (void)
140 /* Eat an optional "signed" token */
142 if (CurTok.Tok == TOK_SIGNED) {
150 static void InitDeclSpec (DeclSpec* D)
151 /* Initialize the DeclSpec struct for use */
154 D->Type[0].C = T_END;
160 static void InitDeclaration (Declaration* D)
161 /* Initialize the Declaration struct for use */
164 D->Type[0].C = T_END;
170 static void NeedTypeSpace (Declaration* D, unsigned Count)
171 /* Check if there is enough space for Count type specifiers within D */
173 if (D->Index + Count >= MAXTYPELEN) {
174 /* We must call Fatal() here, since calling Error() will try to
175 * continue, and the declaration type is not correctly terminated
176 * in case we come here.
178 Fatal ("Too many type specifiers");
184 static void AddTypeToDeclaration (Declaration* D, TypeCode T)
185 /* Add a type specifier to the type of a declaration */
187 NeedTypeSpace (D, 1);
188 D->Type[D->Index++].C = T;
193 static void AddFuncTypeToDeclaration (Declaration* D, FuncDesc* F)
194 /* Add a function type plus function descriptor to the type of a declaration */
196 NeedTypeSpace (D, 1);
197 D->Type[D->Index].C = T_FUNC;
198 SetFuncDesc (D->Type + D->Index, F);
204 static void AddArrayToDeclaration (Declaration* D, long Size)
205 /* Add an array type plus size to the type of a declaration */
207 NeedTypeSpace (D, 1);
208 D->Type[D->Index].C = T_ARRAY;
209 D->Type[D->Index].A.L = Size;
215 static void FixArrayQualifiers (Type* T)
216 /* Using typedefs, it is possible to generate declarations that have
217 * type qualifiers attached to an array, not the element type. Go and
221 TypeCode Q = T_QUAL_NONE;
222 while (T->C != T_END) {
223 if (IsTypeArray (T)) {
224 /* Extract any type qualifiers */
225 Q |= T->C & T_MASK_QUAL;
226 T->C = UnqualifiedType (T->C);
228 /* Add extracted type qualifiers here */
235 /* Q must be empty now */
236 CHECK (Q == T_QUAL_NONE);
241 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
242 /* Parse a storage class */
244 /* Assume we're using an explicit storage class */
245 D->Flags &= ~DS_DEF_STORAGE;
247 /* Check the storage class given */
248 switch (CurTok.Tok) {
251 D->StorageClass = SC_EXTERN | SC_STATIC;
256 D->StorageClass = SC_STATIC;
261 D->StorageClass = SC_REGISTER | SC_STATIC;
266 D->StorageClass = SC_AUTO;
271 D->StorageClass = SC_TYPEDEF;
276 /* No storage class given, use default */
277 D->Flags |= DS_DEF_STORAGE;
278 D->StorageClass = DefStorage;
285 static void ParseEnumDecl (void)
286 /* Process an enum declaration . */
291 /* Accept forward definitions */
292 if (CurTok.Tok != TOK_LCURLY) {
296 /* Skip the opening curly brace */
299 /* Read the enum tags */
301 while (CurTok.Tok != TOK_RCURLY) {
303 /* We expect an identifier */
304 if (CurTok.Tok != TOK_IDENT) {
305 Error ("Identifier expected");
309 /* Remember the identifier and skip it */
310 strcpy (Ident, CurTok.Ident);
313 /* Check for an assigned value */
314 if (CurTok.Tok == TOK_ASSIGN) {
317 ConstAbsIntExpr (hie1, &Expr);
321 /* Add an entry to the symbol table */
322 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
324 /* Check for end of definition */
325 if (CurTok.Tok != TOK_COMMA)
334 static SymEntry* ParseStructDecl (const char* Name, TypeCode StructType)
335 /* Parse a struct/union declaration. */
346 if (CurTok.Tok != TOK_LCURLY) {
347 /* Just a forward declaration. Try to find a struct with the given
348 * name. If there is none, insert a forward declaration into the
349 * current lexical level.
351 Entry = FindTagSym (Name);
353 Entry = AddStructSym (Name, 0, 0);
354 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
355 /* Already defined in the level but no struct */
356 Error ("Symbol `%s' is already different kind", Name);
361 /* Add a forward declaration for the struct in the current lexical level */
362 Entry = AddStructSym (Name, 0, 0);
364 /* Skip the curly brace */
367 /* Enter a new lexical level for the struct */
370 /* Parse struct fields */
373 while (CurTok.Tok != TOK_RCURLY) {
375 /* Get the type of the entry */
377 InitDeclSpec (&Spec);
378 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
380 /* Read fields with this type */
385 /* If we had a flexible array member before, no other fields can
388 if (FlexibleMember) {
389 Error ("Flexible array member must be last field");
390 FlexibleMember = 0; /* Avoid further errors */
393 /* Get type and name of the struct field */
394 ParseDecl (&Spec, &Decl, 0);
396 /* Get the offset of this field */
397 Offs = (StructType == T_STRUCT)? StructSize : 0;
399 /* Calculate the sizes, handle flexible array members */
400 if (StructType == T_STRUCT) {
402 /* It's a struct. Check if this field is a flexible array
403 * member, and calculate the size of the field.
405 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
406 /* Array with unspecified size */
407 if (StructSize == 0) {
408 Error ("Flexible array member cannot be first struct field");
411 /* Assume zero for size calculations */
412 SetElementCount (Decl.Type, FLEXIBLE);
414 StructSize += CheckedSizeOf (Decl.Type);
420 FieldSize = CheckedSizeOf (Decl.Type);
421 if (FieldSize > StructSize) {
422 StructSize = FieldSize;
426 /* Add a field entry to the table */
427 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
429 if (CurTok.Tok != TOK_COMMA) {
437 /* Skip the closing brace */
440 /* Remember the symbol table and leave the struct level */
441 FieldTab = GetSymTab ();
444 /* Make a real entry from the forward decl and return it */
445 return AddStructSym (Name, StructSize, FieldTab);
450 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
451 /* Parse a type specificier */
457 /* Assume we have an explicit type */
458 D->Flags &= ~DS_DEF_TYPE;
460 /* Read type qualifiers if we have any */
461 Qualifiers = OptionalQualifiers (Qualifiers);
463 /* Look at the data type */
464 switch (CurTok.Tok) {
468 D->Type[0].C = T_VOID;
469 D->Type[1].C = T_END;
474 D->Type[0].C = GetDefaultChar();
475 D->Type[1].C = T_END;
480 if (CurTok.Tok == TOK_UNSIGNED) {
483 D->Type[0].C = T_ULONG;
484 D->Type[1].C = T_END;
488 D->Type[0].C = T_LONG;
489 D->Type[1].C = T_END;
495 if (CurTok.Tok == TOK_UNSIGNED) {
498 D->Type[0].C = T_USHORT;
499 D->Type[1].C = T_END;
503 D->Type[0].C = T_SHORT;
504 D->Type[1].C = T_END;
510 D->Type[0].C = T_INT;
511 D->Type[1].C = T_END;
516 switch (CurTok.Tok) {
520 D->Type[0].C = T_SCHAR;
521 D->Type[1].C = T_END;
527 D->Type[0].C = T_SHORT;
528 D->Type[1].C = T_END;
534 D->Type[0].C = T_LONG;
535 D->Type[1].C = T_END;
543 D->Type[0].C = T_INT;
544 D->Type[1].C = T_END;
551 switch (CurTok.Tok) {
555 D->Type[0].C = T_UCHAR;
556 D->Type[1].C = T_END;
562 D->Type[0].C = T_USHORT;
563 D->Type[1].C = T_END;
569 D->Type[0].C = T_ULONG;
570 D->Type[1].C = T_END;
578 D->Type[0].C = T_UINT;
579 D->Type[1].C = T_END;
586 D->Type[0].C = T_FLOAT;
587 D->Type[1].C = T_END;
592 D->Type[0].C = T_DOUBLE;
593 D->Type[1].C = T_END;
598 StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
601 if (CurTok.Tok == TOK_IDENT) {
602 strcpy (Ident, CurTok.Ident);
605 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
607 /* Remember we have an extra type decl */
608 D->Flags |= DS_EXTRA_TYPE;
609 /* Declare the struct in the current scope */
610 Entry = ParseStructDecl (Ident, StructType);
611 /* Encode the struct entry into the type */
612 D->Type[0].C = StructType;
613 SetSymEntry (D->Type, Entry);
614 D->Type[1].C = T_END;
619 if (CurTok.Tok != TOK_LCURLY) {
621 if (CurTok.Tok == TOK_IDENT) {
622 /* Find an entry with this name */
623 Entry = FindTagSym (CurTok.Ident);
625 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
626 Error ("Symbol `%s' is already different kind", Entry->Name);
629 /* Insert entry into table ### */
631 /* Skip the identifier */
634 Error ("Identifier expected");
637 /* Remember we have an extra type decl */
638 D->Flags |= DS_EXTRA_TYPE;
639 /* Parse the enum decl */
641 D->Type[0].C = T_INT;
642 D->Type[1].C = T_END;
646 Entry = FindSym (CurTok.Ident);
647 if (Entry && SymIsTypeDef (Entry)) {
650 TypeCpy (D->Type, Entry->Type);
657 Error ("Type expected");
658 D->Type[0].C = T_INT;
659 D->Type[1].C = T_END;
661 D->Flags |= DS_DEF_TYPE;
662 D->Type[0].C = (TypeCode) Default;
663 D->Type[1].C = T_END;
668 /* There may also be qualifiers *after* the initial type */
669 D->Type[0].C |= OptionalQualifiers (Qualifiers);
674 static Type* ParamTypeCvt (Type* T)
675 /* If T is an array, convert it to a pointer else do nothing. Return the
679 if (IsTypeArray (T)) {
687 static void ParseOldStyleParamList (FuncDesc* F)
688 /* Parse an old style (K&R) parameter list */
691 while (CurTok.Tok != TOK_RPAREN) {
693 /* List of identifiers expected */
694 if (CurTok.Tok != TOK_IDENT) {
695 Error ("Identifier expected");
698 /* Create a symbol table entry with type int */
699 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF, 0);
701 /* Count arguments */
704 /* Skip the identifier */
707 /* Check for more parameters */
708 if (CurTok.Tok == TOK_COMMA) {
715 /* Skip right paren. We must explicitly check for one here, since some of
716 * the breaks above bail out without checking.
720 /* An optional list of type specifications follows */
721 while (CurTok.Tok != TOK_LCURLY) {
725 /* Read the declaration specifier */
726 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
728 /* We accept only auto and register as storage class specifiers, but
729 * we ignore all this, since we use auto anyway.
731 if ((Spec.StorageClass & SC_AUTO) == 0 &&
732 (Spec.StorageClass & SC_REGISTER) == 0) {
733 Error ("Illegal storage class");
736 /* Parse a comma separated variable list */
741 /* Read the parameter */
742 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
743 if (Decl.Ident[0] != '\0') {
745 /* We have a name given. Search for the symbol */
746 SymEntry* Sym = FindLocalSym (Decl.Ident);
748 /* Found it, change the default type to the one given */
749 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
751 Error ("Unknown identifier: `%s'", Decl.Ident);
755 if (CurTok.Tok == TOK_COMMA) {
763 /* Variable list must be semicolon terminated */
770 static void ParseAnsiParamList (FuncDesc* F)
771 /* Parse a new style (ANSI) parameter list */
774 while (CurTok.Tok != TOK_RPAREN) {
780 /* Allow an ellipsis as last parameter */
781 if (CurTok.Tok == TOK_ELLIPSIS) {
783 F->Flags |= FD_VARIADIC;
787 /* Read the declaration specifier */
788 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
790 /* We accept only auto and register as storage class specifiers */
791 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
792 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
793 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
794 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
796 Error ("Illegal storage class");
797 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
800 /* Allow parameters without a name, but remember if we had some to
801 * eventually print an error message later.
803 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
804 if (Decl.Ident[0] == '\0') {
806 /* Unnamed symbol. Generate a name that is not user accessible,
807 * then handle the symbol normal.
809 AnonName (Decl.Ident, "param");
810 F->Flags |= FD_UNNAMED_PARAMS;
812 /* Clear defined bit on nonames */
813 Spec.StorageClass &= ~SC_DEF;
816 /* Parse an attribute ### */
817 ParseAttribute (&Decl, &Attr);
819 /* Create a symbol table entry */
820 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Spec.StorageClass, 0);
822 /* Count arguments */
825 /* Check for more parameters */
826 if (CurTok.Tok == TOK_COMMA) {
833 /* Skip right paren. We must explicitly check for one here, since some of
834 * the breaks above bail out without checking.
838 /* Check if this is a function definition */
839 if (CurTok.Tok == TOK_LCURLY) {
840 /* Print an error if we have unnamed parameters and cc65 extensions
843 if (IS_Get (&Standard) != STD_CC65 &&
844 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
845 Error ("Parameter name omitted");
852 static FuncDesc* ParseFuncDecl (void)
853 /* Parse the argument list of a function. */
858 /* Create a new function descriptor */
859 FuncDesc* F = NewFuncDesc ();
861 /* Enter a new lexical level */
862 EnterFunctionLevel ();
864 /* Check for several special parameter lists */
865 if (CurTok.Tok == TOK_RPAREN) {
866 /* Parameter list is empty */
867 F->Flags |= (FD_EMPTY | FD_VARIADIC);
868 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
869 /* Parameter list declared as void */
871 F->Flags |= FD_VOID_PARAM;
872 } else if (CurTok.Tok == TOK_IDENT &&
873 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
874 /* If the identifier is a typedef, we have a new style parameter list,
875 * if it's some other identifier, it's an old style parameter list.
877 Sym = FindSym (CurTok.Ident);
878 if (Sym == 0 || !SymIsTypeDef (Sym)) {
879 /* Old style (K&R) function. */
880 F->Flags |= FD_OLDSTYLE;
885 if ((F->Flags & FD_OLDSTYLE) == 0) {
886 /* New style function */
887 ParseAnsiParamList (F);
889 /* Old style function */
890 ParseOldStyleParamList (F);
893 /* Remember the last function parameter. We need it later for several
894 * purposes, for example when passing stuff to fastcall functions. Since
895 * more symbols are added to the table, it is easier if we remember it
896 * now, since it is currently the last entry in the symbol table.
898 F->LastParam = GetSymTab()->SymTail;
900 /* Assign offsets. If the function has a variable parameter list,
901 * there's one additional byte (the arg size).
903 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
906 unsigned Size = CheckedSizeOf (Sym->Type);
907 if (SymIsRegVar (Sym)) {
908 Sym->V.R.SaveOffs = Offs;
913 F->ParamSize += Size;
917 /* Add the default address size for the function */
918 if (CodeAddrSize == ADDR_SIZE_FAR) {
924 /* Leave the lexical level remembering the symbol tables */
925 RememberFunctionLevel (F);
927 /* Return the function descriptor */
933 static unsigned FunctionModifierFlags (void)
934 /* Parse __fastcall__, __near__ and __far__ and return the matching FD_ flags */
937 unsigned Flags = FD_NONE;
938 while (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
940 /* Get the flag bit for the next token */
941 unsigned F = FD_NONE;
942 switch (CurTok.Tok) {
943 case TOK_FASTCALL: F = FD_FASTCALL; break;
944 case TOK_NEAR: F = FD_NEAR; break;
945 case TOK_FAR: F = FD_FAR; break;
946 default: Internal ("Unexpected token: %d", CurTok.Tok);
949 /* Remember the flag for this modifier */
951 Error ("Duplicate modifier");
960 if ((Flags & (FD_NEAR | FD_FAR)) == (FD_NEAR | FD_FAR)) {
961 Error ("Cannot specify both, `__near__' and `__far__' modifiers");
962 Flags &= ~(FD_NEAR | FD_FAR);
965 /* Return the flags read */
971 static void ApplyFunctionModifiers (Type* T, unsigned Flags)
972 /* Apply a set of function modifier flags to a function */
974 /* Get the function descriptor */
975 FuncDesc* F = GetFuncDesc (T);
977 /* Special check for __fastcall__ */
978 if ((Flags & FD_FASTCALL) != 0 && IsVariadicFunc (T)) {
979 Error ("Cannot apply `__fastcall__' to functions with "
980 "variable parameter list");
981 Flags &= ~FD_FASTCALL;
984 /* Remove the default function address size modifiers */
985 F->Flags &= ~(FD_NEAR | FD_FAR);
987 /* Add the new modifers */
993 static void Decl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
994 /* Recursively process declarators. Build a type array in reverse order. */
996 /* Pointer to something */
997 if (CurTok.Tok == TOK_STAR) {
1004 /* Allow optional const or volatile qualifiers */
1005 C = T_PTR | OptionalQualifiers (T_QUAL_NONE);
1007 /* Parse the type, the pointer points to */
1008 Decl (Spec, D, Mode);
1011 AddTypeToDeclaration (D, C);
1015 /* Function modifiers */
1016 if (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
1018 /* Remember the current type pointer */
1019 Type* T = D->Type + D->Index;
1021 /* Read the flags */
1022 unsigned Flags = FunctionModifierFlags ();
1024 /* Parse the function */
1025 Decl (Spec, D, Mode);
1027 /* Check that we have a function */
1028 if (!IsTypeFunc (T) && !IsTypeFuncPtr (T)) {
1029 Error ("Function modifier applied to non function");
1031 ApplyFunctionModifiers (T, Flags);
1038 if (CurTok.Tok == TOK_LPAREN) {
1040 Decl (Spec, D, Mode);
1043 /* Things depend on Mode now:
1044 * - Mode == DM_NEED_IDENT means:
1045 * we *must* have a type and a variable identifer.
1046 * - Mode == DM_NO_IDENT means:
1047 * we must have a type but no variable identifer
1048 * (if there is one, it's not read).
1049 * - Mode == DM_ACCEPT_IDENT means:
1050 * we *may* have an identifier. If there is an identifier,
1051 * it is read, but it is no error, if there is none.
1053 if (Mode == DM_NO_IDENT) {
1055 } else if (CurTok.Tok == TOK_IDENT) {
1056 strcpy (D->Ident, CurTok.Ident);
1059 if (Mode == DM_NEED_IDENT) {
1060 Error ("Identifier expected");
1066 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1067 if (CurTok.Tok == TOK_LPAREN) {
1069 /* Function declaration */
1073 /* Parse the function declaration */
1074 F = ParseFuncDecl ();
1076 /* Add the function type. Be sure to bounds check the type buffer */
1077 AddFuncTypeToDeclaration (D, F);
1079 /* Array declaration */
1080 long Size = UNSPECIFIED;
1082 /* Read the size if it is given */
1083 if (CurTok.Tok != TOK_RBRACK) {
1085 ConstAbsIntExpr (hie1, &Expr);
1086 if (Expr.IVal <= 0) {
1087 if (D->Ident[0] != '\0') {
1088 Error ("Size of array `%s' is invalid", D->Ident);
1090 Error ("Size of array is invalid");
1098 /* Add the array type with the size */
1099 AddArrayToDeclaration (D, Size);
1106 /*****************************************************************************/
1108 /*****************************************************************************/
1112 Type* ParseType (Type* T)
1113 /* Parse a complete type specification */
1118 /* Get a type without a default */
1119 InitDeclSpec (&Spec);
1120 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1122 /* Parse additional declarators */
1123 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1125 /* Copy the type to the target buffer */
1126 TypeCpy (T, Decl.Type);
1128 /* Return a pointer to the target buffer */
1134 void ParseDecl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
1135 /* Parse a variable, type or function declaration */
1137 /* Initialize the Declaration struct */
1138 InitDeclaration (D);
1140 /* Get additional declarators and the identifier */
1141 Decl (Spec, D, Mode);
1143 /* Add the base type. */
1144 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1145 TypeCpy (D->Type + D->Index, Spec->Type);
1147 /* Fix any type qualifiers attached to an array type */
1148 FixArrayQualifiers (D->Type);
1150 /* Check several things for function or function pointer types */
1151 if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) {
1153 /* A function. Check the return type */
1154 Type* RetType = GetFuncReturn (D->Type);
1156 /* Functions may not return functions or arrays */
1157 if (IsTypeFunc (RetType)) {
1158 Error ("Functions are not allowed to return functions");
1159 } else if (IsTypeArray (RetType)) {
1160 Error ("Functions are not allowed to return arrays");
1163 /* The return type must not be qualified */
1164 if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) {
1166 if (GetType (RetType) == T_TYPE_VOID) {
1167 /* A qualified void type is always an error */
1168 Error ("function definition has qualified void return type");
1170 /* For others, qualifiers are ignored */
1171 Warning ("type qualifiers ignored on function return type");
1172 RetType[0].C = UnqualifiedType (RetType[0].C);
1176 /* Warn about an implicit int return in the function */
1177 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
1178 RetType[0].C == T_INT && RetType[1].C == T_END) {
1179 /* Function has an implicit int return. Output a warning if we don't
1180 * have the C89 standard enabled explicitly.
1182 if (IS_Get (&Standard) >= STD_C99) {
1183 Warning ("Implicit `int' return type is an obsolete feature");
1185 GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET;
1190 /* Check the size of the generated type */
1191 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1192 unsigned Size = SizeOf (D->Type);
1193 if (Size >= 0x10000) {
1194 if (D->Ident[0] != '\0') {
1195 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1197 Error ("Invalid size in declaration (0x%06X)", Size);
1206 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1207 /* Parse a declaration specification */
1209 TypeCode Qualifiers;
1211 /* Initialize the DeclSpec struct */
1214 /* There may be qualifiers *before* the storage class specifier */
1215 Qualifiers = OptionalQualifiers (T_QUAL_NONE);
1217 /* Now get the storage class specifier for this declaration */
1218 ParseStorageClass (D, DefStorage);
1220 /* Parse the type specifiers passing any initial type qualifiers */
1221 ParseTypeSpec (D, DefType, Qualifiers);
1226 void CheckEmptyDecl (const DeclSpec* D)
1227 /* Called after an empty type declaration (that is, a type declaration without
1228 * a variable). Checks if the declaration does really make sense and issues a
1232 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1233 Warning ("Useless declaration");
1239 static void SkipInitializer (unsigned BracesExpected)
1240 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1241 * smart so we don't have too many following errors.
1244 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1245 switch (CurTok.Tok) {
1246 case TOK_RCURLY: --BracesExpected; break;
1247 case TOK_LCURLY: ++BracesExpected; break;
1256 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1257 /* Accept any number of opening curly braces around an initialization, skip
1258 * them and return the number. If the number of curly braces is less than
1259 * BracesNeeded, issue a warning.
1262 unsigned BraceCount = 0;
1263 while (CurTok.Tok == TOK_LCURLY) {
1267 if (BraceCount < BracesNeeded) {
1268 Error ("`{' expected");
1275 static void ClosingCurlyBraces (unsigned BracesExpected)
1276 /* Accept and skip the given number of closing curly braces together with
1277 * an optional comma. Output an error messages, if the input does not contain
1278 * the expected number of braces.
1281 while (BracesExpected) {
1282 if (CurTok.Tok == TOK_RCURLY) {
1284 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1288 Error ("`}' expected");
1297 static void DefineData (ExprDesc* Expr)
1298 /* Output a data definition for the given expression */
1300 switch (ED_GetLoc (Expr)) {
1303 /* Absolute: numeric address or const */
1304 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1308 /* Global variable */
1309 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1314 /* Static variable or literal in the literal pool */
1315 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1318 case E_LOC_REGISTER:
1319 /* Register variable. Taking the address is usually not
1322 if (IS_Get (&AllowRegVarAddr) == 0) {
1323 Error ("Cannot take the address of a register variable");
1325 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1331 Error ("Non constant initializer");
1335 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1341 static unsigned ParseScalarInit (Type* T)
1342 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1346 /* Optional opening brace */
1347 unsigned BraceCount = OpeningCurlyBraces (0);
1349 /* We warn if an initializer for a scalar contains braces, because this is
1350 * quite unusual and often a sign for some problem in the input.
1352 if (BraceCount > 0) {
1353 Warning ("Braces around scalar initializer");
1356 /* Get the expression and convert it to the target type */
1357 ConstExpr (hie1, &ED);
1358 TypeConversion (&ED, T);
1360 /* Output the data */
1363 /* Close eventually opening braces */
1364 ClosingCurlyBraces (BraceCount);
1372 static unsigned ParsePointerInit (Type* T)
1373 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1375 /* Optional opening brace */
1376 unsigned BraceCount = OpeningCurlyBraces (0);
1380 ConstExpr (hie1, &ED);
1381 TypeConversion (&ED, T);
1383 /* Output the data */
1386 /* Close eventually opening braces */
1387 ClosingCurlyBraces (BraceCount);
1395 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1396 /* Parse initializaton for arrays. Return the number of data bytes. */
1400 /* Get the array data */
1401 Type* ElementType = GetElementType (T);
1402 unsigned ElementSize = CheckedSizeOf (ElementType);
1403 long ElementCount = GetElementCount (T);
1405 /* Special handling for a character array initialized by a literal */
1406 if (IsTypeChar (ElementType) &&
1407 (CurTok.Tok == TOK_SCONST ||
1408 (CurTok.Tok == TOK_LCURLY && NextTok.Tok == TOK_SCONST))) {
1410 /* Char array initialized by string constant */
1414 /* If we initializer is enclosed in brackets, remember this fact and
1415 * skip the opening bracket.
1417 NeedParen = (CurTok.Tok == TOK_LCURLY);
1422 /* Get the initializer string and its size */
1423 Str = GetLiteral (CurTok.IVal);
1424 Count = GetLiteralPoolOffs () - CurTok.IVal;
1426 /* Translate into target charset */
1427 TranslateLiteralPool (CurTok.IVal);
1429 /* If the array is one too small for the string literal, omit the
1432 if (ElementCount != UNSPECIFIED &&
1433 ElementCount != FLEXIBLE &&
1434 Count == ElementCount + 1) {
1435 /* Omit the trailing zero */
1439 /* Output the data */
1440 g_defbytes (Str, Count);
1442 /* Remove string from pool */
1443 ResetLiteralPoolOffs (CurTok.IVal);
1446 /* If the initializer was enclosed in curly braces, we need a closing
1458 /* Initialize the array members */
1460 while (CurTok.Tok != TOK_RCURLY) {
1461 /* Flexible array members may not be initialized within
1462 * an array (because the size of each element may differ
1465 ParseInitInternal (ElementType, 0);
1467 if (CurTok.Tok != TOK_COMMA)
1472 /* Closing curly braces */
1476 if (ElementCount == UNSPECIFIED) {
1477 /* Number of elements determined by initializer */
1478 SetElementCount (T, Count);
1479 ElementCount = Count;
1480 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1481 /* In non ANSI mode, allow initialization of flexible array
1484 ElementCount = Count;
1485 } else if (Count < ElementCount) {
1486 g_zerobytes ((ElementCount - Count) * ElementSize);
1487 } else if (Count > ElementCount) {
1488 Error ("Too many initializers");
1490 return ElementCount * ElementSize;
1495 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1496 /* Parse initialization of a struct or union. Return the number of data bytes. */
1500 unsigned StructSize;
1504 /* Consume the opening curly brace */
1507 /* Get a pointer to the struct entry from the type */
1508 Entry = GetSymEntry (T);
1510 /* Get the size of the struct from the symbol table entry */
1511 StructSize = Entry->V.S.Size;
1513 /* Check if this struct definition has a field table. If it doesn't, it
1514 * is an incomplete definition.
1516 Tab = Entry->V.S.SymTab;
1518 Error ("Cannot initialize variables with incomplete type");
1519 /* Try error recovery */
1520 SkipInitializer (1);
1521 /* Nothing initialized */
1525 /* Get a pointer to the list of symbols */
1526 Entry = Tab->SymHead;
1528 /* Initialize fields */
1530 while (CurTok.Tok != TOK_RCURLY) {
1532 Error ("Too many initializers");
1533 SkipInitializer (1);
1536 /* Parse initialization of one field. Flexible array members may
1537 * only be initialized if they are the last field (or part of the
1538 * last struct field).
1540 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1541 Entry = Entry->NextSym;
1542 if (CurTok.Tok != TOK_COMMA)
1547 /* Consume the closing curly brace */
1550 /* If there are struct fields left, reserve additional storage */
1551 if (Size < StructSize) {
1552 g_zerobytes (StructSize - Size);
1556 /* Return the actual number of bytes initialized. This number may be
1557 * larger than StructSize if flexible array members are present and were
1558 * initialized (possible in non ANSI mode).
1565 static unsigned ParseVoidInit (void)
1566 /* Parse an initialization of a void variable (special cc65 extension).
1567 * Return the number of bytes initialized.
1576 /* Allow an arbitrary list of values */
1579 ConstExpr (hie1, &Expr);
1580 switch (UnqualifiedType (Expr.Type[0].C)) {
1584 if (ED_IsConstAbsInt (&Expr)) {
1585 /* Make it byte sized */
1589 Size += SIZEOF_CHAR;
1598 if (ED_IsConstAbsInt (&Expr)) {
1599 /* Make it word sized */
1600 Expr.IVal &= 0xFFFF;
1608 if (ED_IsConstAbsInt (&Expr)) {
1609 /* Make it dword sized */
1610 Expr.IVal &= 0xFFFFFFFF;
1613 Size += SIZEOF_LONG;
1617 Error ("Illegal type in initialization");
1622 if (CurTok.Tok != TOK_COMMA) {
1627 } while (CurTok.Tok != TOK_RCURLY);
1632 /* Return the number of bytes initialized */
1638 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
1639 /* Parse initialization of variables. Return the number of data bytes. */
1641 switch (UnqualifiedType (T->C)) {
1651 return ParseScalarInit (T);
1654 return ParsePointerInit (T);
1657 return ParseArrayInit (T, AllowFlexibleMembers);
1661 return ParseStructInit (T, AllowFlexibleMembers);
1664 if (IS_Get (&Standard) == STD_CC65) {
1665 /* Special cc65 extension in non ANSI mode */
1666 return ParseVoidInit ();
1671 Error ("Illegal type");
1679 unsigned ParseInit (Type* T)
1680 /* Parse initialization of variables. Return the number of data bytes. */
1682 /* Parse the initialization. Flexible array members can only be initialized
1685 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
1687 /* The initialization may not generate code on global level, because code
1688 * outside function scope will never get executed.
1690 if (HaveGlobalCode ()) {
1691 Error ("Non constant initializers");
1692 RemoveGlobalCode ();
1695 /* Return the size needed for the initialization */