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