1 /*****************************************************************************/
5 /* Parse variable and function declarations */
9 /* (C) 1998-2004 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 /*****************************************************************************/
64 /*****************************************************************************/
66 /*****************************************************************************/
70 static void ParseTypeSpec (DeclSpec* D, int Default);
71 /* Parse a type specificier */
73 static unsigned ParseInitInternal (type* T, int AllowFlexibleMembers);
74 /* Parse initialization of variables. Return the number of data bytes. */
78 /*****************************************************************************/
79 /* internal functions */
80 /*****************************************************************************/
84 static type OptionalQualifiers (type Q)
85 /* Read type qualifiers if we have any */
87 while (CurTok.Tok == TOK_CONST || CurTok.Tok == TOK_VOLATILE) {
92 if (Q & T_QUAL_CONST) {
93 Error ("Duplicate qualifier: `const'");
99 if (Q & T_QUAL_VOLATILE) {
100 Error ("Duplicate qualifier: `volatile'");
102 Q |= T_QUAL_VOLATILE;
106 /* Keep gcc silent */
115 /* Return the qualifiers read */
121 static void optionalint (void)
122 /* Eat an optional "int" token */
124 if (CurTok.Tok == TOK_INT) {
132 static void optionalsigned (void)
133 /* Eat an optional "signed" token */
135 if (CurTok.Tok == TOK_SIGNED) {
143 static void InitDeclSpec (DeclSpec* D)
144 /* Initialize the DeclSpec struct for use */
153 static void InitDeclaration (Declaration* D)
154 /* Initialize the Declaration struct for use */
163 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
164 /* Parse a storage class */
166 /* Assume we're using an explicit storage class */
167 D->Flags &= ~DS_DEF_STORAGE;
169 /* Check the storage class given */
170 switch (CurTok.Tok) {
173 D->StorageClass = SC_EXTERN | SC_STATIC;
178 D->StorageClass = SC_STATIC;
183 D->StorageClass = SC_REGISTER | SC_STATIC;
188 D->StorageClass = SC_AUTO;
193 D->StorageClass = SC_TYPEDEF;
198 /* No storage class given, use default */
199 D->Flags |= DS_DEF_STORAGE;
200 D->StorageClass = DefStorage;
207 static void ParseEnumDecl (void)
208 /* Process an enum declaration . */
213 /* Accept forward definitions */
214 if (CurTok.Tok != TOK_LCURLY) {
218 /* Skip the opening curly brace */
221 /* Read the enum tags */
223 while (CurTok.Tok != TOK_RCURLY) {
225 /* We expect an identifier */
226 if (CurTok.Tok != TOK_IDENT) {
227 Error ("Identifier expected");
231 /* Remember the identifier and skip it */
232 strcpy (Ident, CurTok.Ident);
235 /* Check for an assigned value */
236 if (CurTok.Tok == TOK_ASSIGN) {
240 EnumVal = lval.ConstVal;
243 /* Add an entry to the symbol table */
244 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
246 /* Check for end of definition */
247 if (CurTok.Tok != TOK_COMMA)
256 static SymEntry* ParseStructDecl (const char* Name, type StructType)
257 /* Parse a struct/union declaration. */
268 if (CurTok.Tok != TOK_LCURLY) {
269 /* Just a forward declaration. Try to find a struct with the given
270 * name. If there is none, insert a forward declaration into the
271 * current lexical level.
273 Entry = FindTagSym (Name);
275 Entry = AddStructSym (Name, 0, 0);
276 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
277 /* Already defined in the level but no struct */
278 Error ("Symbol `%s' is already different kind", Name);
283 /* Add a forward declaration for the struct in the current lexical level */
284 Entry = AddStructSym (Name, 0, 0);
286 /* Skip the curly brace */
289 /* Enter a new lexical level for the struct */
292 /* Parse struct fields */
295 while (CurTok.Tok != TOK_RCURLY) {
297 /* Get the type of the entry */
299 InitDeclSpec (&Spec);
300 ParseTypeSpec (&Spec, -1);
302 /* Read fields with this type */
307 /* If we had a flexible array member before, no other fields can
310 if (FlexibleMember) {
311 Error ("Flexible array member must be last field");
312 FlexibleMember = 0; /* Avoid further errors */
315 /* Get type and name of the struct field */
316 ParseDecl (&Spec, &Decl, 0);
318 /* Get the offset of this field */
319 Offs = (StructType == T_STRUCT)? StructSize : 0;
321 /* Calculate the sizes, handle flexible array members */
322 if (StructType == T_STRUCT) {
324 /* It's a struct. Check if this field is a flexible array
325 * member, and calculate the size of the field.
327 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
328 /* Array with unspecified size */
329 if (StructSize == 0) {
330 Error ("Flexible array member cannot be first struct field");
333 /* Assume zero for size calculations */
334 Encode (Decl.Type + 1, FLEXIBLE);
336 StructSize += CheckedSizeOf (Decl.Type);
342 FieldSize = CheckedSizeOf (Decl.Type);
343 if (FieldSize > StructSize) {
344 StructSize = FieldSize;
348 /* Add a field entry to the table */
349 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
351 if (CurTok.Tok != TOK_COMMA) {
359 /* Skip the closing brace */
362 /* Remember the symbol table and leave the struct level */
363 FieldTab = GetSymTab ();
366 /* Make a real entry from the forward decl and return it */
367 return AddStructSym (Name, StructSize, FieldTab);
372 static void ParseTypeSpec (DeclSpec* D, int Default)
373 /* Parse a type specificier */
378 type Qualifiers; /* Type qualifiers */
380 /* Assume we have an explicit type */
381 D->Flags &= ~DS_DEF_TYPE;
383 /* Read type qualifiers if we have any */
384 Qualifiers = OptionalQualifiers (T_QUAL_NONE);
386 /* Look at the data type */
387 switch (CurTok.Tok) {
397 D->Type[0] = GetDefaultChar();
403 if (CurTok.Tok == TOK_UNSIGNED) {
406 D->Type[0] = T_ULONG;
418 if (CurTok.Tok == TOK_UNSIGNED) {
421 D->Type[0] = T_USHORT;
426 D->Type[0] = T_SHORT;
439 switch (CurTok.Tok) {
443 D->Type[0] = T_SCHAR;
450 D->Type[0] = T_SHORT;
474 switch (CurTok.Tok) {
478 D->Type[0] = T_UCHAR;
485 D->Type[0] = T_USHORT;
492 D->Type[0] = T_ULONG;
509 D->Type[0] = T_FLOAT;
515 D->Type[0] = T_DOUBLE;
521 StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
524 if (CurTok.Tok == TOK_IDENT) {
525 strcpy (Ident, CurTok.Ident);
528 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
530 /* Remember we have an extra type decl */
531 D->Flags |= DS_EXTRA_TYPE;
532 /* Declare the struct in the current scope */
533 Entry = ParseStructDecl (Ident, StructType);
534 /* Encode the struct entry into the type */
535 D->Type[0] = StructType;
536 EncodePtr (D->Type+1, Entry);
537 D->Type[DECODE_SIZE+1] = T_END;
542 if (CurTok.Tok != TOK_LCURLY) {
544 if (CurTok.Tok == TOK_IDENT) {
545 /* Find an entry with this name */
546 Entry = FindTagSym (CurTok.Ident);
548 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
549 Error ("Symbol `%s' is already different kind", Entry->Name);
552 /* Insert entry into table ### */
554 /* Skip the identifier */
557 Error ("Identifier expected");
560 /* Remember we have an extra type decl */
561 D->Flags |= DS_EXTRA_TYPE;
562 /* Parse the enum decl */
569 Entry = FindSym (CurTok.Ident);
570 if (Entry && SymIsTypeDef (Entry)) {
573 TypeCpy (D->Type, Entry->Type);
580 Error ("Type expected");
584 D->Flags |= DS_DEF_TYPE;
585 D->Type[0] = (type) Default;
591 /* There may also be qualifiers *after* the initial type */
592 D->Type[0] |= OptionalQualifiers (Qualifiers);
597 static type* ParamTypeCvt (type* T)
598 /* If T is an array, convert it to a pointer else do nothing. Return the
602 if (IsTypeArray (T)) {
611 static void ParseOldStyleParamList (FuncDesc* F)
612 /* Parse an old style (K&R) parameter list */
615 while (CurTok.Tok != TOK_RPAREN) {
617 /* List of identifiers expected */
618 if (CurTok.Tok != TOK_IDENT) {
619 Error ("Identifier expected");
622 /* Create a symbol table entry with type int */
623 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF, 0);
625 /* Count arguments */
628 /* Skip the identifier */
631 /* Check for more parameters */
632 if (CurTok.Tok == TOK_COMMA) {
639 /* Skip right paren. We must explicitly check for one here, since some of
640 * the breaks above bail out without checking.
644 /* An optional list of type specifications follows */
645 while (CurTok.Tok != TOK_LCURLY) {
649 /* Read the declaration specifier */
650 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
652 /* We accept only auto and register as storage class specifiers, but
653 * we ignore all this, since we use auto anyway.
655 if ((Spec.StorageClass & SC_AUTO) == 0 &&
656 (Spec.StorageClass & SC_REGISTER) == 0) {
657 Error ("Illegal storage class");
660 /* Parse a comma separated variable list */
665 /* Read the parameter */
666 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
667 if (Decl.Ident[0] != '\0') {
669 /* We have a name given. Search for the symbol */
670 SymEntry* Sym = FindLocalSym (Decl.Ident);
672 /* Found it, change the default type to the one given */
673 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
675 Error ("Unknown identifier: `%s'", Decl.Ident);
679 if (CurTok.Tok == TOK_COMMA) {
687 /* Variable list must be semicolon terminated */
694 static void ParseAnsiParamList (FuncDesc* F)
695 /* Parse a new style (ANSI) parameter list */
698 while (CurTok.Tok != TOK_RPAREN) {
704 /* Allow an ellipsis as last parameter */
705 if (CurTok.Tok == TOK_ELLIPSIS) {
707 F->Flags |= FD_VARIADIC;
711 /* Read the declaration specifier */
712 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
714 /* We accept only auto and register as storage class specifiers */
715 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
716 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
717 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
718 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
720 Error ("Illegal storage class");
721 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
724 /* Allow parameters without a name, but remember if we had some to
725 * eventually print an error message later.
727 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
728 if (Decl.Ident[0] == '\0') {
730 /* Unnamed symbol. Generate a name that is not user accessible,
731 * then handle the symbol normal.
733 AnonName (Decl.Ident, "param");
734 F->Flags |= FD_UNNAMED_PARAMS;
736 /* Clear defined bit on nonames */
737 Spec.StorageClass &= ~SC_DEF;
740 /* Parse an attribute ### */
741 ParseAttribute (&Decl, &Attr);
743 /* Create a symbol table entry */
744 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Spec.StorageClass, 0);
746 /* Count arguments */
749 /* Check for more parameters */
750 if (CurTok.Tok == TOK_COMMA) {
757 /* Skip right paren. We must explicitly check for one here, since some of
758 * the breaks above bail out without checking.
762 /* Check if this is a function definition */
763 if (CurTok.Tok == TOK_LCURLY) {
764 /* Print an error if in strict ANSI mode and we have unnamed
767 if (ANSI && (F->Flags & FD_UNNAMED_PARAMS) != 0) {
768 Error ("Parameter name omitted");
775 static FuncDesc* ParseFuncDecl (const DeclSpec* Spec)
776 /* Parse the argument list of a function. */
781 /* Create a new function descriptor */
782 FuncDesc* F = NewFuncDesc ();
784 /* Enter a new lexical level */
785 EnterFunctionLevel ();
787 /* Check for several special parameter lists */
788 if (CurTok.Tok == TOK_RPAREN) {
789 /* Parameter list is empty */
790 F->Flags |= (FD_EMPTY | FD_VARIADIC);
791 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
792 /* Parameter list declared as void */
794 F->Flags |= FD_VOID_PARAM;
795 } else if (CurTok.Tok == TOK_IDENT &&
796 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
797 /* If the identifier is a typedef, we have a new style parameter list,
798 * if it's some other identifier, it's an old style parameter list.
800 Sym = FindSym (CurTok.Ident);
801 if (Sym == 0 || !SymIsTypeDef (Sym)) {
802 /* Old style (K&R) function. Assume variable param list. */
803 F->Flags |= (FD_OLDSTYLE | FD_VARIADIC);
807 /* Check for an implicit int return in the function */
808 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
809 Spec->Type[0] == T_INT &&
810 Spec->Type[1] == T_END) {
811 /* Function has an implicit int return */
812 F->Flags |= FD_OLDSTYLE_INTRET;
816 if ((F->Flags & FD_OLDSTYLE) == 0) {
817 /* New style function */
818 ParseAnsiParamList (F);
820 /* Old style function */
821 ParseOldStyleParamList (F);
824 /* Remember the last function parameter. We need it later for several
825 * purposes, for example when passing stuff to fastcall functions. Since
826 * more symbols are added to the table, it is easier if we remember it
827 * now, since it is currently the last entry in the symbol table.
829 F->LastParam = GetSymTab()->SymTail;
831 /* Assign offsets. If the function has a variable parameter list,
832 * there's one additional byte (the arg size).
834 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
837 unsigned Size = CheckedSizeOf (Sym->Type);
838 if (SymIsRegVar (Sym)) {
839 Sym->V.R.SaveOffs = Offs;
844 F->ParamSize += Size;
848 /* Add the default address size for the function */
849 if (CodeAddrSize == ADDR_SIZE_FAR) {
855 /* Leave the lexical level remembering the symbol tables */
856 RememberFunctionLevel (F);
858 /* Return the function descriptor */
864 static unsigned FunctionModifierFlags (void)
865 /* Parse __fastcall__, __near__ and __far__ and return the matching FD_ flags */
868 unsigned Flags = FD_NONE;
869 while (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
871 /* Get the flag bit for the next token */
872 unsigned F = FD_NONE;
873 switch (CurTok.Tok) {
874 case TOK_FASTCALL: F = FD_FASTCALL; break;
875 case TOK_NEAR: F = FD_NEAR; break;
876 case TOK_FAR: F = FD_FAR; break;
877 default: Internal ("Unexpected token: %d", CurTok.Tok);
880 /* Remember the flag for this modifier */
882 Error ("Duplicate modifier");
891 if ((Flags & (FD_NEAR | FD_FAR)) == (FD_NEAR | FD_FAR)) {
892 Error ("Cannot specify both, `__near__' and `__far__' modifiers");
893 Flags &= ~(FD_NEAR | FD_FAR);
896 /* Return the flags read */
902 static void ApplyFunctionModifiers (type* T, unsigned Flags)
903 /* Apply a set of function modifier flags to a function */
905 /* Get the function descriptor */
906 FuncDesc* F = GetFuncDesc (T);
908 /* Special check for __fastcall__ */
909 if ((Flags & FD_FASTCALL) != 0 && IsVariadicFunc (T)) {
910 Error ("Cannot apply `__fastcall__' to functions with "
911 "variable parameter list");
912 Flags &= ~FD_FASTCALL;
915 /* Remove the default function address size modifiers */
916 F->Flags &= ~(FD_NEAR | FD_FAR);
918 /* Add the new modifers */
924 static void Decl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
925 /* Recursively process declarators. Build a type array in reverse order. */
927 /* Pointer to something */
928 if (CurTok.Tok == TOK_STAR) {
935 /* Allow optional const or volatile qualifiers */
936 T = T_PTR | OptionalQualifiers (T_QUAL_NONE);
938 /* Parse the type, the pointer points to */
939 Decl (Spec, D, Mode);
945 /* Function modifiers */
946 if (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
948 /* Remember the current type pointer */
952 unsigned Flags = FunctionModifierFlags ();
954 /* Parse the function */
955 Decl (Spec, D, Mode);
957 /* Check that we have a function */
958 if (!IsTypeFunc (T) && !IsTypeFuncPtr (T)) {
959 Error ("Function modifier applied to non function");
961 ApplyFunctionModifiers (T, Flags);
968 if (CurTok.Tok == TOK_LPAREN) {
970 Decl (Spec, D, Mode);
973 /* Things depend on Mode now:
974 * - Mode == DM_NEED_IDENT means:
975 * we *must* have a type and a variable identifer.
976 * - Mode == DM_NO_IDENT means:
977 * we must have a type but no variable identifer
978 * (if there is one, it's not read).
979 * - Mode == DM_ACCEPT_IDENT means:
980 * we *may* have an identifier. If there is an identifier,
981 * it is read, but it is no error, if there is none.
983 if (Mode == DM_NO_IDENT) {
985 } else if (CurTok.Tok == TOK_IDENT) {
986 strcpy (D->Ident, CurTok.Ident);
989 if (Mode == DM_NEED_IDENT) {
990 Error ("Identifier expected");
996 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
997 if (CurTok.Tok == TOK_LPAREN) {
998 /* Function declaration */
1001 /* Parse the function declaration */
1002 F = ParseFuncDecl (Spec);
1004 EncodePtr (D->T, F);
1005 D->T += DECODE_SIZE;
1007 /* Array declaration */
1008 long Size = UNSPECIFIED;
1010 /* Read the size if it is given */
1011 if (CurTok.Tok != TOK_RBRACK) {
1014 if (lval.ConstVal <= 0) {
1015 if (D->Ident[0] != '\0') {
1016 Error ("Size of array `%s' is invalid", D->Ident);
1018 Error ("Size of array is invalid");
1022 Size = lval.ConstVal;
1026 Encode (D->T, Size);
1027 D->T += DECODE_SIZE;
1034 /*****************************************************************************/
1036 /*****************************************************************************/
1040 type* ParseType (type* Type)
1041 /* Parse a complete type specification */
1046 /* Get a type without a default */
1047 InitDeclSpec (&Spec);
1048 ParseTypeSpec (&Spec, -1);
1050 /* Parse additional declarators */
1051 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1053 /* Copy the type to the target buffer */
1054 TypeCpy (Type, Decl.Type);
1056 /* Return a pointer to the target buffer */
1062 void ParseDecl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
1063 /* Parse a variable, type or function declaration */
1065 /* Initialize the Declaration struct */
1066 InitDeclaration (D);
1068 /* Get additional declarators and the identifier */
1069 Decl (Spec, D, Mode);
1071 /* Add the base type. */
1072 TypeCpy (D->T, Spec->Type);
1074 /* Check the size of the generated type */
1075 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type) && SizeOf (D->Type) >= 0x10000) {
1076 if (D->Ident[0] != '\0') {
1077 Error ("Size of `%s' is invalid", D->Ident);
1079 Error ("Invalid size");
1086 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, int DefType)
1087 /* Parse a declaration specification */
1089 /* Initialize the DeclSpec struct */
1092 /* First, get the storage class specifier for this declaration */
1093 ParseStorageClass (D, DefStorage);
1095 /* Parse the type specifiers */
1096 ParseTypeSpec (D, DefType);
1101 void CheckEmptyDecl (const DeclSpec* D)
1102 /* Called after an empty type declaration (that is, a type declaration without
1103 * a variable). Checks if the declaration does really make sense and issues a
1107 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1108 Warning ("Useless declaration");
1114 static void SkipInitializer (unsigned BracesExpected)
1115 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1116 * smart so we don't have too many following errors.
1119 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1120 switch (CurTok.Tok) {
1121 case TOK_RCURLY: --BracesExpected; break;
1122 case TOK_LCURLY: ++BracesExpected; break;
1131 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1132 /* Accept any number of opening curly braces around an initialization, skip
1133 * them and return the number. If the number of curly braces is less than
1134 * BracesNeeded, issue a warning.
1137 unsigned BraceCount = 0;
1138 while (CurTok.Tok == TOK_LCURLY) {
1142 if (BraceCount < BracesNeeded) {
1143 Error ("`{' expected");
1150 static void ClosingCurlyBraces (unsigned BracesExpected)
1151 /* Accept and skip the given number of closing curly braces together with
1152 * an optional comma. Output an error messages, if the input does not contain
1153 * the expected number of braces.
1156 while (BracesExpected) {
1157 if (CurTok.Tok == TOK_RCURLY) {
1159 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1163 Error ("`}' expected");
1172 static unsigned ParseScalarInit (type* T)
1173 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1177 /* Optional opening brace */
1178 unsigned BraceCount = OpeningCurlyBraces (0);
1180 /* We warn if an initializer for a scalar contains braces, because this is
1181 * quite unusual and often a sign for some problem in the input.
1183 if (BraceCount > 0) {
1184 Warning ("Braces around scalar initializer");
1187 /* Get the expression and convert it to the target type */
1189 TypeConversion (&ED, 0, T);
1191 /* Output the data */
1194 /* Close eventually opening braces */
1195 ClosingCurlyBraces (BraceCount);
1203 static unsigned ParsePointerInit (type* T)
1204 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1206 /* Optional opening brace */
1207 unsigned BraceCount = OpeningCurlyBraces (0);
1212 if ((ED.Flags & E_MCTYPE) == E_TCONST) {
1213 /* Make the const value the correct size */
1214 ED.ConstVal &= 0xFFFF;
1216 TypeConversion (&ED, 0, T);
1218 /* Output the data */
1221 /* Close eventually opening braces */
1222 ClosingCurlyBraces (BraceCount);
1230 static unsigned ParseArrayInit (type* T, int AllowFlexibleMembers)
1231 /* Parse initializaton for arrays. Return the number of data bytes. */
1235 /* Get the array data */
1236 type* ElementType = GetElementType (T);
1237 unsigned ElementSize = CheckedSizeOf (ElementType);
1238 long ElementCount = GetElementCount (T);
1240 /* Special handling for a character array initialized by a literal */
1241 if (IsTypeChar (ElementType) && CurTok.Tok == TOK_SCONST) {
1243 /* Char array initialized by string constant */
1244 const char* Str = GetLiteral (CurTok.IVal);
1245 Count = GetLiteralPoolOffs () - CurTok.IVal;
1247 /* Translate into target charset */
1248 TranslateLiteralPool (CurTok.IVal);
1250 /* If the array is one too small for the string literal, omit the
1253 if (ElementCount != UNSPECIFIED &&
1254 ElementCount != FLEXIBLE &&
1255 Count == ElementCount + 1) {
1256 /* Omit the trailing zero */
1260 /* Output the data */
1261 g_defbytes (Str, Count);
1263 /* Remove string from pool */
1264 ResetLiteralPoolOffs (CurTok.IVal);
1272 /* Initialize the array members */
1274 while (CurTok.Tok != TOK_RCURLY) {
1275 /* Flexible array members may not be initialized within
1276 * an array (because the size of each element may differ
1279 ParseInitInternal (ElementType, 0);
1281 if (CurTok.Tok != TOK_COMMA)
1286 /* Closing curly braces */
1291 if (ElementCount == UNSPECIFIED) {
1292 /* Number of elements determined by initializer */
1293 Encode (T + 1, Count);
1294 ElementCount = Count;
1295 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1296 /* In non ANSI mode, allow initialization of flexible array
1299 ElementCount = Count;
1300 } else if (Count < ElementCount) {
1301 g_zerobytes ((ElementCount - Count) * ElementSize);
1302 } else if (Count > ElementCount) {
1303 Error ("Too many initializers");
1305 return ElementCount * ElementSize;
1310 static unsigned ParseStructInit (type* Type, int AllowFlexibleMembers)
1311 /* Parse initialization of a struct or union. Return the number of data bytes. */
1315 unsigned StructSize;
1319 /* Consume the opening curly brace */
1322 /* Get a pointer to the struct entry from the type */
1323 Entry = DecodePtr (Type + 1);
1325 /* Get the size of the struct from the symbol table entry */
1326 StructSize = Entry->V.S.Size;
1328 /* Check if this struct definition has a field table. If it doesn't, it
1329 * is an incomplete definition.
1331 Tab = Entry->V.S.SymTab;
1333 Error ("Cannot initialize variables with incomplete type");
1334 /* Try error recovery */
1335 SkipInitializer (1);
1336 /* Nothing initialized */
1340 /* Get a pointer to the list of symbols */
1341 Entry = Tab->SymHead;
1343 /* Initialize fields */
1345 while (CurTok.Tok != TOK_RCURLY) {
1347 Error ("Too many initializers");
1348 SkipInitializer (1);
1351 /* Parse initialization of one field. Flexible array members may
1352 * only be initialized if they are the last field (or part of the
1353 * last struct field).
1355 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1356 Entry = Entry->NextSym;
1357 if (CurTok.Tok != TOK_COMMA)
1362 /* Consume the closing curly brace */
1365 /* If there are struct fields left, reserve additional storage */
1366 if (Size < StructSize) {
1367 g_zerobytes (StructSize - Size);
1371 /* Return the actual number of bytes initialized. This number may be
1372 * larger than StructSize if flexible array members are present and were
1373 * initialized (possible in non ANSI mode).
1380 static unsigned ParseVoidInit (void)
1381 /* Parse an initialization of a void variable (special cc65 extension).
1382 * Return the number of bytes initialized.
1391 /* Allow an arbitrary list of values */
1395 switch (UnqualifiedType (lval.Type[0])) {
1399 if ((lval.Flags & E_MCTYPE) == E_TCONST) {
1400 /* Make it byte sized */
1401 lval.ConstVal &= 0xFF;
1404 Size += SIZEOF_CHAR;
1413 if ((lval.Flags & E_MCTYPE) == E_TCONST) {
1414 /* Make it word sized */
1415 lval.ConstVal &= 0xFFFF;
1424 Size += SIZEOF_LONG;
1428 Error ("Illegal type in initialization");
1433 if (CurTok.Tok != TOK_COMMA) {
1438 } while (CurTok.Tok != TOK_RCURLY);
1443 /* Return the number of bytes initialized */
1449 static unsigned ParseInitInternal (type* T, int AllowFlexibleMembers)
1450 /* Parse initialization of variables. Return the number of data bytes. */
1452 switch (UnqualifiedType (*T)) {
1462 return ParseScalarInit (T);
1465 return ParsePointerInit (T);
1468 return ParseArrayInit (T, AllowFlexibleMembers);
1472 return ParseStructInit (T, AllowFlexibleMembers);
1476 /* Special cc65 extension in non ANSI mode */
1477 return ParseVoidInit ();
1482 Error ("Illegal type");
1490 unsigned ParseInit (type* T)
1491 /* Parse initialization of variables. Return the number of data bytes. */
1493 /* Parse the initialization */
1494 unsigned Size = ParseInitInternal (T, !ANSI);
1496 /* The initialization may not generate code on global level, because code
1497 * outside function scope will never get executed.
1499 if (HaveGlobalCode ()) {
1500 Error ("Non constant initializers");
1501 RemoveGlobalCode ();
1504 /* Return the size needed for the initialization */