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 ParseStorageClass (DeclSpec* D, unsigned DefStorage)
216 /* Parse a storage class */
218 /* Assume we're using an explicit storage class */
219 D->Flags &= ~DS_DEF_STORAGE;
221 /* Check the storage class given */
222 switch (CurTok.Tok) {
225 D->StorageClass = SC_EXTERN | SC_STATIC;
230 D->StorageClass = SC_STATIC;
235 D->StorageClass = SC_REGISTER | SC_STATIC;
240 D->StorageClass = SC_AUTO;
245 D->StorageClass = SC_TYPEDEF;
250 /* No storage class given, use default */
251 D->Flags |= DS_DEF_STORAGE;
252 D->StorageClass = DefStorage;
259 static void ParseEnumDecl (void)
260 /* Process an enum declaration . */
265 /* Accept forward definitions */
266 if (CurTok.Tok != TOK_LCURLY) {
270 /* Skip the opening curly brace */
273 /* Read the enum tags */
275 while (CurTok.Tok != TOK_RCURLY) {
277 /* We expect an identifier */
278 if (CurTok.Tok != TOK_IDENT) {
279 Error ("Identifier expected");
283 /* Remember the identifier and skip it */
284 strcpy (Ident, CurTok.Ident);
287 /* Check for an assigned value */
288 if (CurTok.Tok == TOK_ASSIGN) {
291 ConstAbsIntExpr (hie1, &Expr);
295 /* Add an entry to the symbol table */
296 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
298 /* Check for end of definition */
299 if (CurTok.Tok != TOK_COMMA)
308 static SymEntry* ParseStructDecl (const char* Name, TypeCode StructType)
309 /* Parse a struct/union declaration. */
320 if (CurTok.Tok != TOK_LCURLY) {
321 /* Just a forward declaration. Try to find a struct with the given
322 * name. If there is none, insert a forward declaration into the
323 * current lexical level.
325 Entry = FindTagSym (Name);
327 Entry = AddStructSym (Name, 0, 0);
328 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
329 /* Already defined in the level but no struct */
330 Error ("Symbol `%s' is already different kind", Name);
335 /* Add a forward declaration for the struct in the current lexical level */
336 Entry = AddStructSym (Name, 0, 0);
338 /* Skip the curly brace */
341 /* Enter a new lexical level for the struct */
344 /* Parse struct fields */
347 while (CurTok.Tok != TOK_RCURLY) {
349 /* Get the type of the entry */
351 InitDeclSpec (&Spec);
352 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
354 /* Read fields with this type */
359 /* If we had a flexible array member before, no other fields can
362 if (FlexibleMember) {
363 Error ("Flexible array member must be last field");
364 FlexibleMember = 0; /* Avoid further errors */
367 /* Get type and name of the struct field */
368 ParseDecl (&Spec, &Decl, 0);
370 /* Get the offset of this field */
371 Offs = (StructType == T_STRUCT)? StructSize : 0;
373 /* Calculate the sizes, handle flexible array members */
374 if (StructType == T_STRUCT) {
376 /* It's a struct. Check if this field is a flexible array
377 * member, and calculate the size of the field.
379 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
380 /* Array with unspecified size */
381 if (StructSize == 0) {
382 Error ("Flexible array member cannot be first struct field");
385 /* Assume zero for size calculations */
386 SetElementCount (Decl.Type, FLEXIBLE);
388 StructSize += CheckedSizeOf (Decl.Type);
394 FieldSize = CheckedSizeOf (Decl.Type);
395 if (FieldSize > StructSize) {
396 StructSize = FieldSize;
400 /* Add a field entry to the table */
401 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
403 if (CurTok.Tok != TOK_COMMA) {
411 /* Skip the closing brace */
414 /* Remember the symbol table and leave the struct level */
415 FieldTab = GetSymTab ();
418 /* Make a real entry from the forward decl and return it */
419 return AddStructSym (Name, StructSize, FieldTab);
424 static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers)
425 /* Parse a type specificier */
431 /* Assume we have an explicit type */
432 D->Flags &= ~DS_DEF_TYPE;
434 /* Read type qualifiers if we have any */
435 Qualifiers = OptionalQualifiers (Qualifiers);
437 /* Look at the data type */
438 switch (CurTok.Tok) {
442 D->Type[0].C = T_VOID;
443 D->Type[1].C = T_END;
448 D->Type[0].C = GetDefaultChar();
449 D->Type[1].C = T_END;
454 if (CurTok.Tok == TOK_UNSIGNED) {
457 D->Type[0].C = T_ULONG;
458 D->Type[1].C = T_END;
462 D->Type[0].C = T_LONG;
463 D->Type[1].C = T_END;
469 if (CurTok.Tok == TOK_UNSIGNED) {
472 D->Type[0].C = T_USHORT;
473 D->Type[1].C = T_END;
477 D->Type[0].C = T_SHORT;
478 D->Type[1].C = T_END;
484 D->Type[0].C = T_INT;
485 D->Type[1].C = T_END;
490 switch (CurTok.Tok) {
494 D->Type[0].C = T_SCHAR;
495 D->Type[1].C = T_END;
501 D->Type[0].C = T_SHORT;
502 D->Type[1].C = T_END;
508 D->Type[0].C = T_LONG;
509 D->Type[1].C = T_END;
517 D->Type[0].C = T_INT;
518 D->Type[1].C = T_END;
525 switch (CurTok.Tok) {
529 D->Type[0].C = T_UCHAR;
530 D->Type[1].C = T_END;
536 D->Type[0].C = T_USHORT;
537 D->Type[1].C = T_END;
543 D->Type[0].C = T_ULONG;
544 D->Type[1].C = T_END;
552 D->Type[0].C = T_UINT;
553 D->Type[1].C = T_END;
560 D->Type[0].C = T_FLOAT;
561 D->Type[1].C = T_END;
566 D->Type[0].C = T_DOUBLE;
567 D->Type[1].C = T_END;
572 StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
575 if (CurTok.Tok == TOK_IDENT) {
576 strcpy (Ident, CurTok.Ident);
579 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
581 /* Remember we have an extra type decl */
582 D->Flags |= DS_EXTRA_TYPE;
583 /* Declare the struct in the current scope */
584 Entry = ParseStructDecl (Ident, StructType);
585 /* Encode the struct entry into the type */
586 D->Type[0].C = StructType;
587 SetSymEntry (D->Type, Entry);
588 D->Type[1].C = T_END;
593 if (CurTok.Tok != TOK_LCURLY) {
595 if (CurTok.Tok == TOK_IDENT) {
596 /* Find an entry with this name */
597 Entry = FindTagSym (CurTok.Ident);
599 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
600 Error ("Symbol `%s' is already different kind", Entry->Name);
603 /* Insert entry into table ### */
605 /* Skip the identifier */
608 Error ("Identifier expected");
611 /* Remember we have an extra type decl */
612 D->Flags |= DS_EXTRA_TYPE;
613 /* Parse the enum decl */
615 D->Type[0].C = T_INT;
616 D->Type[1].C = T_END;
620 Entry = FindSym (CurTok.Ident);
621 if (Entry && SymIsTypeDef (Entry)) {
624 TypeCpy (D->Type, Entry->Type);
631 Error ("Type expected");
632 D->Type[0].C = T_INT;
633 D->Type[1].C = T_END;
635 D->Flags |= DS_DEF_TYPE;
636 D->Type[0].C = (TypeCode) Default;
637 D->Type[1].C = T_END;
642 /* There may also be qualifiers *after* the initial type */
643 D->Type[0].C |= OptionalQualifiers (Qualifiers);
648 static Type* ParamTypeCvt (Type* T)
649 /* If T is an array, convert it to a pointer else do nothing. Return the
653 if (IsTypeArray (T)) {
661 static void ParseOldStyleParamList (FuncDesc* F)
662 /* Parse an old style (K&R) parameter list */
665 while (CurTok.Tok != TOK_RPAREN) {
667 /* List of identifiers expected */
668 if (CurTok.Tok != TOK_IDENT) {
669 Error ("Identifier expected");
672 /* Create a symbol table entry with type int */
673 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF, 0);
675 /* Count arguments */
678 /* Skip the identifier */
681 /* Check for more parameters */
682 if (CurTok.Tok == TOK_COMMA) {
689 /* Skip right paren. We must explicitly check for one here, since some of
690 * the breaks above bail out without checking.
694 /* An optional list of type specifications follows */
695 while (CurTok.Tok != TOK_LCURLY) {
699 /* Read the declaration specifier */
700 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
702 /* We accept only auto and register as storage class specifiers, but
703 * we ignore all this, since we use auto anyway.
705 if ((Spec.StorageClass & SC_AUTO) == 0 &&
706 (Spec.StorageClass & SC_REGISTER) == 0) {
707 Error ("Illegal storage class");
710 /* Parse a comma separated variable list */
715 /* Read the parameter */
716 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
717 if (Decl.Ident[0] != '\0') {
719 /* We have a name given. Search for the symbol */
720 SymEntry* Sym = FindLocalSym (Decl.Ident);
722 /* Found it, change the default type to the one given */
723 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
725 Error ("Unknown identifier: `%s'", Decl.Ident);
729 if (CurTok.Tok == TOK_COMMA) {
737 /* Variable list must be semicolon terminated */
744 static void ParseAnsiParamList (FuncDesc* F)
745 /* Parse a new style (ANSI) parameter list */
748 while (CurTok.Tok != TOK_RPAREN) {
754 /* Allow an ellipsis as last parameter */
755 if (CurTok.Tok == TOK_ELLIPSIS) {
757 F->Flags |= FD_VARIADIC;
761 /* Read the declaration specifier */
762 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
764 /* We accept only auto and register as storage class specifiers */
765 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
766 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
767 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
768 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
770 Error ("Illegal storage class");
771 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
774 /* Allow parameters without a name, but remember if we had some to
775 * eventually print an error message later.
777 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
778 if (Decl.Ident[0] == '\0') {
780 /* Unnamed symbol. Generate a name that is not user accessible,
781 * then handle the symbol normal.
783 AnonName (Decl.Ident, "param");
784 F->Flags |= FD_UNNAMED_PARAMS;
786 /* Clear defined bit on nonames */
787 Spec.StorageClass &= ~SC_DEF;
790 /* Parse an attribute ### */
791 ParseAttribute (&Decl, &Attr);
793 /* Create a symbol table entry */
794 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Spec.StorageClass, 0);
796 /* Count arguments */
799 /* Check for more parameters */
800 if (CurTok.Tok == TOK_COMMA) {
807 /* Skip right paren. We must explicitly check for one here, since some of
808 * the breaks above bail out without checking.
812 /* Check if this is a function definition */
813 if (CurTok.Tok == TOK_LCURLY) {
814 /* Print an error if we have unnamed parameters and cc65 extensions
817 if (IS_Get (&Standard) != STD_CC65 &&
818 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
819 Error ("Parameter name omitted");
826 static FuncDesc* ParseFuncDecl (const DeclSpec* Spec)
827 /* Parse the argument list of a function. */
832 /* Create a new function descriptor */
833 FuncDesc* F = NewFuncDesc ();
835 /* Enter a new lexical level */
836 EnterFunctionLevel ();
838 /* Check for several special parameter lists */
839 if (CurTok.Tok == TOK_RPAREN) {
840 /* Parameter list is empty */
841 F->Flags |= (FD_EMPTY | FD_VARIADIC);
842 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
843 /* Parameter list declared as void */
845 F->Flags |= FD_VOID_PARAM;
846 } else if (CurTok.Tok == TOK_IDENT &&
847 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
848 /* If the identifier is a typedef, we have a new style parameter list,
849 * if it's some other identifier, it's an old style parameter list.
851 Sym = FindSym (CurTok.Ident);
852 if (Sym == 0 || !SymIsTypeDef (Sym)) {
853 /* Old style (K&R) function. */
854 F->Flags |= FD_OLDSTYLE;
858 /* Check for an implicit int return in the function */
859 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
860 Spec->Type[0].C == T_INT &&
861 Spec->Type[1].C == T_END) {
862 /* Function has an implicit int return. Output a warning if we don't
863 * have the C89 standard enabled explicitly.
865 if (IS_Get (&Standard) >= STD_C99) {
866 Warning ("Implicit `int' return type is an obsolete feature");
868 F->Flags |= FD_OLDSTYLE_INTRET;
872 if ((F->Flags & FD_OLDSTYLE) == 0) {
873 /* New style function */
874 ParseAnsiParamList (F);
876 /* Old style function */
877 ParseOldStyleParamList (F);
880 /* Remember the last function parameter. We need it later for several
881 * purposes, for example when passing stuff to fastcall functions. Since
882 * more symbols are added to the table, it is easier if we remember it
883 * now, since it is currently the last entry in the symbol table.
885 F->LastParam = GetSymTab()->SymTail;
887 /* Assign offsets. If the function has a variable parameter list,
888 * there's one additional byte (the arg size).
890 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
893 unsigned Size = CheckedSizeOf (Sym->Type);
894 if (SymIsRegVar (Sym)) {
895 Sym->V.R.SaveOffs = Offs;
900 F->ParamSize += Size;
904 /* Add the default address size for the function */
905 if (CodeAddrSize == ADDR_SIZE_FAR) {
911 /* Leave the lexical level remembering the symbol tables */
912 RememberFunctionLevel (F);
914 /* Return the function descriptor */
920 static unsigned FunctionModifierFlags (void)
921 /* Parse __fastcall__, __near__ and __far__ and return the matching FD_ flags */
924 unsigned Flags = FD_NONE;
925 while (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
927 /* Get the flag bit for the next token */
928 unsigned F = FD_NONE;
929 switch (CurTok.Tok) {
930 case TOK_FASTCALL: F = FD_FASTCALL; break;
931 case TOK_NEAR: F = FD_NEAR; break;
932 case TOK_FAR: F = FD_FAR; break;
933 default: Internal ("Unexpected token: %d", CurTok.Tok);
936 /* Remember the flag for this modifier */
938 Error ("Duplicate modifier");
947 if ((Flags & (FD_NEAR | FD_FAR)) == (FD_NEAR | FD_FAR)) {
948 Error ("Cannot specify both, `__near__' and `__far__' modifiers");
949 Flags &= ~(FD_NEAR | FD_FAR);
952 /* Return the flags read */
958 static void ApplyFunctionModifiers (Type* T, unsigned Flags)
959 /* Apply a set of function modifier flags to a function */
961 /* Get the function descriptor */
962 FuncDesc* F = GetFuncDesc (T);
964 /* Special check for __fastcall__ */
965 if ((Flags & FD_FASTCALL) != 0 && IsVariadicFunc (T)) {
966 Error ("Cannot apply `__fastcall__' to functions with "
967 "variable parameter list");
968 Flags &= ~FD_FASTCALL;
971 /* Remove the default function address size modifiers */
972 F->Flags &= ~(FD_NEAR | FD_FAR);
974 /* Add the new modifers */
980 static void Decl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
981 /* Recursively process declarators. Build a type array in reverse order. */
983 /* Pointer to something */
984 if (CurTok.Tok == TOK_STAR) {
991 /* Allow optional const or volatile qualifiers */
992 C = T_PTR | OptionalQualifiers (T_QUAL_NONE);
994 /* Parse the type, the pointer points to */
995 Decl (Spec, D, Mode);
998 AddTypeToDeclaration (D, C);
1002 /* Function modifiers */
1003 if (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
1005 /* Remember the current type pointer */
1006 Type* T = D->Type + D->Index;
1008 /* Read the flags */
1009 unsigned Flags = FunctionModifierFlags ();
1011 /* Parse the function */
1012 Decl (Spec, D, Mode);
1014 /* Check that we have a function */
1015 if (!IsTypeFunc (T) && !IsTypeFuncPtr (T)) {
1016 Error ("Function modifier applied to non function");
1018 ApplyFunctionModifiers (T, Flags);
1025 if (CurTok.Tok == TOK_LPAREN) {
1027 Decl (Spec, D, Mode);
1030 /* Things depend on Mode now:
1031 * - Mode == DM_NEED_IDENT means:
1032 * we *must* have a type and a variable identifer.
1033 * - Mode == DM_NO_IDENT means:
1034 * we must have a type but no variable identifer
1035 * (if there is one, it's not read).
1036 * - Mode == DM_ACCEPT_IDENT means:
1037 * we *may* have an identifier. If there is an identifier,
1038 * it is read, but it is no error, if there is none.
1040 if (Mode == DM_NO_IDENT) {
1042 } else if (CurTok.Tok == TOK_IDENT) {
1043 strcpy (D->Ident, CurTok.Ident);
1046 if (Mode == DM_NEED_IDENT) {
1047 Error ("Identifier expected");
1053 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1054 if (CurTok.Tok == TOK_LPAREN) {
1056 /* Function declaration */
1060 /* Parse the function declaration */
1061 F = ParseFuncDecl (Spec);
1063 /* Add the function type. Be sure to bounds check the type buffer */
1064 AddFuncTypeToDeclaration (D, F);
1066 /* Array declaration */
1067 long Size = UNSPECIFIED;
1069 /* Read the size if it is given */
1070 if (CurTok.Tok != TOK_RBRACK) {
1072 ConstAbsIntExpr (hie1, &Expr);
1073 if (Expr.IVal <= 0) {
1074 if (D->Ident[0] != '\0') {
1075 Error ("Size of array `%s' is invalid", D->Ident);
1077 Error ("Size of array is invalid");
1085 /* Add the array type with the size */
1086 AddArrayToDeclaration (D, Size);
1093 /*****************************************************************************/
1095 /*****************************************************************************/
1099 Type* ParseType (Type* T)
1100 /* Parse a complete type specification */
1105 /* Get a type without a default */
1106 InitDeclSpec (&Spec);
1107 ParseTypeSpec (&Spec, -1, T_QUAL_NONE);
1109 /* Parse additional declarators */
1110 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1112 /* Copy the type to the target buffer */
1113 TypeCpy (T, Decl.Type);
1115 /* Return a pointer to the target buffer */
1121 void ParseDecl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
1122 /* Parse a variable, type or function declaration */
1124 /* Initialize the Declaration struct */
1125 InitDeclaration (D);
1127 /* Get additional declarators and the identifier */
1128 Decl (Spec, D, Mode);
1130 /* Add the base type. */
1131 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1132 TypeCpy (D->Type + D->Index, Spec->Type);
1134 /* Check the size of the generated type */
1135 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1136 unsigned Size = SizeOf (D->Type);
1137 if (Size >= 0x10000) {
1138 if (D->Ident[0] != '\0') {
1139 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1141 Error ("Invalid size in declaration (0x%06X)", Size);
1149 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType)
1150 /* Parse a declaration specification */
1152 TypeCode Qualifiers;
1154 /* Initialize the DeclSpec struct */
1157 /* There may be qualifiers *before* the storage class specifier */
1158 Qualifiers = OptionalQualifiers (T_QUAL_NONE);
1160 /* Now get the storage class specifier for this declaration */
1161 ParseStorageClass (D, DefStorage);
1163 /* Parse the type specifiers passing any initial type qualifiers */
1164 ParseTypeSpec (D, DefType, Qualifiers);
1169 void CheckEmptyDecl (const DeclSpec* D)
1170 /* Called after an empty type declaration (that is, a type declaration without
1171 * a variable). Checks if the declaration does really make sense and issues a
1175 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1176 Warning ("Useless declaration");
1182 static void SkipInitializer (unsigned BracesExpected)
1183 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1184 * smart so we don't have too many following errors.
1187 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1188 switch (CurTok.Tok) {
1189 case TOK_RCURLY: --BracesExpected; break;
1190 case TOK_LCURLY: ++BracesExpected; break;
1199 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1200 /* Accept any number of opening curly braces around an initialization, skip
1201 * them and return the number. If the number of curly braces is less than
1202 * BracesNeeded, issue a warning.
1205 unsigned BraceCount = 0;
1206 while (CurTok.Tok == TOK_LCURLY) {
1210 if (BraceCount < BracesNeeded) {
1211 Error ("`{' expected");
1218 static void ClosingCurlyBraces (unsigned BracesExpected)
1219 /* Accept and skip the given number of closing curly braces together with
1220 * an optional comma. Output an error messages, if the input does not contain
1221 * the expected number of braces.
1224 while (BracesExpected) {
1225 if (CurTok.Tok == TOK_RCURLY) {
1227 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1231 Error ("`}' expected");
1240 static void DefineData (ExprDesc* Expr)
1241 /* Output a data definition for the given expression */
1243 switch (ED_GetLoc (Expr)) {
1246 /* Absolute: numeric address or const */
1247 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
1251 /* Global variable */
1252 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
1257 /* Static variable or literal in the literal pool */
1258 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
1261 case E_LOC_REGISTER:
1262 /* Register variable. Taking the address is usually not
1265 if (IS_Get (&AllowRegVarAddr) == 0) {
1266 Error ("Cannot take the address of a register variable");
1268 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
1274 Error ("Non constant initializer");
1278 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
1284 static unsigned ParseScalarInit (Type* T)
1285 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1289 /* Optional opening brace */
1290 unsigned BraceCount = OpeningCurlyBraces (0);
1292 /* We warn if an initializer for a scalar contains braces, because this is
1293 * quite unusual and often a sign for some problem in the input.
1295 if (BraceCount > 0) {
1296 Warning ("Braces around scalar initializer");
1299 /* Get the expression and convert it to the target type */
1300 ConstExpr (hie1, &ED);
1301 TypeConversion (&ED, T);
1303 /* Output the data */
1306 /* Close eventually opening braces */
1307 ClosingCurlyBraces (BraceCount);
1315 static unsigned ParsePointerInit (Type* T)
1316 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1318 /* Optional opening brace */
1319 unsigned BraceCount = OpeningCurlyBraces (0);
1323 ConstExpr (hie1, &ED);
1324 TypeConversion (&ED, T);
1326 /* Output the data */
1329 /* Close eventually opening braces */
1330 ClosingCurlyBraces (BraceCount);
1338 static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers)
1339 /* Parse initializaton for arrays. Return the number of data bytes. */
1343 /* Get the array data */
1344 Type* ElementType = GetElementType (T);
1345 unsigned ElementSize = CheckedSizeOf (ElementType);
1346 long ElementCount = GetElementCount (T);
1348 /* Special handling for a character array initialized by a literal */
1349 if (IsTypeChar (ElementType) &&
1350 (CurTok.Tok == TOK_SCONST ||
1351 (CurTok.Tok == TOK_LCURLY && NextTok.Tok == TOK_SCONST))) {
1353 /* Char array initialized by string constant */
1357 /* If we initializer is enclosed in brackets, remember this fact and
1358 * skip the opening bracket.
1360 NeedParen = (CurTok.Tok == TOK_LCURLY);
1365 /* Get the initializer string and its size */
1366 Str = GetLiteral (CurTok.IVal);
1367 Count = GetLiteralPoolOffs () - CurTok.IVal;
1369 /* Translate into target charset */
1370 TranslateLiteralPool (CurTok.IVal);
1372 /* If the array is one too small for the string literal, omit the
1375 if (ElementCount != UNSPECIFIED &&
1376 ElementCount != FLEXIBLE &&
1377 Count == ElementCount + 1) {
1378 /* Omit the trailing zero */
1382 /* Output the data */
1383 g_defbytes (Str, Count);
1385 /* Remove string from pool */
1386 ResetLiteralPoolOffs (CurTok.IVal);
1389 /* If the initializer was enclosed in curly braces, we need a closing
1401 /* Initialize the array members */
1403 while (CurTok.Tok != TOK_RCURLY) {
1404 /* Flexible array members may not be initialized within
1405 * an array (because the size of each element may differ
1408 ParseInitInternal (ElementType, 0);
1410 if (CurTok.Tok != TOK_COMMA)
1415 /* Closing curly braces */
1419 if (ElementCount == UNSPECIFIED) {
1420 /* Number of elements determined by initializer */
1421 SetElementCount (T, Count);
1422 ElementCount = Count;
1423 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1424 /* In non ANSI mode, allow initialization of flexible array
1427 ElementCount = Count;
1428 } else if (Count < ElementCount) {
1429 g_zerobytes ((ElementCount - Count) * ElementSize);
1430 } else if (Count > ElementCount) {
1431 Error ("Too many initializers");
1433 return ElementCount * ElementSize;
1438 static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers)
1439 /* Parse initialization of a struct or union. Return the number of data bytes. */
1443 unsigned StructSize;
1447 /* Consume the opening curly brace */
1450 /* Get a pointer to the struct entry from the type */
1451 Entry = GetSymEntry (T);
1453 /* Get the size of the struct from the symbol table entry */
1454 StructSize = Entry->V.S.Size;
1456 /* Check if this struct definition has a field table. If it doesn't, it
1457 * is an incomplete definition.
1459 Tab = Entry->V.S.SymTab;
1461 Error ("Cannot initialize variables with incomplete type");
1462 /* Try error recovery */
1463 SkipInitializer (1);
1464 /* Nothing initialized */
1468 /* Get a pointer to the list of symbols */
1469 Entry = Tab->SymHead;
1471 /* Initialize fields */
1473 while (CurTok.Tok != TOK_RCURLY) {
1475 Error ("Too many initializers");
1476 SkipInitializer (1);
1479 /* Parse initialization of one field. Flexible array members may
1480 * only be initialized if they are the last field (or part of the
1481 * last struct field).
1483 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1484 Entry = Entry->NextSym;
1485 if (CurTok.Tok != TOK_COMMA)
1490 /* Consume the closing curly brace */
1493 /* If there are struct fields left, reserve additional storage */
1494 if (Size < StructSize) {
1495 g_zerobytes (StructSize - Size);
1499 /* Return the actual number of bytes initialized. This number may be
1500 * larger than StructSize if flexible array members are present and were
1501 * initialized (possible in non ANSI mode).
1508 static unsigned ParseVoidInit (void)
1509 /* Parse an initialization of a void variable (special cc65 extension).
1510 * Return the number of bytes initialized.
1519 /* Allow an arbitrary list of values */
1522 ConstExpr (hie1, &Expr);
1523 switch (UnqualifiedType (Expr.Type[0].C)) {
1527 if (ED_IsConstAbsInt (&Expr)) {
1528 /* Make it byte sized */
1532 Size += SIZEOF_CHAR;
1541 if (ED_IsConstAbsInt (&Expr)) {
1542 /* Make it word sized */
1543 Expr.IVal &= 0xFFFF;
1551 if (ED_IsConstAbsInt (&Expr)) {
1552 /* Make it dword sized */
1553 Expr.IVal &= 0xFFFFFFFF;
1556 Size += SIZEOF_LONG;
1560 Error ("Illegal type in initialization");
1565 if (CurTok.Tok != TOK_COMMA) {
1570 } while (CurTok.Tok != TOK_RCURLY);
1575 /* Return the number of bytes initialized */
1581 static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers)
1582 /* Parse initialization of variables. Return the number of data bytes. */
1584 switch (UnqualifiedType (T->C)) {
1594 return ParseScalarInit (T);
1597 return ParsePointerInit (T);
1600 return ParseArrayInit (T, AllowFlexibleMembers);
1604 return ParseStructInit (T, AllowFlexibleMembers);
1607 if (IS_Get (&Standard) == STD_CC65) {
1608 /* Special cc65 extension in non ANSI mode */
1609 return ParseVoidInit ();
1614 Error ("Illegal type");
1622 unsigned ParseInit (Type* T)
1623 /* Parse initialization of variables. Return the number of data bytes. */
1625 /* Parse the initialization. Flexible array members can only be initialized
1628 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
1630 /* The initialization may not generate code on global level, because code
1631 * outside function scope will never get executed.
1633 if (HaveGlobalCode ()) {
1634 Error ("Non constant initializers");
1635 RemoveGlobalCode ();
1638 /* Return the size needed for the initialization */