]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
Fix wrong check for typedef which caused non allocation of storage for structs
[cc65] / src / cc65 / compile.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 compile.c                                 */
4 /*                                                                           */
5 /*                       Top level compiler subroutine                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2009 Ullrich von Bassewitz                                       */
10 /*               Roemerstrasse 52                                            */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdlib.h>
37 #include <time.h>
38
39 /* common */
40 #include "debugflag.h"
41 #include "version.h"
42 #include "xmalloc.h"
43 #include "xsprintf.h"
44
45 /* cc65 */
46 #include "asmlabel.h"
47 #include "asmstmt.h"
48 #include "codegen.h"
49 #include "compile.h"
50 #include "declare.h"
51 #include "error.h"
52 #include "expr.h"
53 #include "function.h"
54 #include "global.h"
55 #include "input.h"
56 #include "litpool.h"
57 #include "macrotab.h"
58 #include "output.h"
59 #include "pragma.h"
60 #include "preproc.h"
61 #include "standard.h"
62 #include "symtab.h"
63
64
65
66 /*****************************************************************************/
67 /*                                   Code                                    */
68 /*****************************************************************************/
69
70
71
72 static void Parse (void)
73 /* Top level parser routine. */
74 {
75     int comma;
76     SymEntry* Entry;
77
78     /* Go... */
79     NextToken ();
80     NextToken ();
81
82     /* Parse until end of input */
83     while (CurTok.Tok != TOK_CEOF) {
84
85         DeclSpec        Spec;
86         Declaration     Decl;
87
88         /* Check for empty statements */
89         if (CurTok.Tok == TOK_SEMI) {
90             NextToken ();
91             continue;
92         }
93
94         /* Check for an ASM statement (which is allowed also on global level) */
95         if (CurTok.Tok == TOK_ASM) {
96             AsmStatement ();
97             ConsumeSemi ();
98             continue;
99         }
100
101         /* Check for a #pragma */
102         if (CurTok.Tok == TOK_PRAGMA) {
103             DoPragma ();
104             continue;
105         }
106
107         /* Read variable defs and functions */
108         ParseDeclSpec (&Spec, SC_EXTERN | SC_STATIC, T_INT);
109
110         /* Don't accept illegal storage classes */
111         if ((Spec.StorageClass & SC_TYPE) == 0) {
112             if ((Spec.StorageClass & SC_AUTO) != 0 ||
113                 (Spec.StorageClass & SC_REGISTER) != 0) {
114                 Error ("Illegal storage class");
115                 Spec.StorageClass = SC_EXTERN | SC_STATIC;
116             }
117         }
118
119         /* Check if this is only a type declaration */
120         if (CurTok.Tok == TOK_SEMI) {
121             CheckEmptyDecl (&Spec);
122             NextToken ();
123             continue;
124         }
125
126         /* Read declarations for this type */
127         Entry = 0;
128         comma = 0;
129         while (1) {
130
131             /* Read the next declaration */
132             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
133             if (Decl.Ident[0] == '\0') {
134                 NextToken ();
135                 break;
136             }
137
138             /* Check if we must reserve storage for the variable. We do this,
139              * if it is not a typedef or function, if we don't had a storage
140              * class given ("int i") or if the storage class is explicitly
141              * specified as static. This means that "extern int i" will not
142              * get storage allocated.
143              */
144             if ((Decl.StorageClass & SC_FUNC) != SC_FUNC          &&
145                 (Decl.StorageClass & SC_TYPEDEF) != SC_TYPEDEF    &&
146                 ((Spec.Flags & DS_DEF_STORAGE) != 0  ||
147                  (Decl.StorageClass & (SC_STATIC | SC_EXTERN)) == SC_STATIC)) {
148
149                 /* We will allocate storage */
150                 Decl.StorageClass |= SC_STORAGE | SC_DEF;
151             }
152
153             /* If this is a function declarator that is not followed by a comma
154              * or semicolon, it must be followed by a function body. If this is
155              * the case, convert an empty parameter list into one accepting no
156              * parameters (same as void) as required by the standard.
157              */
158             if ((Decl.StorageClass & SC_FUNC) != 0 &&
159                 (CurTok.Tok != TOK_COMMA)          &&
160                 (CurTok.Tok != TOK_SEMI)) {
161
162                 FuncDesc* D = GetFuncDesc (Decl.Type);
163                 if (D->Flags & FD_EMPTY) {
164                     D->Flags = (D->Flags & ~(FD_EMPTY | FD_VARIADIC)) | FD_VOID_PARAM;
165                 }
166             }
167
168             /* Add an entry to the symbol table */
169             Entry = AddGlobalSym (Decl.Ident, Decl.Type, Decl.StorageClass);
170
171             /* Reserve storage for the variable if we need to */
172             if (Decl.StorageClass & SC_STORAGE) {
173
174                 /* Get the size of the variable */
175                 unsigned Size = SizeOf (Decl.Type);
176
177                 /* Allow initialization */
178                 if (CurTok.Tok == TOK_ASSIGN) {
179
180                     /* We cannot initialize types of unknown size, or
181                      * void types in non ANSI mode.
182                      */
183                     if (Size == 0) {
184                         if (!IsTypeVoid (Decl.Type)) {
185                             if (!IsTypeArray (Decl.Type)) {
186                                 /* Size is unknown and not an array */
187                                 Error ("Variable `%s' has unknown size", Decl.Ident);
188                             }
189                         } else if (IS_Get (&Standard) != STD_CC65) {
190                             /* We cannot declare variables of type void */
191                             Error ("Illegal type for variable `%s'", Decl.Ident);
192                         }
193                     }
194
195                     /* Switch to the data or rodata segment. For arrays, check
196                       * the element qualifiers, since not the array but its
197                       * elements are const.
198                       */
199                     if (IsQualConst (Decl.Type) ||
200                         (IsTypeArray (Decl.Type) &&
201                          IsQualConst (GetElementType (Decl.Type)))) {
202                         g_userodata ();
203                     } else {
204                         g_usedata ();
205                     }
206
207                     /* Define a label */
208                     g_defgloblabel (Entry->Name);
209
210                     /* Skip the '=' */
211                     NextToken ();
212
213                     /* Parse the initialization */
214                     ParseInit (Entry->Type);
215                 } else {
216
217                     if (IsTypeVoid (Decl.Type)) {
218                         /* We cannot declare variables of type void */
219                         Error ("Illegal type for variable `%s'", Decl.Ident);
220                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
221                     } else if (Size == 0) {
222                         /* Size is unknown. Is it an array? */
223                         if (!IsTypeArray (Decl.Type)) {
224                             Error ("Variable `%s' has unknown size", Decl.Ident);
225                         }
226                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
227                     }
228
229                     /* Allocate storage if it is still needed */
230                     if (Entry->Flags & SC_STORAGE) {
231
232                         /* Switch to the BSS segment */
233                         g_usebss ();
234
235                         /* Define a label */
236                         g_defgloblabel (Entry->Name);
237
238                         /* Allocate space for uninitialized variable */
239                         g_res (Size);
240                     }
241                 }
242
243             }
244
245             /* Check for end of declaration list */
246             if (CurTok.Tok == TOK_COMMA) {
247                 NextToken ();
248                 comma = 1;
249             } else {
250                 break;
251             }
252         }
253
254         /* Function declaration? */
255         if (Entry && IsTypeFunc (Entry->Type)) {
256
257             /* Function */
258             if (!comma) {
259                 if (CurTok.Tok == TOK_SEMI) {
260                     /* Prototype only */
261                     NextToken ();
262                 } else {
263
264                     /* Function body. Check for duplicate function definitions */
265                     if (SymIsDef (Entry)) {
266                         Error ("Body for function `%s' has already been defined",
267                                Entry->Name);
268                     }
269
270                     /* Parse the function body */
271                     NewFunc (Entry);
272                 }
273             }
274
275         } else {
276
277             /* Must be followed by a semicolon */
278             ConsumeSemi ();
279
280         }
281     }
282 }
283
284
285
286 void Compile (const char* FileName)
287 /* Top level compile routine. Will setup things and call the parser. */
288 {
289     char        DateStr[32];
290     char        TimeStr[32];
291     time_t      Time;
292     struct tm*  TM;
293
294     /* Since strftime is locale dependent, we need the abbreviated month names
295      * in english.
296      */
297     static const char MonthNames[12][4] = {
298         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
299         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
300     };
301
302     /* Add macros that are always defined */
303     DefineNumericMacro ("__CC65__", VERSION);
304
305     /* Language standard that is supported */
306     DefineNumericMacro ("__CC65_STD_C89__", STD_C89);
307     DefineNumericMacro ("__CC65_STD_C99__", STD_C99);
308     DefineNumericMacro ("__CC65_STD_CC65__", STD_CC65);
309     DefineNumericMacro ("__CC65_STD__", IS_Get (&Standard));
310
311     /* Optimization macros. Since no source code has been parsed for now, the
312      * IS_Get functions access the values in effect now, regardless of any
313      * changes using #pragma later.
314      */
315     if (IS_Get (&Optimize)) {
316         long CodeSize = IS_Get (&CodeSizeFactor);
317         DefineNumericMacro ("__OPT__", 1);
318         if (CodeSize > 100) {
319             DefineNumericMacro ("__OPT_i__", CodeSize);
320         }
321         if (IS_Get (&EnableRegVars)) {
322             DefineNumericMacro ("__OPT_r__", 1);
323         }
324         if (IS_Get (&InlineStdFuncs)) {
325             DefineNumericMacro ("__OPT_s__", 1);
326         }
327     }
328
329     /* __TIME__ and __DATE__ macros */
330     Time = time (0);
331     TM   = localtime (&Time);
332     xsprintf (DateStr, sizeof (DateStr), "\"%s %2d %d\"",
333               MonthNames[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900);
334     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
335     DefineTextMacro ("__DATE__", DateStr);
336     DefineTextMacro ("__TIME__", TimeStr);
337
338     /* Initialize the literal pool */
339     InitLiteralPool ();
340
341     /* Create the base lexical level */
342     EnterGlobalLevel ();
343
344     /* Generate the code generator preamble */
345     g_preamble ();
346
347     /* Open the input file */
348     OpenMainFile (FileName);
349
350     /* Are we supposed to compile or just preprocess the input? */
351     if (PreprocessOnly) {
352
353         /* Open the file */
354         OpenOutputFile ();
355
356         /* Preprocess each line and write it to the output file */
357         while (NextLine ()) {
358             Preprocess ();
359             WriteOutput ("%.*s\n", SB_GetLen (Line), SB_GetConstBuf (Line));
360         }
361
362         /* Close the output file */
363         CloseOutputFile ();
364
365         if (Debug) {
366             PrintMacroStats (stdout);
367         }
368
369     } else {
370
371         /* Ok, start the ball rolling... */
372         Parse ();
373
374         /* Dump the literal pool. */
375         DumpLiteralPool ();
376
377         /* Write imported/exported symbols */
378         EmitExternals ();
379
380         if (Debug) {
381             PrintLiteralPoolStats (stdout);
382             PrintMacroStats (stdout);
383         }
384
385     }
386
387     /* Leave the main lexical level */
388     LeaveGlobalLevel ();
389
390     /* Print an error report */
391     ErrorReport ();
392 }
393
394
395
396