]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
3dd7bffa43a8e84aff4a73c8c35567ba52eebdb5
[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
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             Declaration         Decl;
131
132             /* Read the next declaration */
133             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
134             if (Decl.Ident[0] == '\0') {
135                 NextToken ();
136                 break;
137             }
138
139             /* Check if we must reserve storage for the variable. We do this,
140              * if it is not a typedef or function, if we don't had a storage
141              * class given ("int i") or if the storage class is explicitly
142              * specified as static. This means that "extern int i" will not
143              * get storage allocated.
144              */
145             if ((Decl.StorageClass & SC_FUNC) != SC_FUNC          &&
146                 (Decl.StorageClass & SC_TYPEDEF) != SC_TYPEDEF    &&
147                 ((Spec.Flags & DS_DEF_STORAGE) != 0  ||
148                  (Decl.StorageClass & (SC_STATIC | SC_EXTERN)) == SC_STATIC)) {
149
150                 /* We will allocate storage */
151                 Decl.StorageClass |= SC_STORAGE | SC_DEF;
152             }
153
154             /* If this is a function declarator that is not followed by a comma
155              * or semicolon, it must be followed by a function body. If this is
156              * the case, convert an empty parameter list into one accepting no
157              * parameters (same as void) as required by the standard.
158              */
159             if ((Decl.StorageClass & SC_FUNC) != 0 &&
160                 (CurTok.Tok != TOK_COMMA)          &&
161                 (CurTok.Tok != TOK_SEMI)) {
162
163                 FuncDesc* D = GetFuncDesc (Decl.Type);
164                 if (D->Flags & FD_EMPTY) {
165                     D->Flags = (D->Flags & ~(FD_EMPTY | FD_VARIADIC)) | FD_VOID_PARAM;
166                 }
167             }
168
169             /* Add an entry to the symbol table */
170             Entry = AddGlobalSym (Decl.Ident, Decl.Type, Decl.StorageClass);
171
172             /* Add declaration attributes */
173             SymUseAttr (Entry, &Decl);
174
175             /* Reserve storage for the variable if we need to */
176             if (Decl.StorageClass & SC_STORAGE) {
177
178                 /* Get the size of the variable */
179                 unsigned Size = SizeOf (Decl.Type);
180
181                 /* Allow initialization */
182                 if (CurTok.Tok == TOK_ASSIGN) {
183
184                     /* We cannot initialize types of unknown size, or
185                      * void types in non ANSI mode.
186                      */
187                     if (Size == 0) {
188                         if (!IsTypeVoid (Decl.Type)) {
189                             if (!IsTypeArray (Decl.Type)) {
190                                 /* Size is unknown and not an array */
191                                 Error ("Variable `%s' has unknown size", Decl.Ident);
192                             }
193                         } else if (IS_Get (&Standard) != STD_CC65) {
194                             /* We cannot declare variables of type void */
195                             Error ("Illegal type for variable `%s'", Decl.Ident);
196                         }
197                     }
198
199                     /* Switch to the data or rodata segment. For arrays, check
200                       * the element qualifiers, since not the array but its
201                       * elements are const.
202                       */
203                     if (IsQualConst (Decl.Type) ||
204                         (IsTypeArray (Decl.Type) &&
205                          IsQualConst (GetElementType (Decl.Type)))) {
206                         g_userodata ();
207                     } else {
208                         g_usedata ();
209                     }
210
211                     /* Define a label */
212                     g_defgloblabel (Entry->Name);
213
214                     /* Skip the '=' */
215                     NextToken ();
216
217                     /* Parse the initialization */
218                     ParseInit (Entry->Type);
219                 } else {
220
221                     if (IsTypeVoid (Decl.Type)) {
222                         /* We cannot declare variables of type void */
223                         Error ("Illegal type for variable `%s'", Decl.Ident);
224                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
225                     } else if (Size == 0) {
226                         /* Size is unknown. Is it an array? */
227                         if (!IsTypeArray (Decl.Type)) {
228                             Error ("Variable `%s' has unknown size", Decl.Ident);
229                         }
230                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
231                     }
232
233                     /* Allocate storage if it is still needed */
234                     if (Entry->Flags & SC_STORAGE) {
235
236                         /* Switch to the BSS segment */
237                         g_usebss ();
238
239                         /* Define a label */
240                         g_defgloblabel (Entry->Name);
241
242                         /* Allocate space for uninitialized variable */
243                         g_res (Size);
244                     }
245                 }
246
247             }
248
249             /* Check for end of declaration list */
250             if (CurTok.Tok == TOK_COMMA) {
251                 NextToken ();
252                 comma = 1;
253             } else {
254                 break;
255             }
256         }
257
258         /* Function declaration? */
259         if (Entry && IsTypeFunc (Entry->Type)) {
260
261             /* Function */
262             if (!comma) {
263                 if (CurTok.Tok == TOK_SEMI) {
264                     /* Prototype only */
265                     NextToken ();
266                 } else {
267
268                     /* Function body. Check for duplicate function definitions */
269                     if (SymIsDef (Entry)) {
270                         Error ("Body for function `%s' has already been defined",
271                                Entry->Name);
272                     }
273
274                     /* Parse the function body */
275                     NewFunc (Entry);
276                 }
277             }
278
279         } else {
280
281             /* Must be followed by a semicolon */
282             ConsumeSemi ();
283
284         }
285     }
286 }
287
288
289
290 void Compile (const char* FileName)
291 /* Top level compile routine. Will setup things and call the parser. */
292 {
293     char        DateStr[32];
294     char        TimeStr[32];
295     time_t      Time;
296     struct tm*  TM;
297
298     /* Since strftime is locale dependent, we need the abbreviated month names
299      * in english.
300      */
301     static const char MonthNames[12][4] = {
302         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
303         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
304     };
305
306     /* Add macros that are always defined */
307     DefineNumericMacro ("__CC65__", GetVersionAsNumber ());
308
309     /* Language standard that is supported */
310     DefineNumericMacro ("__CC65_STD_C89__", STD_C89);
311     DefineNumericMacro ("__CC65_STD_C99__", STD_C99);
312     DefineNumericMacro ("__CC65_STD_CC65__", STD_CC65);
313     DefineNumericMacro ("__CC65_STD__", IS_Get (&Standard));
314
315     /* Optimization macros. Since no source code has been parsed for now, the
316      * IS_Get functions access the values in effect now, regardless of any
317      * changes using #pragma later.
318      */
319     if (IS_Get (&Optimize)) {
320         long CodeSize = IS_Get (&CodeSizeFactor);
321         DefineNumericMacro ("__OPT__", 1);
322         if (CodeSize > 100) {
323             DefineNumericMacro ("__OPT_i__", CodeSize);
324         }
325         if (IS_Get (&EnableRegVars)) {
326             DefineNumericMacro ("__OPT_r__", 1);
327         }
328         if (IS_Get (&InlineStdFuncs)) {
329             DefineNumericMacro ("__OPT_s__", 1);
330         }
331     }
332
333     /* __TIME__ and __DATE__ macros */
334     Time = time (0);
335     TM   = localtime (&Time);
336     xsprintf (DateStr, sizeof (DateStr), "\"%s %2d %d\"",
337               MonthNames[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900);
338     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
339     DefineTextMacro ("__DATE__", DateStr);
340     DefineTextMacro ("__TIME__", TimeStr);
341
342     /* Other standard macros */
343     /* DefineNumericMacro ("__STDC__", 1);      <- not now */
344     DefineNumericMacro ("__STDC_HOSTED__", 1);
345
346     /* Initialize the literal pool */
347     InitLiteralPool ();
348
349     /* Create the base lexical level */
350     EnterGlobalLevel ();
351
352     /* Generate the code generator preamble */
353     g_preamble ();
354
355     /* Open the input file */
356     OpenMainFile (FileName);
357
358     /* Are we supposed to compile or just preprocess the input? */
359     if (PreprocessOnly) {
360
361         /* Open the file */
362         OpenOutputFile ();
363
364         /* Preprocess each line and write it to the output file */
365         while (NextLine ()) {
366             Preprocess ();
367             WriteOutput ("%.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line));
368         }
369
370         /* Close the output file */
371         CloseOutputFile ();
372
373         if (Debug) {
374             PrintMacroStats (stdout);
375         }
376
377     } else {
378
379         /* Ok, start the ball rolling... */
380         Parse ();
381
382         /* Dump the literal pool. */
383         DumpLiteralPool ();
384
385         /* Write imported/exported symbols */
386         EmitExternals ();
387
388         if (Debug) {
389             PrintLiteralPoolStats (stdout);
390             PrintMacroStats (stdout);
391         }
392
393     }
394
395     /* Leave the main lexical level */
396     LeaveGlobalLevel ();
397
398     /* Print an error report */
399     ErrorReport ();
400 }
401
402
403
404