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 (TokIsTypeQual (&CurTok)) {
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 Internal ("Unexpected type qualifier token: %d", CurTok.Tok);
114 /* Return the qualifiers read */
120 static void optionalint (void)
121 /* Eat an optional "int" token */
123 if (CurTok.Tok == TOK_INT) {
131 static void optionalsigned (void)
132 /* Eat an optional "signed" token */
134 if (CurTok.Tok == TOK_SIGNED) {
142 static void InitDeclSpec (DeclSpec* D)
143 /* Initialize the DeclSpec struct for use */
152 static void InitDeclaration (Declaration* D)
153 /* Initialize the Declaration struct for use */
162 static void NeedTypeSpace (Declaration* D, unsigned Count)
163 /* Check if there is enough space for Count type specifiers within D */
165 if (D->Index + Count >= MAXTYPELEN) {
166 /* We must call Fatal() here, since calling Error() will try to
167 * continue, and the declaration type is not correctly terminated
168 * in case we come here.
170 Fatal ("Too many type specifiers");
176 static void AddTypeToDeclaration (Declaration* D, type T)
177 /* Add a type specifier to the type of a declaration */
179 NeedTypeSpace (D, 1);
180 D->Type[D->Index++] = T;
185 static void AddEncodeToDeclaration (Declaration* D, type T, unsigned long Val)
186 /* Add a type plus encoding to the type of a declaration */
188 NeedTypeSpace (D, DECODE_SIZE+1);
189 D->Type[D->Index++] = T;
190 Encode (D->Type + D->Index, Val);
191 D->Index += DECODE_SIZE;
196 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
197 /* Parse a storage class */
199 /* Assume we're using an explicit storage class */
200 D->Flags &= ~DS_DEF_STORAGE;
202 /* Check the storage class given */
203 switch (CurTok.Tok) {
206 D->StorageClass = SC_EXTERN | SC_STATIC;
211 D->StorageClass = SC_STATIC;
216 D->StorageClass = SC_REGISTER | SC_STATIC;
221 D->StorageClass = SC_AUTO;
226 D->StorageClass = SC_TYPEDEF;
231 /* No storage class given, use default */
232 D->Flags |= DS_DEF_STORAGE;
233 D->StorageClass = DefStorage;
240 static void ParseEnumDecl (void)
241 /* Process an enum declaration . */
246 /* Accept forward definitions */
247 if (CurTok.Tok != TOK_LCURLY) {
251 /* Skip the opening curly brace */
254 /* Read the enum tags */
256 while (CurTok.Tok != TOK_RCURLY) {
258 /* We expect an identifier */
259 if (CurTok.Tok != TOK_IDENT) {
260 Error ("Identifier expected");
264 /* Remember the identifier and skip it */
265 strcpy (Ident, CurTok.Ident);
268 /* Check for an assigned value */
269 if (CurTok.Tok == TOK_ASSIGN) {
272 ConstAbsIntExpr (hie1, &lval);
276 /* Add an entry to the symbol table */
277 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
279 /* Check for end of definition */
280 if (CurTok.Tok != TOK_COMMA)
289 static SymEntry* ParseStructDecl (const char* Name, type StructType)
290 /* Parse a struct/union declaration. */
301 if (CurTok.Tok != TOK_LCURLY) {
302 /* Just a forward declaration. Try to find a struct with the given
303 * name. If there is none, insert a forward declaration into the
304 * current lexical level.
306 Entry = FindTagSym (Name);
308 Entry = AddStructSym (Name, 0, 0);
309 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
310 /* Already defined in the level but no struct */
311 Error ("Symbol `%s' is already different kind", Name);
316 /* Add a forward declaration for the struct in the current lexical level */
317 Entry = AddStructSym (Name, 0, 0);
319 /* Skip the curly brace */
322 /* Enter a new lexical level for the struct */
325 /* Parse struct fields */
328 while (CurTok.Tok != TOK_RCURLY) {
330 /* Get the type of the entry */
332 InitDeclSpec (&Spec);
333 ParseTypeSpec (&Spec, -1);
335 /* Read fields with this type */
340 /* If we had a flexible array member before, no other fields can
343 if (FlexibleMember) {
344 Error ("Flexible array member must be last field");
345 FlexibleMember = 0; /* Avoid further errors */
348 /* Get type and name of the struct field */
349 ParseDecl (&Spec, &Decl, 0);
351 /* Get the offset of this field */
352 Offs = (StructType == T_STRUCT)? StructSize : 0;
354 /* Calculate the sizes, handle flexible array members */
355 if (StructType == T_STRUCT) {
357 /* It's a struct. Check if this field is a flexible array
358 * member, and calculate the size of the field.
360 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
361 /* Array with unspecified size */
362 if (StructSize == 0) {
363 Error ("Flexible array member cannot be first struct field");
366 /* Assume zero for size calculations */
367 Encode (Decl.Type + 1, FLEXIBLE);
369 StructSize += CheckedSizeOf (Decl.Type);
375 FieldSize = CheckedSizeOf (Decl.Type);
376 if (FieldSize > StructSize) {
377 StructSize = FieldSize;
381 /* Add a field entry to the table */
382 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
384 if (CurTok.Tok != TOK_COMMA) {
392 /* Skip the closing brace */
395 /* Remember the symbol table and leave the struct level */
396 FieldTab = GetSymTab ();
399 /* Make a real entry from the forward decl and return it */
400 return AddStructSym (Name, StructSize, FieldTab);
405 static void ParseTypeSpec (DeclSpec* D, int Default)
406 /* Parse a type specificier */
411 type Qualifiers; /* Type qualifiers */
413 /* Assume we have an explicit type */
414 D->Flags &= ~DS_DEF_TYPE;
416 /* Read type qualifiers if we have any */
417 Qualifiers = OptionalQualifiers (T_QUAL_NONE);
419 /* Look at the data type */
420 switch (CurTok.Tok) {
430 D->Type[0] = GetDefaultChar();
436 if (CurTok.Tok == TOK_UNSIGNED) {
439 D->Type[0] = T_ULONG;
451 if (CurTok.Tok == TOK_UNSIGNED) {
454 D->Type[0] = T_USHORT;
459 D->Type[0] = T_SHORT;
472 switch (CurTok.Tok) {
476 D->Type[0] = T_SCHAR;
483 D->Type[0] = T_SHORT;
507 switch (CurTok.Tok) {
511 D->Type[0] = T_UCHAR;
518 D->Type[0] = T_USHORT;
525 D->Type[0] = T_ULONG;
542 D->Type[0] = T_FLOAT;
548 D->Type[0] = T_DOUBLE;
554 StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
557 if (CurTok.Tok == TOK_IDENT) {
558 strcpy (Ident, CurTok.Ident);
561 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
563 /* Remember we have an extra type decl */
564 D->Flags |= DS_EXTRA_TYPE;
565 /* Declare the struct in the current scope */
566 Entry = ParseStructDecl (Ident, StructType);
567 /* Encode the struct entry into the type */
568 D->Type[0] = StructType;
569 EncodePtr (D->Type+1, Entry);
570 D->Type[DECODE_SIZE+1] = T_END;
575 if (CurTok.Tok != TOK_LCURLY) {
577 if (CurTok.Tok == TOK_IDENT) {
578 /* Find an entry with this name */
579 Entry = FindTagSym (CurTok.Ident);
581 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
582 Error ("Symbol `%s' is already different kind", Entry->Name);
585 /* Insert entry into table ### */
587 /* Skip the identifier */
590 Error ("Identifier expected");
593 /* Remember we have an extra type decl */
594 D->Flags |= DS_EXTRA_TYPE;
595 /* Parse the enum decl */
602 Entry = FindSym (CurTok.Ident);
603 if (Entry && SymIsTypeDef (Entry)) {
606 TypeCpy (D->Type, Entry->Type);
613 Error ("Type expected");
617 D->Flags |= DS_DEF_TYPE;
618 D->Type[0] = (type) Default;
624 /* There may also be qualifiers *after* the initial type */
625 D->Type[0] |= OptionalQualifiers (Qualifiers);
630 static type* ParamTypeCvt (type* T)
631 /* If T is an array, convert it to a pointer else do nothing. Return the
635 if (IsTypeArray (T)) {
644 static void ParseOldStyleParamList (FuncDesc* F)
645 /* Parse an old style (K&R) parameter list */
648 while (CurTok.Tok != TOK_RPAREN) {
650 /* List of identifiers expected */
651 if (CurTok.Tok != TOK_IDENT) {
652 Error ("Identifier expected");
655 /* Create a symbol table entry with type int */
656 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF, 0);
658 /* Count arguments */
661 /* Skip the identifier */
664 /* Check for more parameters */
665 if (CurTok.Tok == TOK_COMMA) {
672 /* Skip right paren. We must explicitly check for one here, since some of
673 * the breaks above bail out without checking.
677 /* An optional list of type specifications follows */
678 while (CurTok.Tok != TOK_LCURLY) {
682 /* Read the declaration specifier */
683 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
685 /* We accept only auto and register as storage class specifiers, but
686 * we ignore all this, since we use auto anyway.
688 if ((Spec.StorageClass & SC_AUTO) == 0 &&
689 (Spec.StorageClass & SC_REGISTER) == 0) {
690 Error ("Illegal storage class");
693 /* Parse a comma separated variable list */
698 /* Read the parameter */
699 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
700 if (Decl.Ident[0] != '\0') {
702 /* We have a name given. Search for the symbol */
703 SymEntry* Sym = FindLocalSym (Decl.Ident);
705 /* Found it, change the default type to the one given */
706 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
708 Error ("Unknown identifier: `%s'", Decl.Ident);
712 if (CurTok.Tok == TOK_COMMA) {
720 /* Variable list must be semicolon terminated */
727 static void ParseAnsiParamList (FuncDesc* F)
728 /* Parse a new style (ANSI) parameter list */
731 while (CurTok.Tok != TOK_RPAREN) {
737 /* Allow an ellipsis as last parameter */
738 if (CurTok.Tok == TOK_ELLIPSIS) {
740 F->Flags |= FD_VARIADIC;
744 /* Read the declaration specifier */
745 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
747 /* We accept only auto and register as storage class specifiers */
748 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
749 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
750 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
751 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
753 Error ("Illegal storage class");
754 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
757 /* Allow parameters without a name, but remember if we had some to
758 * eventually print an error message later.
760 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
761 if (Decl.Ident[0] == '\0') {
763 /* Unnamed symbol. Generate a name that is not user accessible,
764 * then handle the symbol normal.
766 AnonName (Decl.Ident, "param");
767 F->Flags |= FD_UNNAMED_PARAMS;
769 /* Clear defined bit on nonames */
770 Spec.StorageClass &= ~SC_DEF;
773 /* Parse an attribute ### */
774 ParseAttribute (&Decl, &Attr);
776 /* Create a symbol table entry */
777 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Spec.StorageClass, 0);
779 /* Count arguments */
782 /* Check for more parameters */
783 if (CurTok.Tok == TOK_COMMA) {
790 /* Skip right paren. We must explicitly check for one here, since some of
791 * the breaks above bail out without checking.
795 /* Check if this is a function definition */
796 if (CurTok.Tok == TOK_LCURLY) {
797 /* Print an error if in strict ANSI mode and we have unnamed
800 if (ANSI && (F->Flags & FD_UNNAMED_PARAMS) != 0) {
801 Error ("Parameter name omitted");
808 static FuncDesc* ParseFuncDecl (const DeclSpec* Spec)
809 /* Parse the argument list of a function. */
814 /* Create a new function descriptor */
815 FuncDesc* F = NewFuncDesc ();
817 /* Enter a new lexical level */
818 EnterFunctionLevel ();
820 /* Check for several special parameter lists */
821 if (CurTok.Tok == TOK_RPAREN) {
822 /* Parameter list is empty */
823 F->Flags |= (FD_EMPTY | FD_VARIADIC);
824 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
825 /* Parameter list declared as void */
827 F->Flags |= FD_VOID_PARAM;
828 } else if (CurTok.Tok == TOK_IDENT &&
829 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
830 /* If the identifier is a typedef, we have a new style parameter list,
831 * if it's some other identifier, it's an old style parameter list.
833 Sym = FindSym (CurTok.Ident);
834 if (Sym == 0 || !SymIsTypeDef (Sym)) {
835 /* Old style (K&R) function. Assume variable param list. */
836 F->Flags |= (FD_OLDSTYLE | FD_VARIADIC);
840 /* Check for an implicit int return in the function */
841 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
842 Spec->Type[0] == T_INT &&
843 Spec->Type[1] == T_END) {
844 /* Function has an implicit int return */
845 F->Flags |= FD_OLDSTYLE_INTRET;
849 if ((F->Flags & FD_OLDSTYLE) == 0) {
850 /* New style function */
851 ParseAnsiParamList (F);
853 /* Old style function */
854 ParseOldStyleParamList (F);
857 /* Remember the last function parameter. We need it later for several
858 * purposes, for example when passing stuff to fastcall functions. Since
859 * more symbols are added to the table, it is easier if we remember it
860 * now, since it is currently the last entry in the symbol table.
862 F->LastParam = GetSymTab()->SymTail;
864 /* Assign offsets. If the function has a variable parameter list,
865 * there's one additional byte (the arg size).
867 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
870 unsigned Size = CheckedSizeOf (Sym->Type);
871 if (SymIsRegVar (Sym)) {
872 Sym->V.R.SaveOffs = Offs;
877 F->ParamSize += Size;
881 /* Add the default address size for the function */
882 if (CodeAddrSize == ADDR_SIZE_FAR) {
888 /* Leave the lexical level remembering the symbol tables */
889 RememberFunctionLevel (F);
891 /* Return the function descriptor */
897 static unsigned FunctionModifierFlags (void)
898 /* Parse __fastcall__, __near__ and __far__ and return the matching FD_ flags */
901 unsigned Flags = FD_NONE;
902 while (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
904 /* Get the flag bit for the next token */
905 unsigned F = FD_NONE;
906 switch (CurTok.Tok) {
907 case TOK_FASTCALL: F = FD_FASTCALL; break;
908 case TOK_NEAR: F = FD_NEAR; break;
909 case TOK_FAR: F = FD_FAR; break;
910 default: Internal ("Unexpected token: %d", CurTok.Tok);
913 /* Remember the flag for this modifier */
915 Error ("Duplicate modifier");
924 if ((Flags & (FD_NEAR | FD_FAR)) == (FD_NEAR | FD_FAR)) {
925 Error ("Cannot specify both, `__near__' and `__far__' modifiers");
926 Flags &= ~(FD_NEAR | FD_FAR);
929 /* Return the flags read */
935 static void ApplyFunctionModifiers (type* T, unsigned Flags)
936 /* Apply a set of function modifier flags to a function */
938 /* Get the function descriptor */
939 FuncDesc* F = GetFuncDesc (T);
941 /* Special check for __fastcall__ */
942 if ((Flags & FD_FASTCALL) != 0 && IsVariadicFunc (T)) {
943 Error ("Cannot apply `__fastcall__' to functions with "
944 "variable parameter list");
945 Flags &= ~FD_FASTCALL;
948 /* Remove the default function address size modifiers */
949 F->Flags &= ~(FD_NEAR | FD_FAR);
951 /* Add the new modifers */
957 static void Decl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
958 /* Recursively process declarators. Build a type array in reverse order. */
960 /* Pointer to something */
961 if (CurTok.Tok == TOK_STAR) {
968 /* Allow optional const or volatile qualifiers */
969 T = T_PTR | OptionalQualifiers (T_QUAL_NONE);
971 /* Parse the type, the pointer points to */
972 Decl (Spec, D, Mode);
975 AddTypeToDeclaration (D, T);
979 /* Function modifiers */
980 if (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
982 /* Remember the current type pointer */
983 type* T = D->Type + D->Index;
986 unsigned Flags = FunctionModifierFlags ();
988 /* Parse the function */
989 Decl (Spec, D, Mode);
991 /* Check that we have a function */
992 if (!IsTypeFunc (T) && !IsTypeFuncPtr (T)) {
993 Error ("Function modifier applied to non function");
995 ApplyFunctionModifiers (T, Flags);
1002 if (CurTok.Tok == TOK_LPAREN) {
1004 Decl (Spec, D, Mode);
1007 /* Things depend on Mode now:
1008 * - Mode == DM_NEED_IDENT means:
1009 * we *must* have a type and a variable identifer.
1010 * - Mode == DM_NO_IDENT means:
1011 * we must have a type but no variable identifer
1012 * (if there is one, it's not read).
1013 * - Mode == DM_ACCEPT_IDENT means:
1014 * we *may* have an identifier. If there is an identifier,
1015 * it is read, but it is no error, if there is none.
1017 if (Mode == DM_NO_IDENT) {
1019 } else if (CurTok.Tok == TOK_IDENT) {
1020 strcpy (D->Ident, CurTok.Ident);
1023 if (Mode == DM_NEED_IDENT) {
1024 Error ("Identifier expected");
1030 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1031 if (CurTok.Tok == TOK_LPAREN) {
1033 /* Function declaration */
1037 /* Parse the function declaration */
1038 F = ParseFuncDecl (Spec);
1040 /* Add the function type. Be sure to bounds check the type buffer */
1041 AddEncodeToDeclaration (D, T_FUNC, (unsigned long) F);
1043 /* Array declaration */
1044 long Size = UNSPECIFIED;
1046 /* Read the size if it is given */
1047 if (CurTok.Tok != TOK_RBRACK) {
1049 ConstAbsIntExpr (hie1, &lval);
1050 if (lval.Val <= 0) {
1051 if (D->Ident[0] != '\0') {
1052 Error ("Size of array `%s' is invalid", D->Ident);
1054 Error ("Size of array is invalid");
1063 AddEncodeToDeclaration (D, T_ARRAY, Size);
1070 /*****************************************************************************/
1072 /*****************************************************************************/
1076 type* ParseType (type* Type)
1077 /* Parse a complete type specification */
1082 /* Get a type without a default */
1083 InitDeclSpec (&Spec);
1084 ParseTypeSpec (&Spec, -1);
1086 /* Parse additional declarators */
1087 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1089 /* Copy the type to the target buffer */
1090 TypeCpy (Type, Decl.Type);
1092 /* Return a pointer to the target buffer */
1098 void ParseDecl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
1099 /* Parse a variable, type or function declaration */
1101 /* Initialize the Declaration struct */
1102 InitDeclaration (D);
1104 /* Get additional declarators and the identifier */
1105 Decl (Spec, D, Mode);
1107 /* Add the base type. */
1108 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1109 TypeCpy (D->Type + D->Index, Spec->Type);
1111 /* Check the size of the generated type */
1112 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type) && SizeOf (D->Type) >= 0x10000) {
1113 if (D->Ident[0] != '\0') {
1114 Error ("Size of `%s' is invalid", D->Ident);
1116 Error ("Invalid size");
1123 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, int DefType)
1124 /* Parse a declaration specification */
1126 /* Initialize the DeclSpec struct */
1129 /* First, get the storage class specifier for this declaration */
1130 ParseStorageClass (D, DefStorage);
1132 /* Parse the type specifiers */
1133 ParseTypeSpec (D, DefType);
1138 void CheckEmptyDecl (const DeclSpec* D)
1139 /* Called after an empty type declaration (that is, a type declaration without
1140 * a variable). Checks if the declaration does really make sense and issues a
1144 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1145 Warning ("Useless declaration");
1151 static void SkipInitializer (unsigned BracesExpected)
1152 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1153 * smart so we don't have too many following errors.
1156 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1157 switch (CurTok.Tok) {
1158 case TOK_RCURLY: --BracesExpected; break;
1159 case TOK_LCURLY: ++BracesExpected; break;
1168 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1169 /* Accept any number of opening curly braces around an initialization, skip
1170 * them and return the number. If the number of curly braces is less than
1171 * BracesNeeded, issue a warning.
1174 unsigned BraceCount = 0;
1175 while (CurTok.Tok == TOK_LCURLY) {
1179 if (BraceCount < BracesNeeded) {
1180 Error ("`{' expected");
1187 static void ClosingCurlyBraces (unsigned BracesExpected)
1188 /* Accept and skip the given number of closing curly braces together with
1189 * an optional comma. Output an error messages, if the input does not contain
1190 * the expected number of braces.
1193 while (BracesExpected) {
1194 if (CurTok.Tok == TOK_RCURLY) {
1196 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1200 Error ("`}' expected");
1209 static unsigned ParseScalarInit (type* T)
1210 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1214 /* Optional opening brace */
1215 unsigned BraceCount = OpeningCurlyBraces (0);
1217 /* We warn if an initializer for a scalar contains braces, because this is
1218 * quite unusual and often a sign for some problem in the input.
1220 if (BraceCount > 0) {
1221 Warning ("Braces around scalar initializer");
1224 /* Get the expression and convert it to the target type */
1225 ConstExpr (hie1, &ED);
1226 TypeConversion (&ED, T);
1228 /* Output the data */
1231 /* Close eventually opening braces */
1232 ClosingCurlyBraces (BraceCount);
1240 static unsigned ParsePointerInit (type* T)
1241 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1243 /* Optional opening brace */
1244 unsigned BraceCount = OpeningCurlyBraces (0);
1248 ConstExpr (hie1, &ED);
1249 TypeConversion (&ED, T);
1251 /* Output the data */
1254 /* Close eventually opening braces */
1255 ClosingCurlyBraces (BraceCount);
1263 static unsigned ParseArrayInit (type* T, int AllowFlexibleMembers)
1264 /* Parse initializaton for arrays. Return the number of data bytes. */
1268 /* Get the array data */
1269 type* ElementType = GetElementType (T);
1270 unsigned ElementSize = CheckedSizeOf (ElementType);
1271 long ElementCount = GetElementCount (T);
1273 /* Special handling for a character array initialized by a literal */
1274 if (IsTypeChar (ElementType) && CurTok.Tok == TOK_SCONST) {
1276 /* Char array initialized by string constant */
1277 const char* Str = GetLiteral (CurTok.IVal);
1278 Count = GetLiteralPoolOffs () - CurTok.IVal;
1280 /* Translate into target charset */
1281 TranslateLiteralPool (CurTok.IVal);
1283 /* If the array is one too small for the string literal, omit the
1286 if (ElementCount != UNSPECIFIED &&
1287 ElementCount != FLEXIBLE &&
1288 Count == ElementCount + 1) {
1289 /* Omit the trailing zero */
1293 /* Output the data */
1294 g_defbytes (Str, Count);
1296 /* Remove string from pool */
1297 ResetLiteralPoolOffs (CurTok.IVal);
1305 /* Initialize the array members */
1307 while (CurTok.Tok != TOK_RCURLY) {
1308 /* Flexible array members may not be initialized within
1309 * an array (because the size of each element may differ
1312 ParseInitInternal (ElementType, 0);
1314 if (CurTok.Tok != TOK_COMMA)
1319 /* Closing curly braces */
1324 if (ElementCount == UNSPECIFIED) {
1325 /* Number of elements determined by initializer */
1326 Encode (T + 1, Count);
1327 ElementCount = Count;
1328 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1329 /* In non ANSI mode, allow initialization of flexible array
1332 ElementCount = Count;
1333 } else if (Count < ElementCount) {
1334 g_zerobytes ((ElementCount - Count) * ElementSize);
1335 } else if (Count > ElementCount) {
1336 Error ("Too many initializers");
1338 return ElementCount * ElementSize;
1343 static unsigned ParseStructInit (type* Type, int AllowFlexibleMembers)
1344 /* Parse initialization of a struct or union. Return the number of data bytes. */
1348 unsigned StructSize;
1352 /* Consume the opening curly brace */
1355 /* Get a pointer to the struct entry from the type */
1356 Entry = DecodePtr (Type + 1);
1358 /* Get the size of the struct from the symbol table entry */
1359 StructSize = Entry->V.S.Size;
1361 /* Check if this struct definition has a field table. If it doesn't, it
1362 * is an incomplete definition.
1364 Tab = Entry->V.S.SymTab;
1366 Error ("Cannot initialize variables with incomplete type");
1367 /* Try error recovery */
1368 SkipInitializer (1);
1369 /* Nothing initialized */
1373 /* Get a pointer to the list of symbols */
1374 Entry = Tab->SymHead;
1376 /* Initialize fields */
1378 while (CurTok.Tok != TOK_RCURLY) {
1380 Error ("Too many initializers");
1381 SkipInitializer (1);
1384 /* Parse initialization of one field. Flexible array members may
1385 * only be initialized if they are the last field (or part of the
1386 * last struct field).
1388 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1389 Entry = Entry->NextSym;
1390 if (CurTok.Tok != TOK_COMMA)
1395 /* Consume the closing curly brace */
1398 /* If there are struct fields left, reserve additional storage */
1399 if (Size < StructSize) {
1400 g_zerobytes (StructSize - Size);
1404 /* Return the actual number of bytes initialized. This number may be
1405 * larger than StructSize if flexible array members are present and were
1406 * initialized (possible in non ANSI mode).
1413 static unsigned ParseVoidInit (void)
1414 /* Parse an initialization of a void variable (special cc65 extension).
1415 * Return the number of bytes initialized.
1424 /* Allow an arbitrary list of values */
1427 ConstExpr (hie1, &Expr);
1428 switch (UnqualifiedType (Expr.Type[0])) {
1432 if (ED_IsConstAbsInt (&Expr)) {
1433 /* Make it byte sized */
1437 Size += SIZEOF_CHAR;
1446 if (ED_IsConstAbsInt (&Expr)) {
1447 /* Make it word sized */
1456 if (ED_IsConstAbsInt (&Expr)) {
1457 /* Make it dword sized */
1458 Expr.Val &= 0xFFFFFFFF;
1461 Size += SIZEOF_LONG;
1465 Error ("Illegal type in initialization");
1470 if (CurTok.Tok != TOK_COMMA) {
1475 } while (CurTok.Tok != TOK_RCURLY);
1480 /* Return the number of bytes initialized */
1486 static unsigned ParseInitInternal (type* T, int AllowFlexibleMembers)
1487 /* Parse initialization of variables. Return the number of data bytes. */
1489 switch (UnqualifiedType (*T)) {
1499 return ParseScalarInit (T);
1502 return ParsePointerInit (T);
1505 return ParseArrayInit (T, AllowFlexibleMembers);
1509 return ParseStructInit (T, AllowFlexibleMembers);
1513 /* Special cc65 extension in non ANSI mode */
1514 return ParseVoidInit ();
1519 Error ("Illegal type");
1527 unsigned ParseInit (type* T)
1528 /* Parse initialization of variables. Return the number of data bytes. */
1530 /* Parse the initialization */
1531 unsigned Size = ParseInitInternal (T, !ANSI);
1533 /* The initialization may not generate code on global level, because code
1534 * outside function scope will never get executed.
1536 if (HaveGlobalCode ()) {
1537 Error ("Non constant initializers");
1538 RemoveGlobalCode ();
1541 /* Return the size needed for the initialization */