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