1 /*****************************************************************************/
5 /* Parse variable and function declarations */
9 /* (C) 1998-2003 Ullrich von Bassewitz */
10 /* Römerstrasse 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 /*****************************************************************************/
62 /*****************************************************************************/
64 /*****************************************************************************/
68 static void ParseTypeSpec (DeclSpec* D, int Default);
69 /* Parse a type specificier */
71 static unsigned ParseInitInternal (type* T, int AllowFlexibleMembers);
72 /* Parse initialization of variables. Return the number of data bytes. */
76 /*****************************************************************************/
77 /* internal functions */
78 /*****************************************************************************/
82 static type OptionalQualifiers (type Q)
83 /* Read type qualifiers if we have any */
85 while (CurTok.Tok == TOK_CONST || CurTok.Tok == TOK_VOLATILE) {
90 if (Q & T_QUAL_CONST) {
91 Error ("Duplicate qualifier: `const'");
97 if (Q & T_QUAL_VOLATILE) {
98 Error ("Duplicate qualifier: `volatile'");
100 Q |= T_QUAL_VOLATILE;
104 /* Keep gcc silent */
113 /* Return the qualifiers read */
119 static void optionalint (void)
120 /* Eat an optional "int" token */
122 if (CurTok.Tok == TOK_INT) {
130 static void optionalsigned (void)
131 /* Eat an optional "signed" token */
133 if (CurTok.Tok == TOK_SIGNED) {
141 static void InitDeclSpec (DeclSpec* D)
142 /* Initialize the DeclSpec struct for use */
151 static void InitDeclaration (Declaration* D)
152 /* Initialize the Declaration struct for use */
161 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
162 /* Parse a storage class */
164 /* Assume we're using an explicit storage class */
165 D->Flags &= ~DS_DEF_STORAGE;
167 /* Check the storage class given */
168 switch (CurTok.Tok) {
171 D->StorageClass = SC_EXTERN | SC_STATIC;
176 D->StorageClass = SC_STATIC;
181 D->StorageClass = SC_REGISTER | SC_STATIC;
186 D->StorageClass = SC_AUTO;
191 D->StorageClass = SC_TYPEDEF;
196 /* No storage class given, use default */
197 D->Flags |= DS_DEF_STORAGE;
198 D->StorageClass = DefStorage;
205 static void ParseEnumDecl (void)
206 /* Process an enum declaration . */
211 /* Accept forward definitions */
212 if (CurTok.Tok != TOK_LCURLY) {
216 /* Skip the opening curly brace */
219 /* Read the enum tags */
221 while (CurTok.Tok != TOK_RCURLY) {
223 /* We expect an identifier */
224 if (CurTok.Tok != TOK_IDENT) {
225 Error ("Identifier expected");
229 /* Remember the identifier and skip it */
230 strcpy (Ident, CurTok.Ident);
233 /* Check for an assigned value */
234 if (CurTok.Tok == TOK_ASSIGN) {
238 EnumVal = lval.ConstVal;
241 /* Add an entry to the symbol table */
242 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
244 /* Check for end of definition */
245 if (CurTok.Tok != TOK_COMMA)
254 static SymEntry* ParseStructDecl (const char* Name, type StructType)
255 /* Parse a struct/union declaration. */
266 if (CurTok.Tok != TOK_LCURLY) {
267 /* Just a forward declaration. Try to find a struct with the given
268 * name. If there is none, insert a forward declaration into the
269 * current lexical level.
271 Entry = FindTagSym (Name);
273 Entry = AddStructSym (Name, 0, 0);
274 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
275 /* Already defined in the level but no struct */
276 Error ("Symbol `%s' is already different kind", Name);
281 /* Add a forward declaration for the struct in the current lexical level */
282 Entry = AddStructSym (Name, 0, 0);
284 /* Skip the curly brace */
287 /* Enter a new lexical level for the struct */
290 /* Parse struct fields */
293 while (CurTok.Tok != TOK_RCURLY) {
295 /* Get the type of the entry */
297 InitDeclSpec (&Spec);
298 ParseTypeSpec (&Spec, -1);
300 /* Read fields with this type */
305 /* If we had a flexible array member before, no other fields can
308 if (FlexibleMember) {
309 Error ("Flexible array member must be last field");
310 FlexibleMember = 0; /* Avoid further errors */
313 /* Get type and name of the struct field */
314 ParseDecl (&Spec, &Decl, 0);
316 /* Get the offset of this field */
317 Offs = (StructType == T_STRUCT)? StructSize : 0;
319 /* Calculate the sizes, handle flexible array members */
320 if (StructType == T_STRUCT) {
322 /* It's a struct. Check if this field is a flexible array
323 * member, and calculate the size of the field.
325 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
326 /* Array with unspecified size */
327 if (StructSize == 0) {
328 Error ("Flexible array member cannot be first struct field");
331 /* Assume zero for size calculations */
332 Encode (Decl.Type + 1, FLEXIBLE);
334 StructSize += CheckedSizeOf (Decl.Type);
340 FieldSize = CheckedSizeOf (Decl.Type);
341 if (FieldSize > StructSize) {
342 StructSize = FieldSize;
346 /* Add a field entry to the table */
347 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
349 if (CurTok.Tok != TOK_COMMA) {
357 /* Skip the closing brace */
360 /* Remember the symbol table and leave the struct level */
361 FieldTab = GetSymTab ();
364 /* Make a real entry from the forward decl and return it */
365 return AddStructSym (Name, StructSize, FieldTab);
370 static void ParseTypeSpec (DeclSpec* D, int Default)
371 /* Parse a type specificier */
376 type Qualifiers; /* Type qualifiers */
378 /* Assume we have an explicit type */
379 D->Flags &= ~DS_DEF_TYPE;
381 /* Read type qualifiers if we have any */
382 Qualifiers = OptionalQualifiers (T_QUAL_NONE);
384 /* Look at the data type */
385 switch (CurTok.Tok) {
395 D->Type[0] = GetDefaultChar();
401 if (CurTok.Tok == TOK_UNSIGNED) {
404 D->Type[0] = T_ULONG;
416 if (CurTok.Tok == TOK_UNSIGNED) {
419 D->Type[0] = T_USHORT;
424 D->Type[0] = T_SHORT;
437 switch (CurTok.Tok) {
441 D->Type[0] = T_SCHAR;
448 D->Type[0] = T_SHORT;
472 switch (CurTok.Tok) {
476 D->Type[0] = T_UCHAR;
483 D->Type[0] = T_USHORT;
490 D->Type[0] = T_ULONG;
507 StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
510 if (CurTok.Tok == TOK_IDENT) {
511 strcpy (Ident, CurTok.Ident);
514 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
516 /* Remember we have an extra type decl */
517 D->Flags |= DS_EXTRA_TYPE;
518 /* Declare the struct in the current scope */
519 Entry = ParseStructDecl (Ident, StructType);
520 /* Encode the struct entry into the type */
521 D->Type[0] = StructType;
522 EncodePtr (D->Type+1, Entry);
523 D->Type[DECODE_SIZE+1] = T_END;
528 if (CurTok.Tok != TOK_LCURLY) {
530 if (CurTok.Tok == TOK_IDENT) {
531 /* Find an entry with this name */
532 Entry = FindTagSym (CurTok.Ident);
534 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
535 Error ("Symbol `%s' is already different kind", Entry->Name);
538 /* Insert entry into table ### */
540 /* Skip the identifier */
543 Error ("Identifier expected");
546 /* Remember we have an extra type decl */
547 D->Flags |= DS_EXTRA_TYPE;
548 /* Parse the enum decl */
555 Entry = FindSym (CurTok.Ident);
556 if (Entry && SymIsTypeDef (Entry)) {
559 TypeCpy (D->Type, Entry->Type);
566 Error ("Type expected");
570 D->Flags |= DS_DEF_TYPE;
571 D->Type[0] = (type) Default;
577 /* There may also be qualifiers *after* the initial type */
578 D->Type[0] |= OptionalQualifiers (Qualifiers);
583 static type* ParamTypeCvt (type* T)
584 /* If T is an array, convert it to a pointer else do nothing. Return the
588 if (IsTypeArray (T)) {
597 static void ParseOldStyleParamList (FuncDesc* F)
598 /* Parse an old style (K&R) parameter list */
601 while (CurTok.Tok != TOK_RPAREN) {
603 /* List of identifiers expected */
604 if (CurTok.Tok != TOK_IDENT) {
605 Error ("Identifier expected");
608 /* Create a symbol table entry with type int */
609 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF, 0);
611 /* Count arguments */
614 /* Skip the identifier */
617 /* Check for more parameters */
618 if (CurTok.Tok == TOK_COMMA) {
625 /* Skip right paren. We must explicitly check for one here, since some of
626 * the breaks above bail out without checking.
630 /* An optional list of type specifications follows */
631 while (CurTok.Tok != TOK_LCURLY) {
635 /* Read the declaration specifier */
636 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
638 /* We accept only auto and register as storage class specifiers, but
639 * we ignore all this, since we use auto anyway.
641 if ((Spec.StorageClass & SC_AUTO) == 0 &&
642 (Spec.StorageClass & SC_REGISTER) == 0) {
643 Error ("Illegal storage class");
646 /* Parse a comma separated variable list */
651 /* Read the parameter */
652 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
653 if (Decl.Ident[0] != '\0') {
655 /* We have a name given. Search for the symbol */
656 SymEntry* Sym = FindLocalSym (Decl.Ident);
658 /* Found it, change the default type to the one given */
659 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
661 Error ("Unknown identifier: `%s'", Decl.Ident);
665 if (CurTok.Tok == TOK_COMMA) {
673 /* Variable list must be semicolon terminated */
680 static void ParseAnsiParamList (FuncDesc* F)
681 /* Parse a new style (ANSI) parameter list */
684 while (CurTok.Tok != TOK_RPAREN) {
690 /* Allow an ellipsis as last parameter */
691 if (CurTok.Tok == TOK_ELLIPSIS) {
693 F->Flags |= FD_VARIADIC;
697 /* Read the declaration specifier */
698 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
700 /* We accept only auto and register as storage class specifiers */
701 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
702 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
703 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
704 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
706 Error ("Illegal storage class");
707 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
710 /* Allow parameters without a name, but remember if we had some to
711 * eventually print an error message later.
713 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
714 if (Decl.Ident[0] == '\0') {
716 /* Unnamed symbol. Generate a name that is not user accessible,
717 * then handle the symbol normal.
719 AnonName (Decl.Ident, "param");
720 F->Flags |= FD_UNNAMED_PARAMS;
722 /* Clear defined bit on nonames */
723 Spec.StorageClass &= ~SC_DEF;
726 /* Parse an attribute ### */
727 ParseAttribute (&Decl, &Attr);
729 /* Create a symbol table entry */
730 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Spec.StorageClass, 0);
732 /* Count arguments */
735 /* Check for more parameters */
736 if (CurTok.Tok == TOK_COMMA) {
743 /* Skip right paren. We must explicitly check for one here, since some of
744 * the breaks above bail out without checking.
748 /* Check if this is a function definition */
749 if (CurTok.Tok == TOK_LCURLY) {
750 /* Print an error if in strict ANSI mode and we have unnamed
753 if (ANSI && (F->Flags & FD_UNNAMED_PARAMS) != 0) {
754 Error ("Parameter name omitted");
761 static FuncDesc* ParseFuncDecl (const DeclSpec* Spec)
762 /* Parse the argument list of a function. */
767 /* Create a new function descriptor */
768 FuncDesc* F = NewFuncDesc ();
770 /* Enter a new lexical level */
771 EnterFunctionLevel ();
773 /* Check for several special parameter lists */
774 if (CurTok.Tok == TOK_RPAREN) {
775 /* Parameter list is empty */
776 F->Flags |= (FD_EMPTY | FD_VARIADIC);
777 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
778 /* Parameter list declared as void */
780 F->Flags |= FD_VOID_PARAM;
781 } else if (CurTok.Tok == TOK_IDENT &&
782 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
783 /* If the identifier is a typedef, we have a new style parameter list,
784 * if it's some other identifier, it's an old style parameter list.
786 Sym = FindSym (CurTok.Ident);
787 if (Sym == 0 || !SymIsTypeDef (Sym)) {
788 /* Old style (K&R) function. Assume variable param list. */
789 F->Flags |= (FD_OLDSTYLE | FD_VARIADIC);
793 /* Check for an implicit int return in the function */
794 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
795 Spec->Type[0] == T_INT &&
796 Spec->Type[1] == T_END) {
797 /* Function has an implicit int return */
798 F->Flags |= FD_OLDSTYLE_INTRET;
802 if ((F->Flags & FD_OLDSTYLE) == 0) {
803 /* New style function */
804 ParseAnsiParamList (F);
806 /* Old style function */
807 ParseOldStyleParamList (F);
810 /* Remember the last function parameter. We need it later for several
811 * purposes, for example when passing stuff to fastcall functions. Since
812 * more symbols are added to the table, it is easier if we remember it
813 * now, since it is currently the last entry in the symbol table.
815 F->LastParam = GetSymTab()->SymTail;
817 /* Assign offsets. If the function has a variable parameter list,
818 * there's one additional byte (the arg size).
820 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
823 unsigned Size = CheckedSizeOf (Sym->Type);
824 if (SymIsRegVar (Sym)) {
825 Sym->V.R.SaveOffs = Offs;
830 F->ParamSize += Size;
834 /* Leave the lexical level remembering the symbol tables */
835 RememberFunctionLevel (F);
837 /* Return the function descriptor */
843 static void Decl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
844 /* Recursively process declarators. Build a type array in reverse order. */
847 if (CurTok.Tok == TOK_STAR) {
850 /* Allow optional const or volatile qualifiers */
851 T |= OptionalQualifiers (T_QUAL_NONE);
852 Decl (Spec, D, Mode);
855 } else if (CurTok.Tok == TOK_LPAREN) {
857 Decl (Spec, D, Mode);
859 } else if (CurTok.Tok == TOK_FASTCALL) {
860 /* Remember the current type pointer */
862 /* Skip the fastcall token */
864 /* Parse the function */
865 Decl (Spec, D, Mode);
866 /* Set the fastcall flag */
867 if (!IsTypeFunc (T) && !IsTypeFuncPtr (T)) {
868 Error ("__fastcall__ modifier applied to non function");
869 } else if (IsVariadicFunc (T)) {
870 Error ("Cannot apply __fastcall__ to functions with variable parameter list");
872 FuncDesc* F = GetFuncDesc (T);
873 F->Flags |= FD_FASTCALL;
877 /* Things depend on Mode now:
878 * - Mode == DM_NEED_IDENT means:
879 * we *must* have a type and a variable identifer.
880 * - Mode == DM_NO_IDENT means:
881 * we must have a type but no variable identifer
882 * (if there is one, it's not read).
883 * - Mode == DM_ACCEPT_IDENT means:
884 * we *may* have an identifier. If there is an identifier,
885 * it is read, but it is no error, if there is none.
887 if (Mode == DM_NO_IDENT) {
889 } else if (CurTok.Tok == TOK_IDENT) {
890 strcpy (D->Ident, CurTok.Ident);
893 if (Mode == DM_NEED_IDENT) {
894 Error ("Identifier expected");
900 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
901 if (CurTok.Tok == TOK_LPAREN) {
902 /* Function declaration */
905 /* Parse the function declaration */
906 F = ParseFuncDecl (Spec);
911 /* Array declaration */
912 long Size = UNSPECIFIED;
914 /* Read the size if it is given */
915 if (CurTok.Tok != TOK_RBRACK) {
918 if (lval.ConstVal <= 0) {
919 if (D->Ident[0] != '\0') {
920 Error ("Size of array `%s' is invalid", D->Ident);
922 Error ("Size of array is invalid");
926 Size = lval.ConstVal;
938 /*****************************************************************************/
940 /*****************************************************************************/
944 type* ParseType (type* Type)
945 /* Parse a complete type specification */
950 /* Get a type without a default */
951 InitDeclSpec (&Spec);
952 ParseTypeSpec (&Spec, -1);
954 /* Parse additional declarators */
955 InitDeclaration (&Decl);
956 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
958 /* Copy the type to the target buffer */
959 TypeCpy (Type, Decl.Type);
961 /* Return a pointer to the target buffer */
967 void ParseDecl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
968 /* Parse a variable, type or function declaration */
970 /* Initialize the Declaration struct */
973 /* Get additional declarators and the identifier */
974 Decl (Spec, D, Mode);
976 /* Add the base type. */
977 TypeCpy (D->T, Spec->Type);
979 /* Check the size of the generated type */
980 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type) && SizeOf (D->Type) >= 0x10000) {
981 if (D->Ident[0] != '\0') {
982 Error ("Size of `%s' is invalid", D->Ident);
984 Error ("Invalid size");
991 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, int DefType)
992 /* Parse a declaration specification */
994 /* Initialize the DeclSpec struct */
997 /* First, get the storage class specifier for this declaration */
998 ParseStorageClass (D, DefStorage);
1000 /* Parse the type specifiers */
1001 ParseTypeSpec (D, DefType);
1006 void CheckEmptyDecl (const DeclSpec* D)
1007 /* Called after an empty type declaration (that is, a type declaration without
1008 * a variable). Checks if the declaration does really make sense and issues a
1012 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1013 Warning ("Useless declaration");
1019 static void SkipInitializer (unsigned BracesExpected)
1020 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1021 * smart so we don't have too many following errors.
1024 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1025 switch (CurTok.Tok) {
1026 case TOK_RCURLY: --BracesExpected; break;
1027 case TOK_LCURLY: ++BracesExpected; break;
1036 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1037 /* Accept any number of opening curly braces around an initialization, skip
1038 * them and return the number. If the number of curly braces is less than
1039 * BracesNeeded, issue a warning.
1042 unsigned BraceCount = 0;
1043 while (CurTok.Tok == TOK_LCURLY) {
1047 if (BraceCount < BracesNeeded) {
1048 Error ("`{' expected");
1055 static void ClosingCurlyBraces (unsigned BracesExpected)
1056 /* Accept and skip the given number of closing curly braces together with
1057 * an optional comma. Output an error messages, if the input does not contain
1058 * the expected number of braces.
1061 while (BracesExpected) {
1062 if (CurTok.Tok == TOK_RCURLY) {
1064 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1068 Error ("`}' expected");
1077 static unsigned ParseScalarInit (type* T)
1078 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1082 /* Optional opening brace */
1083 unsigned BraceCount = OpeningCurlyBraces (0);
1085 /* We warn if an initializer for a scalar contains braces, because this is
1086 * quite unusual and often a sign for some problem in the input.
1088 if (BraceCount > 0) {
1089 Warning ("Braces around scalar initializer");
1092 /* Get the expression and convert it to the target type */
1094 TypeConversion (&ED, 0, T);
1096 /* Output the data */
1099 /* Close eventually opening braces */
1100 ClosingCurlyBraces (BraceCount);
1108 static unsigned ParsePointerInit (type* T)
1109 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1111 /* Optional opening brace */
1112 unsigned BraceCount = OpeningCurlyBraces (0);
1117 if ((ED.Flags & E_MCTYPE) == E_TCONST) {
1118 /* Make the const value the correct size */
1119 ED.ConstVal &= 0xFFFF;
1121 TypeConversion (&ED, 0, T);
1123 /* Output the data */
1126 /* Close eventually opening braces */
1127 ClosingCurlyBraces (BraceCount);
1135 static unsigned ParseArrayInit (type* T, int AllowFlexibleMembers)
1136 /* Parse initializaton for arrays. Return the number of data bytes. */
1140 /* Get the array data */
1141 type* ElementType = GetElementType (T);
1142 unsigned ElementSize = CheckedSizeOf (ElementType);
1143 long ElementCount = GetElementCount (T);
1145 /* Special handling for a character array initialized by a literal */
1146 if (IsTypeChar (ElementType) && CurTok.Tok == TOK_SCONST) {
1148 /* Char array initialized by string constant */
1149 const char* Str = GetLiteral (CurTok.IVal);
1150 Count = GetLiteralPoolOffs () - CurTok.IVal;
1152 /* Translate into target charset */
1153 TranslateLiteralPool (CurTok.IVal);
1155 /* If the array is one too small for the string literal, omit the
1158 if (ElementCount != UNSPECIFIED &&
1159 ElementCount != FLEXIBLE &&
1160 Count == ElementCount + 1) {
1161 /* Omit the trailing zero */
1165 /* Output the data */
1166 g_defbytes (Str, Count);
1168 /* Remove string from pool */
1169 ResetLiteralPoolOffs (CurTok.IVal);
1177 /* Initialize the array members */
1179 while (CurTok.Tok != TOK_RCURLY) {
1180 /* Flexible array members may not be initialized within
1181 * an array (because the size of each element may differ
1184 ParseInitInternal (ElementType, 0);
1186 if (CurTok.Tok != TOK_COMMA)
1191 /* Closing curly braces */
1196 if (ElementCount == UNSPECIFIED) {
1197 /* Number of elements determined by initializer */
1198 Encode (T + 1, Count);
1199 ElementCount = Count;
1200 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1201 /* In non ANSI mode, allow initialization of flexible array
1204 ElementCount = Count;
1205 } else if (Count < ElementCount) {
1206 g_zerobytes ((ElementCount - Count) * ElementSize);
1207 } else if (Count > ElementCount) {
1208 Error ("Too many initializers");
1210 return ElementCount * ElementSize;
1215 static unsigned ParseStructInit (type* Type, int AllowFlexibleMembers)
1216 /* Parse initialization of a struct or union. Return the number of data bytes. */
1220 unsigned StructSize;
1224 /* Consume the opening curly brace */
1227 /* Get a pointer to the struct entry from the type */
1228 Entry = DecodePtr (Type + 1);
1230 /* Get the size of the struct from the symbol table entry */
1231 StructSize = Entry->V.S.Size;
1233 /* Check if this struct definition has a field table. If it doesn't, it
1234 * is an incomplete definition.
1236 Tab = Entry->V.S.SymTab;
1238 Error ("Cannot initialize variables with incomplete type");
1239 /* Try error recovery */
1240 SkipInitializer (1);
1241 /* Nothing initialized */
1245 /* Get a pointer to the list of symbols */
1246 Entry = Tab->SymHead;
1248 /* Initialize fields */
1250 while (CurTok.Tok != TOK_RCURLY) {
1252 Error ("Too many initializers");
1253 SkipInitializer (1);
1256 /* Parse initialization of one field. Flexible array members may
1257 * only be initialized if they are the last field (or part of the
1258 * last struct field).
1260 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1261 Entry = Entry->NextSym;
1262 if (CurTok.Tok != TOK_COMMA)
1267 /* Consume the closing curly brace */
1270 /* If there are struct fields left, reserve additional storage */
1271 if (Size < StructSize) {
1272 g_zerobytes (StructSize - Size);
1276 /* Return the actual number of bytes initialized. This number may be
1277 * larger than StructSize if flexible array members are present and were
1278 * initialized (possible in non ANSI mode).
1285 static unsigned ParseVoidInit (void)
1286 /* Parse an initialization of a void variable (special cc65 extension).
1287 * Return the number of bytes initialized.
1296 /* Allow an arbitrary list of values */
1300 switch (UnqualifiedType (lval.Type[0])) {
1304 if ((lval.Flags & E_MCTYPE) == E_TCONST) {
1305 /* Make it byte sized */
1306 lval.ConstVal &= 0xFF;
1309 Size += SIZEOF_CHAR;
1318 if ((lval.Flags & E_MCTYPE) == E_TCONST) {
1319 /* Make it word sized */
1320 lval.ConstVal &= 0xFFFF;
1329 Size += SIZEOF_LONG;
1333 Error ("Illegal type in initialization");
1338 if (CurTok.Tok != TOK_COMMA) {
1343 } while (CurTok.Tok != TOK_RCURLY);
1348 /* Return the number of bytes initialized */
1354 static unsigned ParseInitInternal (type* T, int AllowFlexibleMembers)
1355 /* Parse initialization of variables. Return the number of data bytes. */
1357 switch (UnqualifiedType (*T)) {
1367 return ParseScalarInit (T);
1370 return ParsePointerInit (T);
1373 return ParseArrayInit (T, AllowFlexibleMembers);
1377 return ParseStructInit (T, AllowFlexibleMembers);
1381 /* Special cc65 extension in non ANSI mode */
1382 return ParseVoidInit ();
1387 Error ("Illegal type");
1395 unsigned ParseInit (type* T)
1396 /* Parse initialization of variables. Return the number of data bytes. */
1398 /* Parse the initialization */
1399 unsigned Size = ParseInitInternal (T, !ANSI);
1401 /* The initialization may not generate code on global level, because code
1402 * outside function scope will never get executed.
1404 if (HaveGlobalCode ()) {
1405 Error ("Non constant initializers");
1406 RemoveGlobalCode ();
1409 /* Return the size needed for the initialization */