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 /*****************************************************************************/
65 /*****************************************************************************/
67 /*****************************************************************************/
71 static void ParseTypeSpec (DeclSpec* D, int Default);
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 type OptionalQualifiers (type 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 Internal ("Unexpected type qualifier token: %d", CurTok.Tok);
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 NeedTypeSpace (Declaration* D, unsigned Count)
164 /* Check if there is enough space for Count type specifiers within D */
166 if (D->Index + Count >= MAXTYPELEN) {
167 /* We must call Fatal() here, since calling Error() will try to
168 * continue, and the declaration type is not correctly terminated
169 * in case we come here.
171 Fatal ("Too many type specifiers");
177 static void AddTypeToDeclaration (Declaration* D, type T)
178 /* Add a type specifier to the type of a declaration */
180 NeedTypeSpace (D, 1);
181 D->Type[D->Index++] = T;
186 static void AddEncodeToDeclaration (Declaration* D, type T, unsigned long Val)
187 /* Add a type plus encoding to the type of a declaration */
189 NeedTypeSpace (D, DECODE_SIZE+1);
190 D->Type[D->Index++] = T;
191 Encode (D->Type + D->Index, Val);
192 D->Index += DECODE_SIZE;
197 static void ParseStorageClass (DeclSpec* D, unsigned DefStorage)
198 /* Parse a storage class */
200 /* Assume we're using an explicit storage class */
201 D->Flags &= ~DS_DEF_STORAGE;
203 /* Check the storage class given */
204 switch (CurTok.Tok) {
207 D->StorageClass = SC_EXTERN | SC_STATIC;
212 D->StorageClass = SC_STATIC;
217 D->StorageClass = SC_REGISTER | SC_STATIC;
222 D->StorageClass = SC_AUTO;
227 D->StorageClass = SC_TYPEDEF;
232 /* No storage class given, use default */
233 D->Flags |= DS_DEF_STORAGE;
234 D->StorageClass = DefStorage;
241 static void ParseEnumDecl (void)
242 /* Process an enum declaration . */
247 /* Accept forward definitions */
248 if (CurTok.Tok != TOK_LCURLY) {
252 /* Skip the opening curly brace */
255 /* Read the enum tags */
257 while (CurTok.Tok != TOK_RCURLY) {
259 /* We expect an identifier */
260 if (CurTok.Tok != TOK_IDENT) {
261 Error ("Identifier expected");
265 /* Remember the identifier and skip it */
266 strcpy (Ident, CurTok.Ident);
269 /* Check for an assigned value */
270 if (CurTok.Tok == TOK_ASSIGN) {
273 ConstAbsIntExpr (hie1, &Expr);
277 /* Add an entry to the symbol table */
278 AddConstSym (Ident, type_int, SC_ENUM, EnumVal++);
280 /* Check for end of definition */
281 if (CurTok.Tok != TOK_COMMA)
290 static SymEntry* ParseStructDecl (const char* Name, type StructType)
291 /* Parse a struct/union declaration. */
302 if (CurTok.Tok != TOK_LCURLY) {
303 /* Just a forward declaration. Try to find a struct with the given
304 * name. If there is none, insert a forward declaration into the
305 * current lexical level.
307 Entry = FindTagSym (Name);
309 Entry = AddStructSym (Name, 0, 0);
310 } else if (SymIsLocal (Entry) && (Entry->Flags & SC_STRUCT) == 0) {
311 /* Already defined in the level but no struct */
312 Error ("Symbol `%s' is already different kind", Name);
317 /* Add a forward declaration for the struct in the current lexical level */
318 Entry = AddStructSym (Name, 0, 0);
320 /* Skip the curly brace */
323 /* Enter a new lexical level for the struct */
326 /* Parse struct fields */
329 while (CurTok.Tok != TOK_RCURLY) {
331 /* Get the type of the entry */
333 InitDeclSpec (&Spec);
334 ParseTypeSpec (&Spec, -1);
336 /* Read fields with this type */
341 /* If we had a flexible array member before, no other fields can
344 if (FlexibleMember) {
345 Error ("Flexible array member must be last field");
346 FlexibleMember = 0; /* Avoid further errors */
349 /* Get type and name of the struct field */
350 ParseDecl (&Spec, &Decl, 0);
352 /* Get the offset of this field */
353 Offs = (StructType == T_STRUCT)? StructSize : 0;
355 /* Calculate the sizes, handle flexible array members */
356 if (StructType == T_STRUCT) {
358 /* It's a struct. Check if this field is a flexible array
359 * member, and calculate the size of the field.
361 if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) {
362 /* Array with unspecified size */
363 if (StructSize == 0) {
364 Error ("Flexible array member cannot be first struct field");
367 /* Assume zero for size calculations */
368 Encode (Decl.Type + 1, FLEXIBLE);
370 StructSize += CheckedSizeOf (Decl.Type);
376 FieldSize = CheckedSizeOf (Decl.Type);
377 if (FieldSize > StructSize) {
378 StructSize = FieldSize;
382 /* Add a field entry to the table */
383 AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, Offs);
385 if (CurTok.Tok != TOK_COMMA) {
393 /* Skip the closing brace */
396 /* Remember the symbol table and leave the struct level */
397 FieldTab = GetSymTab ();
400 /* Make a real entry from the forward decl and return it */
401 return AddStructSym (Name, StructSize, FieldTab);
406 static void ParseTypeSpec (DeclSpec* D, int Default)
407 /* Parse a type specificier */
412 type Qualifiers; /* Type qualifiers */
414 /* Assume we have an explicit type */
415 D->Flags &= ~DS_DEF_TYPE;
417 /* Read type qualifiers if we have any */
418 Qualifiers = OptionalQualifiers (T_QUAL_NONE);
420 /* Look at the data type */
421 switch (CurTok.Tok) {
431 D->Type[0] = GetDefaultChar();
437 if (CurTok.Tok == TOK_UNSIGNED) {
440 D->Type[0] = T_ULONG;
452 if (CurTok.Tok == TOK_UNSIGNED) {
455 D->Type[0] = T_USHORT;
460 D->Type[0] = T_SHORT;
473 switch (CurTok.Tok) {
477 D->Type[0] = T_SCHAR;
484 D->Type[0] = T_SHORT;
508 switch (CurTok.Tok) {
512 D->Type[0] = T_UCHAR;
519 D->Type[0] = T_USHORT;
526 D->Type[0] = T_ULONG;
543 D->Type[0] = T_FLOAT;
549 D->Type[0] = T_DOUBLE;
555 StructType = (CurTok.Tok == TOK_STRUCT)? T_STRUCT : T_UNION;
558 if (CurTok.Tok == TOK_IDENT) {
559 strcpy (Ident, CurTok.Ident);
562 AnonName (Ident, (StructType == T_STRUCT)? "struct" : "union");
564 /* Remember we have an extra type decl */
565 D->Flags |= DS_EXTRA_TYPE;
566 /* Declare the struct in the current scope */
567 Entry = ParseStructDecl (Ident, StructType);
568 /* Encode the struct entry into the type */
569 D->Type[0] = StructType;
570 EncodePtr (D->Type+1, Entry);
571 D->Type[DECODE_SIZE+1] = T_END;
576 if (CurTok.Tok != TOK_LCURLY) {
578 if (CurTok.Tok == TOK_IDENT) {
579 /* Find an entry with this name */
580 Entry = FindTagSym (CurTok.Ident);
582 if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) {
583 Error ("Symbol `%s' is already different kind", Entry->Name);
586 /* Insert entry into table ### */
588 /* Skip the identifier */
591 Error ("Identifier expected");
594 /* Remember we have an extra type decl */
595 D->Flags |= DS_EXTRA_TYPE;
596 /* Parse the enum decl */
603 Entry = FindSym (CurTok.Ident);
604 if (Entry && SymIsTypeDef (Entry)) {
607 TypeCpy (D->Type, Entry->Type);
614 Error ("Type expected");
618 D->Flags |= DS_DEF_TYPE;
619 D->Type[0] = (type) Default;
625 /* There may also be qualifiers *after* the initial type */
626 D->Type[0] |= OptionalQualifiers (Qualifiers);
631 static type* ParamTypeCvt (type* T)
632 /* If T is an array, convert it to a pointer else do nothing. Return the
636 if (IsTypeArray (T)) {
645 static void ParseOldStyleParamList (FuncDesc* F)
646 /* Parse an old style (K&R) parameter list */
649 while (CurTok.Tok != TOK_RPAREN) {
651 /* List of identifiers expected */
652 if (CurTok.Tok != TOK_IDENT) {
653 Error ("Identifier expected");
656 /* Create a symbol table entry with type int */
657 AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF, 0);
659 /* Count arguments */
662 /* Skip the identifier */
665 /* Check for more parameters */
666 if (CurTok.Tok == TOK_COMMA) {
673 /* Skip right paren. We must explicitly check for one here, since some of
674 * the breaks above bail out without checking.
678 /* An optional list of type specifications follows */
679 while (CurTok.Tok != TOK_LCURLY) {
683 /* Read the declaration specifier */
684 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
686 /* We accept only auto and register as storage class specifiers, but
687 * we ignore all this, since we use auto anyway.
689 if ((Spec.StorageClass & SC_AUTO) == 0 &&
690 (Spec.StorageClass & SC_REGISTER) == 0) {
691 Error ("Illegal storage class");
694 /* Parse a comma separated variable list */
699 /* Read the parameter */
700 ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
701 if (Decl.Ident[0] != '\0') {
703 /* We have a name given. Search for the symbol */
704 SymEntry* Sym = FindLocalSym (Decl.Ident);
706 /* Found it, change the default type to the one given */
707 ChangeSymType (Sym, ParamTypeCvt (Decl.Type));
709 Error ("Unknown identifier: `%s'", Decl.Ident);
713 if (CurTok.Tok == TOK_COMMA) {
721 /* Variable list must be semicolon terminated */
728 static void ParseAnsiParamList (FuncDesc* F)
729 /* Parse a new style (ANSI) parameter list */
732 while (CurTok.Tok != TOK_RPAREN) {
738 /* Allow an ellipsis as last parameter */
739 if (CurTok.Tok == TOK_ELLIPSIS) {
741 F->Flags |= FD_VARIADIC;
745 /* Read the declaration specifier */
746 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
748 /* We accept only auto and register as storage class specifiers */
749 if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) {
750 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
751 } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) {
752 Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF;
754 Error ("Illegal storage class");
755 Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF;
758 /* Allow parameters without a name, but remember if we had some to
759 * eventually print an error message later.
761 ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT);
762 if (Decl.Ident[0] == '\0') {
764 /* Unnamed symbol. Generate a name that is not user accessible,
765 * then handle the symbol normal.
767 AnonName (Decl.Ident, "param");
768 F->Flags |= FD_UNNAMED_PARAMS;
770 /* Clear defined bit on nonames */
771 Spec.StorageClass &= ~SC_DEF;
774 /* Parse an attribute ### */
775 ParseAttribute (&Decl, &Attr);
777 /* Create a symbol table entry */
778 AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Spec.StorageClass, 0);
780 /* Count arguments */
783 /* Check for more parameters */
784 if (CurTok.Tok == TOK_COMMA) {
791 /* Skip right paren. We must explicitly check for one here, since some of
792 * the breaks above bail out without checking.
796 /* Check if this is a function definition */
797 if (CurTok.Tok == TOK_LCURLY) {
798 /* Print an error if we have unnamed parameters and cc65 extensions
801 if (IS_Get (&Standard) != STD_CC65 &&
802 (F->Flags & FD_UNNAMED_PARAMS) != 0) {
803 Error ("Parameter name omitted");
810 static FuncDesc* ParseFuncDecl (const DeclSpec* Spec)
811 /* Parse the argument list of a function. */
816 /* Create a new function descriptor */
817 FuncDesc* F = NewFuncDesc ();
819 /* Enter a new lexical level */
820 EnterFunctionLevel ();
822 /* Check for several special parameter lists */
823 if (CurTok.Tok == TOK_RPAREN) {
824 /* Parameter list is empty */
825 F->Flags |= (FD_EMPTY | FD_VARIADIC);
826 } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) {
827 /* Parameter list declared as void */
829 F->Flags |= FD_VOID_PARAM;
830 } else if (CurTok.Tok == TOK_IDENT &&
831 (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) {
832 /* If the identifier is a typedef, we have a new style parameter list,
833 * if it's some other identifier, it's an old style parameter list.
835 Sym = FindSym (CurTok.Ident);
836 if (Sym == 0 || !SymIsTypeDef (Sym)) {
837 /* Old style (K&R) function. Assume variable param list. */
838 F->Flags |= (FD_OLDSTYLE | FD_VARIADIC);
842 /* Check for an implicit int return in the function */
843 if ((Spec->Flags & DS_DEF_TYPE) != 0 &&
844 Spec->Type[0] == T_INT &&
845 Spec->Type[1] == T_END) {
846 /* Function has an implicit int return */
847 F->Flags |= FD_OLDSTYLE_INTRET;
851 if ((F->Flags & FD_OLDSTYLE) == 0) {
852 /* New style function */
853 ParseAnsiParamList (F);
855 /* Old style function */
856 ParseOldStyleParamList (F);
859 /* Remember the last function parameter. We need it later for several
860 * purposes, for example when passing stuff to fastcall functions. Since
861 * more symbols are added to the table, it is easier if we remember it
862 * now, since it is currently the last entry in the symbol table.
864 F->LastParam = GetSymTab()->SymTail;
866 /* Assign offsets. If the function has a variable parameter list,
867 * there's one additional byte (the arg size).
869 Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
872 unsigned Size = CheckedSizeOf (Sym->Type);
873 if (SymIsRegVar (Sym)) {
874 Sym->V.R.SaveOffs = Offs;
879 F->ParamSize += Size;
883 /* Add the default address size for the function */
884 if (CodeAddrSize == ADDR_SIZE_FAR) {
890 /* Leave the lexical level remembering the symbol tables */
891 RememberFunctionLevel (F);
893 /* Return the function descriptor */
899 static unsigned FunctionModifierFlags (void)
900 /* Parse __fastcall__, __near__ and __far__ and return the matching FD_ flags */
903 unsigned Flags = FD_NONE;
904 while (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
906 /* Get the flag bit for the next token */
907 unsigned F = FD_NONE;
908 switch (CurTok.Tok) {
909 case TOK_FASTCALL: F = FD_FASTCALL; break;
910 case TOK_NEAR: F = FD_NEAR; break;
911 case TOK_FAR: F = FD_FAR; break;
912 default: Internal ("Unexpected token: %d", CurTok.Tok);
915 /* Remember the flag for this modifier */
917 Error ("Duplicate modifier");
926 if ((Flags & (FD_NEAR | FD_FAR)) == (FD_NEAR | FD_FAR)) {
927 Error ("Cannot specify both, `__near__' and `__far__' modifiers");
928 Flags &= ~(FD_NEAR | FD_FAR);
931 /* Return the flags read */
937 static void ApplyFunctionModifiers (type* T, unsigned Flags)
938 /* Apply a set of function modifier flags to a function */
940 /* Get the function descriptor */
941 FuncDesc* F = GetFuncDesc (T);
943 /* Special check for __fastcall__ */
944 if ((Flags & FD_FASTCALL) != 0 && IsVariadicFunc (T)) {
945 Error ("Cannot apply `__fastcall__' to functions with "
946 "variable parameter list");
947 Flags &= ~FD_FASTCALL;
950 /* Remove the default function address size modifiers */
951 F->Flags &= ~(FD_NEAR | FD_FAR);
953 /* Add the new modifers */
959 static void Decl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
960 /* Recursively process declarators. Build a type array in reverse order. */
962 /* Pointer to something */
963 if (CurTok.Tok == TOK_STAR) {
970 /* Allow optional const or volatile qualifiers */
971 T = T_PTR | OptionalQualifiers (T_QUAL_NONE);
973 /* Parse the type, the pointer points to */
974 Decl (Spec, D, Mode);
977 AddTypeToDeclaration (D, T);
981 /* Function modifiers */
982 if (CurTok.Tok == TOK_FASTCALL || CurTok.Tok == TOK_NEAR || CurTok.Tok == TOK_FAR) {
984 /* Remember the current type pointer */
985 type* T = D->Type + D->Index;
988 unsigned Flags = FunctionModifierFlags ();
990 /* Parse the function */
991 Decl (Spec, D, Mode);
993 /* Check that we have a function */
994 if (!IsTypeFunc (T) && !IsTypeFuncPtr (T)) {
995 Error ("Function modifier applied to non function");
997 ApplyFunctionModifiers (T, Flags);
1004 if (CurTok.Tok == TOK_LPAREN) {
1006 Decl (Spec, D, Mode);
1009 /* Things depend on Mode now:
1010 * - Mode == DM_NEED_IDENT means:
1011 * we *must* have a type and a variable identifer.
1012 * - Mode == DM_NO_IDENT means:
1013 * we must have a type but no variable identifer
1014 * (if there is one, it's not read).
1015 * - Mode == DM_ACCEPT_IDENT means:
1016 * we *may* have an identifier. If there is an identifier,
1017 * it is read, but it is no error, if there is none.
1019 if (Mode == DM_NO_IDENT) {
1021 } else if (CurTok.Tok == TOK_IDENT) {
1022 strcpy (D->Ident, CurTok.Ident);
1025 if (Mode == DM_NEED_IDENT) {
1026 Error ("Identifier expected");
1032 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) {
1033 if (CurTok.Tok == TOK_LPAREN) {
1035 /* Function declaration */
1039 /* Parse the function declaration */
1040 F = ParseFuncDecl (Spec);
1042 /* Add the function type. Be sure to bounds check the type buffer */
1043 AddEncodeToDeclaration (D, T_FUNC, (unsigned long) F);
1045 /* Array declaration */
1046 long Size = UNSPECIFIED;
1048 /* Read the size if it is given */
1049 if (CurTok.Tok != TOK_RBRACK) {
1051 ConstAbsIntExpr (hie1, &Expr);
1052 if (Expr.IVal <= 0) {
1053 if (D->Ident[0] != '\0') {
1054 Error ("Size of array `%s' is invalid", D->Ident);
1056 Error ("Size of array is invalid");
1065 AddEncodeToDeclaration (D, T_ARRAY, Size);
1072 /*****************************************************************************/
1074 /*****************************************************************************/
1078 type* ParseType (type* Type)
1079 /* Parse a complete type specification */
1084 /* Get a type without a default */
1085 InitDeclSpec (&Spec);
1086 ParseTypeSpec (&Spec, -1);
1088 /* Parse additional declarators */
1089 ParseDecl (&Spec, &Decl, DM_NO_IDENT);
1091 /* Copy the type to the target buffer */
1092 TypeCpy (Type, Decl.Type);
1094 /* Return a pointer to the target buffer */
1100 void ParseDecl (const DeclSpec* Spec, Declaration* D, unsigned Mode)
1101 /* Parse a variable, type or function declaration */
1103 /* Initialize the Declaration struct */
1104 InitDeclaration (D);
1106 /* Get additional declarators and the identifier */
1107 Decl (Spec, D, Mode);
1109 /* Add the base type. */
1110 NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */
1111 TypeCpy (D->Type + D->Index, Spec->Type);
1113 /* Check the size of the generated type */
1114 if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) {
1115 unsigned Size = SizeOf (D->Type);
1116 if (Size >= 0x10000) {
1117 if (D->Ident[0] != '\0') {
1118 Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size);
1120 Error ("Invalid size in declaration (0x%06X)", Size);
1128 void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, int DefType)
1129 /* Parse a declaration specification */
1131 /* Initialize the DeclSpec struct */
1134 /* First, get the storage class specifier for this declaration */
1135 ParseStorageClass (D, DefStorage);
1137 /* Parse the type specifiers */
1138 ParseTypeSpec (D, DefType);
1143 void CheckEmptyDecl (const DeclSpec* D)
1144 /* Called after an empty type declaration (that is, a type declaration without
1145 * a variable). Checks if the declaration does really make sense and issues a
1149 if ((D->Flags & DS_EXTRA_TYPE) == 0) {
1150 Warning ("Useless declaration");
1156 static void SkipInitializer (unsigned BracesExpected)
1157 /* Skip the remainder of an initializer in case of errors. Try to be somewhat
1158 * smart so we don't have too many following errors.
1161 while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) {
1162 switch (CurTok.Tok) {
1163 case TOK_RCURLY: --BracesExpected; break;
1164 case TOK_LCURLY: ++BracesExpected; break;
1173 static unsigned OpeningCurlyBraces (unsigned BracesNeeded)
1174 /* Accept any number of opening curly braces around an initialization, skip
1175 * them and return the number. If the number of curly braces is less than
1176 * BracesNeeded, issue a warning.
1179 unsigned BraceCount = 0;
1180 while (CurTok.Tok == TOK_LCURLY) {
1184 if (BraceCount < BracesNeeded) {
1185 Error ("`{' expected");
1192 static void ClosingCurlyBraces (unsigned BracesExpected)
1193 /* Accept and skip the given number of closing curly braces together with
1194 * an optional comma. Output an error messages, if the input does not contain
1195 * the expected number of braces.
1198 while (BracesExpected) {
1199 if (CurTok.Tok == TOK_RCURLY) {
1201 } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) {
1205 Error ("`}' expected");
1214 static unsigned ParseScalarInit (type* T)
1215 /* Parse initializaton for scalar data types. Return the number of data bytes. */
1219 /* Optional opening brace */
1220 unsigned BraceCount = OpeningCurlyBraces (0);
1222 /* We warn if an initializer for a scalar contains braces, because this is
1223 * quite unusual and often a sign for some problem in the input.
1225 if (BraceCount > 0) {
1226 Warning ("Braces around scalar initializer");
1229 /* Get the expression and convert it to the target type */
1230 ConstExpr (hie1, &ED);
1231 TypeConversion (&ED, T);
1233 /* Output the data */
1236 /* Close eventually opening braces */
1237 ClosingCurlyBraces (BraceCount);
1245 static unsigned ParsePointerInit (type* T)
1246 /* Parse initializaton for pointer data types. Return the number of data bytes. */
1248 /* Optional opening brace */
1249 unsigned BraceCount = OpeningCurlyBraces (0);
1253 ConstExpr (hie1, &ED);
1254 TypeConversion (&ED, T);
1256 /* Output the data */
1259 /* Close eventually opening braces */
1260 ClosingCurlyBraces (BraceCount);
1268 static unsigned ParseArrayInit (type* T, int AllowFlexibleMembers)
1269 /* Parse initializaton for arrays. Return the number of data bytes. */
1273 /* Get the array data */
1274 type* ElementType = GetElementType (T);
1275 unsigned ElementSize = CheckedSizeOf (ElementType);
1276 long ElementCount = GetElementCount (T);
1278 /* Special handling for a character array initialized by a literal */
1279 if (IsTypeChar (ElementType) && CurTok.Tok == TOK_SCONST) {
1281 /* Char array initialized by string constant */
1282 const char* Str = GetLiteral (CurTok.IVal);
1283 Count = GetLiteralPoolOffs () - CurTok.IVal;
1285 /* Translate into target charset */
1286 TranslateLiteralPool (CurTok.IVal);
1288 /* If the array is one too small for the string literal, omit the
1291 if (ElementCount != UNSPECIFIED &&
1292 ElementCount != FLEXIBLE &&
1293 Count == ElementCount + 1) {
1294 /* Omit the trailing zero */
1298 /* Output the data */
1299 g_defbytes (Str, Count);
1301 /* Remove string from pool */
1302 ResetLiteralPoolOffs (CurTok.IVal);
1310 /* Initialize the array members */
1312 while (CurTok.Tok != TOK_RCURLY) {
1313 /* Flexible array members may not be initialized within
1314 * an array (because the size of each element may differ
1317 ParseInitInternal (ElementType, 0);
1319 if (CurTok.Tok != TOK_COMMA)
1324 /* Closing curly braces */
1329 if (ElementCount == UNSPECIFIED) {
1330 /* Number of elements determined by initializer */
1331 Encode (T + 1, Count);
1332 ElementCount = Count;
1333 } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) {
1334 /* In non ANSI mode, allow initialization of flexible array
1337 ElementCount = Count;
1338 } else if (Count < ElementCount) {
1339 g_zerobytes ((ElementCount - Count) * ElementSize);
1340 } else if (Count > ElementCount) {
1341 Error ("Too many initializers");
1343 return ElementCount * ElementSize;
1348 static unsigned ParseStructInit (type* Type, int AllowFlexibleMembers)
1349 /* Parse initialization of a struct or union. Return the number of data bytes. */
1353 unsigned StructSize;
1357 /* Consume the opening curly brace */
1360 /* Get a pointer to the struct entry from the type */
1361 Entry = DecodePtr (Type + 1);
1363 /* Get the size of the struct from the symbol table entry */
1364 StructSize = Entry->V.S.Size;
1366 /* Check if this struct definition has a field table. If it doesn't, it
1367 * is an incomplete definition.
1369 Tab = Entry->V.S.SymTab;
1371 Error ("Cannot initialize variables with incomplete type");
1372 /* Try error recovery */
1373 SkipInitializer (1);
1374 /* Nothing initialized */
1378 /* Get a pointer to the list of symbols */
1379 Entry = Tab->SymHead;
1381 /* Initialize fields */
1383 while (CurTok.Tok != TOK_RCURLY) {
1385 Error ("Too many initializers");
1386 SkipInitializer (1);
1389 /* Parse initialization of one field. Flexible array members may
1390 * only be initialized if they are the last field (or part of the
1391 * last struct field).
1393 Size += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0);
1394 Entry = Entry->NextSym;
1395 if (CurTok.Tok != TOK_COMMA)
1400 /* Consume the closing curly brace */
1403 /* If there are struct fields left, reserve additional storage */
1404 if (Size < StructSize) {
1405 g_zerobytes (StructSize - Size);
1409 /* Return the actual number of bytes initialized. This number may be
1410 * larger than StructSize if flexible array members are present and were
1411 * initialized (possible in non ANSI mode).
1418 static unsigned ParseVoidInit (void)
1419 /* Parse an initialization of a void variable (special cc65 extension).
1420 * Return the number of bytes initialized.
1429 /* Allow an arbitrary list of values */
1432 ConstExpr (hie1, &Expr);
1433 switch (UnqualifiedType (Expr.Type[0])) {
1437 if (ED_IsConstAbsInt (&Expr)) {
1438 /* Make it byte sized */
1442 Size += SIZEOF_CHAR;
1451 if (ED_IsConstAbsInt (&Expr)) {
1452 /* Make it word sized */
1453 Expr.IVal &= 0xFFFF;
1461 if (ED_IsConstAbsInt (&Expr)) {
1462 /* Make it dword sized */
1463 Expr.IVal &= 0xFFFFFFFF;
1466 Size += SIZEOF_LONG;
1470 Error ("Illegal type in initialization");
1475 if (CurTok.Tok != TOK_COMMA) {
1480 } while (CurTok.Tok != TOK_RCURLY);
1485 /* Return the number of bytes initialized */
1491 static unsigned ParseInitInternal (type* T, int AllowFlexibleMembers)
1492 /* Parse initialization of variables. Return the number of data bytes. */
1494 switch (UnqualifiedType (*T)) {
1504 return ParseScalarInit (T);
1507 return ParsePointerInit (T);
1510 return ParseArrayInit (T, AllowFlexibleMembers);
1514 return ParseStructInit (T, AllowFlexibleMembers);
1517 if (IS_Get (&Standard) == STD_CC65) {
1518 /* Special cc65 extension in non ANSI mode */
1519 return ParseVoidInit ();
1524 Error ("Illegal type");
1532 unsigned ParseInit (type* T)
1533 /* Parse initialization of variables. Return the number of data bytes. */
1535 /* Parse the initialization. Flexible array members can only be initialized
1538 unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65);
1540 /* The initialization may not generate code on global level, because code
1541 * outside function scope will never get executed.
1543 if (HaveGlobalCode ()) {
1544 Error ("Non constant initializers");
1545 RemoveGlobalCode ();
1548 /* Return the size needed for the initialization */