]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
Fixed problem with last change: Static declaration do also set the SC_EXTERN
[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 "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         /* 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             Declaration         Decl;
132
133             /* Read the next declaration */
134             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
135             if (Decl.Ident[0] == '\0') {
136                 NextToken ();
137                 break;
138             }
139
140             /* Check if we must reserve storage for the variable. We do this,
141              *
142              *   - if it is not a typedef or function,
143              *   - if we don't had a storage class given ("int i")
144              *   - if the storage class is explicitly specified as static,
145              *   - or if there is an initialization.
146              *
147              * This means that "extern int i;" will not get storage allocated.
148              */
149             if ((Decl.StorageClass & SC_FUNC) != SC_FUNC          &&
150                 (Decl.StorageClass & SC_TYPEDEF) != SC_TYPEDEF    &&
151                 ((Spec.Flags & DS_DEF_STORAGE) != 0         ||
152                  (Decl.StorageClass & (SC_EXTERN|SC_STATIC)) == SC_STATIC ||
153                  ((Decl.StorageClass & SC_EXTERN) != 0 &&
154                   CurTok.Tok == TOK_ASSIGN))) {
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 non ANSI mode.
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 (Decl.Type) ||
210                         (IsTypeArray (Decl.Type) &&
211                          IsQualConst (GetElementType (Decl.Type)))) {
212                         g_userodata ();
213                     } else {
214                         g_usedata ();
215                     }
216
217                     /* Define a label */
218                     g_defgloblabel (Entry->Name);
219
220                     /* Skip the '=' */
221                     NextToken ();
222
223                     /* Parse the initialization */
224                     ParseInit (Entry->Type);
225                 } else {
226
227                     if (IsTypeVoid (Decl.Type)) {
228                         /* We cannot declare variables of type void */
229                         Error ("Illegal type for variable `%s'", Decl.Ident);
230                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
231                     } else if (Size == 0) {
232                         /* Size is unknown. Is it an array? */
233                         if (!IsTypeArray (Decl.Type)) {
234                             Error ("Variable `%s' has unknown size", Decl.Ident);
235                         }
236                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
237                     }
238
239                     /* Allocate storage if it is still needed */
240                     if (Entry->Flags & SC_STORAGE) {
241
242                         /* Switch to the BSS segment */
243                         g_usebss ();
244
245                         /* Define a label */
246                         g_defgloblabel (Entry->Name);
247
248                         /* Allocate space for uninitialized variable */
249                         g_res (Size);
250                     }
251                 }
252
253             }
254
255             /* Check for end of declaration list */
256             if (CurTok.Tok == TOK_COMMA) {
257                 NextToken ();
258                 comma = 1;
259             } else {
260                 break;
261             }
262         }
263
264         /* Function declaration? */
265         if (Entry && IsTypeFunc (Entry->Type)) {
266
267             /* Function */
268             if (!comma) {
269                 if (CurTok.Tok == TOK_SEMI) {
270                     /* Prototype only */
271                     NextToken ();
272                 } else {
273
274                     /* Function body. Check for duplicate function definitions */
275                     if (SymIsDef (Entry)) {
276                         Error ("Body for function `%s' has already been defined",
277                                Entry->Name);
278                     }
279
280                     /* Parse the function body */
281                     NewFunc (Entry);
282                 }
283             }
284
285         } else {
286
287             /* Must be followed by a semicolon */
288             ConsumeSemi ();
289
290         }
291     }
292 }
293
294
295
296 void Compile (const char* FileName)
297 /* Top level compile routine. Will setup things and call the parser. */
298 {
299     char        DateStr[32];
300     char        TimeStr[32];
301     time_t      Time;
302     struct tm*  TM;
303
304     /* Since strftime is locale dependent, we need the abbreviated month names
305      * in english.
306      */
307     static const char MonthNames[12][4] = {
308         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
309         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
310     };
311
312     /* Add macros that are always defined */
313     DefineNumericMacro ("__CC65__", GetVersionAsNumber ());
314
315     /* Language standard that is supported */
316     DefineNumericMacro ("__CC65_STD_C89__", STD_C89);
317     DefineNumericMacro ("__CC65_STD_C99__", STD_C99);
318     DefineNumericMacro ("__CC65_STD_CC65__", STD_CC65);
319     DefineNumericMacro ("__CC65_STD__", IS_Get (&Standard));
320
321     /* Optimization macros. Since no source code has been parsed for now, the
322      * IS_Get functions access the values in effect now, regardless of any
323      * changes using #pragma later.
324      */
325     if (IS_Get (&Optimize)) {
326         long CodeSize = IS_Get (&CodeSizeFactor);
327         DefineNumericMacro ("__OPT__", 1);
328         if (CodeSize > 100) {
329             DefineNumericMacro ("__OPT_i__", CodeSize);
330         }
331         if (IS_Get (&EnableRegVars)) {
332             DefineNumericMacro ("__OPT_r__", 1);
333         }
334         if (IS_Get (&InlineStdFuncs)) {
335             DefineNumericMacro ("__OPT_s__", 1);
336         }
337     }
338
339     /* __TIME__ and __DATE__ macros */
340     Time = time (0);
341     TM   = localtime (&Time);
342     xsprintf (DateStr, sizeof (DateStr), "\"%s %2d %d\"",
343               MonthNames[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900);
344     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
345     DefineTextMacro ("__DATE__", DateStr);
346     DefineTextMacro ("__TIME__", TimeStr);
347
348     /* Other standard macros */
349     /* DefineNumericMacro ("__STDC__", 1);      <- not now */
350     DefineNumericMacro ("__STDC_HOSTED__", 1);
351
352     /* Create the base lexical level */
353     EnterGlobalLevel ();
354
355     /* Create the global code and data segments */
356     CreateGlobalSegments ();
357
358     /* Initialize the literal pool */
359     InitLiteralPool ();
360
361     /* Generate the code generator preamble */
362     g_preamble ();
363
364     /* Open the input file */
365     OpenMainFile (FileName);
366
367     /* Are we supposed to compile or just preprocess the input? */
368     if (PreprocessOnly) {
369
370         /* Open the file */
371         OpenOutputFile ();
372
373         /* Preprocess each line and write it to the output file */
374         while (NextLine ()) {
375             Preprocess ();
376             WriteOutput ("%.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line));
377         }
378
379         /* Close the output file */
380         CloseOutputFile ();
381
382     } else {
383
384         /* Ok, start the ball rolling... */
385         Parse ();
386
387     }
388
389     if (Debug) {
390         PrintMacroStats (stdout);
391     }
392
393     /* Print an error report */
394     ErrorReport ();
395 }
396
397
398
399 void FinishCompile (void)
400 /* Emit literals, externals, do cleanup and optimizations */
401 {
402     SymTable* SymTab;
403     SymEntry* Func;
404
405     /* Walk over all functions, doing cleanup, optimizations ... */
406     SymTab = GetGlobalSymTab ();
407     Func   = SymTab->SymHead;
408     while (Func) {
409         if (SymIsOutputFunc (Func)) {
410             /* Function which is defined and referenced or extern */
411             MoveLiteralPool (Func->V.F.LitPool);
412             CS_MergeLabels (Func->V.F.Seg->Code);
413             RunOpt (Func->V.F.Seg->Code);
414         }
415         Func = Func->NextSym;
416     }
417
418     /* Output the literal pool */
419     OutputLiteralPool ();
420
421     /* Write imported/exported symbols */
422     EmitExternals ();
423
424     /* Leave the main lexical level */
425     LeaveGlobalLevel ();
426 }
427
428
429