]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
Inline shifts in g_asl as is already the case in g_scale.
[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) == 0      &&
145                 (Decl.StorageClass & SC_TYPEDEF) == 0   &&
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 */
196                     if (IsQualConst (Decl.Type)) {
197                         g_userodata ();
198                     } else {
199                         g_usedata ();
200                     }
201
202                     /* Define a label */
203                     g_defgloblabel (Entry->Name);
204
205                     /* Skip the '=' */
206                     NextToken ();
207
208                     /* Parse the initialization */
209                     ParseInit (Entry->Type);
210                 } else {
211
212                     if (IsTypeVoid (Decl.Type)) {
213                         /* We cannot declare variables of type void */
214                         Error ("Illegal type for variable `%s'", Decl.Ident);
215                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
216                     } else if (Size == 0) {
217                         /* Size is unknown. Is it an array? */
218                         if (!IsTypeArray (Decl.Type)) {
219                             Error ("Variable `%s' has unknown size", Decl.Ident);
220                         }
221                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
222                     }
223
224                     /* Allocate storage if it is still needed */
225                     if (Entry->Flags & SC_STORAGE) {
226
227                         /* Switch to the BSS segment */
228                         g_usebss ();
229
230                         /* Define a label */
231                         g_defgloblabel (Entry->Name);
232
233                         /* Allocate space for uninitialized variable */
234                         g_res (Size);
235                     }
236                 }
237
238             }
239
240             /* Check for end of declaration list */
241             if (CurTok.Tok == TOK_COMMA) {
242                 NextToken ();
243                 comma = 1;
244             } else {
245                 break;
246             }
247         }
248
249         /* Function declaration? */
250         if (Entry && IsTypeFunc (Entry->Type)) {
251
252             /* Function */
253             if (!comma) {
254                 if (CurTok.Tok == TOK_SEMI) {
255                     /* Prototype only */
256                     NextToken ();
257                 } else {
258
259                     /* Function body. Check for duplicate function definitions */
260                     if (SymIsDef (Entry)) {
261                         Error ("Body for function `%s' has already been defined",
262                                Entry->Name);
263                     }
264
265                     /* Parse the function body */
266                     NewFunc (Entry);
267                 }
268             }
269
270         } else {
271
272             /* Must be followed by a semicolon */
273             ConsumeSemi ();
274
275         }
276     }
277 }
278
279
280
281 void Compile (const char* FileName)
282 /* Top level compile routine. Will setup things and call the parser. */
283 {
284     char        DateStr[32];
285     char        TimeStr[32];
286     time_t      Time;
287     struct tm*  TM;
288
289     /* Since strftime is locale dependent, we need the abbreviated month names
290      * in english.
291      */
292     static const char MonthNames[12][4] = {
293         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
294         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
295     };
296
297     /* Add macros that are always defined */
298     DefineNumericMacro ("__CC65__", VERSION);
299
300     /* Language standard that is supported */
301     DefineNumericMacro ("__CC65_STD_C89__", STD_C89);
302     DefineNumericMacro ("__CC65_STD_C99__", STD_C99);
303     DefineNumericMacro ("__CC65_STD_CC65__", STD_CC65);
304     DefineNumericMacro ("__CC65_STD__", IS_Get (&Standard));
305
306     /* Optimization macros. Since no source code has been parsed for now, the
307      * IS_Get functions access the values in effect now, regardless of any
308      * changes using #pragma later.
309      */
310     if (IS_Get (&Optimize)) {
311         long CodeSize = IS_Get (&CodeSizeFactor);
312         DefineNumericMacro ("__OPT__", 1);
313         if (CodeSize > 100) {
314             DefineNumericMacro ("__OPT_i__", CodeSize);
315         }
316         if (IS_Get (&EnableRegVars)) {
317             DefineNumericMacro ("__OPT_r__", 1);
318         }
319         if (IS_Get (&InlineStdFuncs)) {
320             DefineNumericMacro ("__OPT_s__", 1);
321         }
322     }
323
324     /* __TIME__ and __DATE__ macros */
325     Time = time (0);
326     TM   = localtime (&Time);
327     xsprintf (DateStr, sizeof (DateStr), "\"%s %2d %d\"",
328               MonthNames[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900);
329     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
330     DefineTextMacro ("__DATE__", DateStr);
331     DefineTextMacro ("__TIME__", TimeStr);
332
333     /* Initialize the literal pool */
334     InitLiteralPool ();
335
336     /* Create the base lexical level */
337     EnterGlobalLevel ();
338
339     /* Generate the code generator preamble */
340     g_preamble ();
341
342     /* Open the input file */
343     OpenMainFile (FileName);
344
345     /* Are we supposed to compile or just preprocess the input? */
346     if (PreprocessOnly) {
347
348         /* Open the file */
349         OpenOutputFile ();
350
351         /* Preprocess each line and write it to the output file */
352         while (NextLine ()) {
353             Preprocess ();
354             WriteOutput ("%.*s\n", SB_GetLen (Line), SB_GetConstBuf (Line));
355         }
356
357         /* Close the output file */
358         CloseOutputFile ();
359
360         if (Debug) {
361             PrintMacroStats (stdout);
362         }
363
364     } else {
365
366         /* Ok, start the ball rolling... */
367         Parse ();
368
369         /* Dump the literal pool. */
370         DumpLiteralPool ();
371
372         /* Write imported/exported symbols */
373         EmitExternals ();
374
375         if (Debug) {
376             PrintLiteralPoolStats (stdout);
377             PrintMacroStats (stdout);
378         }
379
380     }
381
382     /* Leave the main lexical level */
383     LeaveGlobalLevel ();
384
385     /* Print an error report */
386     ErrorReport ();
387 }
388
389
390
391