]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
Fixed the last fix. Sigh:-(
[cc65] / src / cc65 / compile.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 compile.c                                 */
4 /*                                                                           */
5 /*                       Top level compiler subroutine                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2002 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
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 "declare.h"
50 #include "error.h"
51 #include "expr.h"
52 #include "function.h"
53 #include "global.h"
54 #include "incpath.h"
55 #include "input.h"
56 #include "litpool.h"
57 #include "macrotab.h"
58 #include "pragma.h"
59 #include "symtab.h"
60 #include "compile.h"
61
62
63
64 /*****************************************************************************/
65 /*                                   Code                                    */
66 /*****************************************************************************/
67
68
69
70 static void Parse (void)
71 /* Top level parser routine. */
72 {
73     int comma;
74     SymEntry* Entry;
75
76     /* Go... */
77     NextToken ();
78     NextToken ();
79
80     /* Parse until end of input */
81     while (CurTok.Tok != TOK_CEOF) {
82
83         DeclSpec        Spec;
84         Declaration     Decl;
85         int             NeedStorage;
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         /* Check if we must reserve storage for the variable. We do
126          * this if we don't had a storage class given ("int i") or
127          * if the storage class is explicitly specified as static.
128          * This means that "extern int i" will not get storage
129          * allocated.
130          */
131         NeedStorage = (Spec.StorageClass & SC_TYPEDEF) == 0 &&
132                       ((Spec.Flags & DS_DEF_STORAGE) != 0  ||
133                       (Spec.StorageClass & (SC_STATIC | SC_EXTERN)) == SC_STATIC);
134
135         /* Read declarations for this type */
136         Entry = 0;
137         comma = 0;
138         while (1) {
139
140             unsigned SymFlags;
141
142             /* Read the next declaration */
143             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
144             if (Decl.Ident[0] == '\0') {
145                 NextToken ();
146                 break;
147             }
148
149             /* Get the symbol flags */
150             SymFlags = Spec.StorageClass;
151             if (IsTypeFunc (Decl.Type)) {
152                 SymFlags |= SC_FUNC;
153             } else {
154                 if (NeedStorage) {
155                     /* We will allocate storage, variable is defined */
156                     SymFlags |= SC_STORAGE | SC_DEF;
157                 }
158             }
159
160             /* Add an entry to the symbol table */
161             Entry = AddGlobalSym (Decl.Ident, Decl.Type, SymFlags);
162
163             /* Reserve storage for the variable if we need to */
164             if (SymFlags & SC_STORAGE) {
165
166                 /* Get the size of the variable */
167                 unsigned Size = SizeOf (Decl.Type);
168
169                 /* Allow initialization */
170                 if (CurTok.Tok == TOK_ASSIGN) {
171
172                     /* We cannot initialize types of unknown size, or
173                      * void types in non ANSI mode.
174                      */
175                     if (Size == 0) {
176                         if (!IsTypeVoid (Decl.Type)) {
177                             if (!IsTypeArray (Decl.Type)) {
178                                 /* Size is unknown and not an array */
179                                 Error ("Variable `%s' has unknown size", Decl.Ident);
180                             }
181                         } else if (ANSI) {
182                             /* We cannot declare variables of type void */
183                             Error ("Illegal type for variable `%s'", Decl.Ident);
184                         }
185                     }
186
187                     /* Switch to the data or rodata segment */
188                     if (IsQualConst (Decl.Type)) {
189                         g_userodata ();
190                     } else {
191                         g_usedata ();
192                     }
193
194                     /* Define a label */
195                     g_defgloblabel (Entry->Name);
196
197                     /* Skip the '=' */
198                     NextToken ();
199
200                     /* Parse the initialization */
201                     ParseInit (Entry->Type);
202                 } else {
203
204                     if (IsTypeVoid (Decl.Type)) {
205                         /* We cannot declare variables of type void */
206                         Error ("Illegal type for variable `%s'", Decl.Ident);
207                     } else if (Size == 0) {
208                         /* Size is unknown */
209                         Error ("Variable `%s' has unknown size", Decl.Ident);
210                     }
211
212                     /* Switch to the BSS segment */
213                     g_usebss ();
214
215                     /* Define a label */
216                     g_defgloblabel (Entry->Name);
217
218                     /* Allocate space for uninitialized variable */
219                     g_res (SizeOf (Entry->Type));
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 if (Entry) {
242                     /* Function body definition */
243                     if (SymIsDef (Entry)) {
244                         Error ("Body for function `%s' has already been defined",
245                                Entry->Name);
246                     }
247                     NewFunc (Entry);
248                 }
249             }
250
251         } else {
252
253             /* Must be followed by a semicolon */
254             ConsumeSemi ();
255
256         }
257     }
258 }
259
260
261
262 void Compile (const char* FileName)
263 /* Top level compile routine. Will setup things and call the parser. */
264 {
265     char*       Path;
266     char        Buf[20];
267     char        DateStr[20];
268     char        TimeStr[20];
269     time_t      Time;
270     struct tm*  TM;
271
272     /* Since strftime is locale dependent, we need the abbreviated month names
273      * in english.
274      */
275     static const char MonthNames[12][4] = {
276         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
277         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
278     };
279
280     /* Add some standard paths to the include search path */
281     AddIncludePath ("", INC_USER);              /* Current directory */
282     AddIncludePath ("include", INC_SYS);
283 #ifdef CC65_INC
284     AddIncludePath (CC65_INC, INC_SYS);
285 #else
286     AddIncludePath ("/usr/lib/cc65/include", INC_SYS);
287 #endif
288     Path = getenv ("CC65_INC");
289     if (Path) {
290         AddIncludePath (Path, INC_SYS | INC_USER);
291     }
292
293     /* Add macros that are always defined */
294     DefineNumericMacro ("__CC65__", (VER_MAJOR * 0x100) + (VER_MINOR * 0x10) + VER_PATCH);
295
296     /* Strict ANSI macro */
297     if (ANSI) {
298         DefineNumericMacro ("__STRICT_ANSI__", 1);
299     }
300
301     /* Optimization macros */
302     if (Optimize) {
303         DefineNumericMacro ("__OPT__", 1);
304         if (FavourSize == 0) {
305             DefineNumericMacro ("__OPT_i__", 1);
306         }
307         if (EnableRegVars) {
308             DefineNumericMacro ("__OPT_r__", 1);
309         }
310         if (InlineStdFuncs) {
311             DefineNumericMacro ("__OPT_s__", 1);
312         }
313     }
314
315     /* __TIME__ and __DATE__ macros */
316     Time = time (0);
317     TM   = localtime (&Time);
318     strftime (Buf, sizeof (Buf), "%e %Y", TM);
319     xsprintf (DateStr, sizeof (DateStr), "\"%s %s\"", MonthNames[TM->tm_mon], Buf);
320     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
321     DefineTextMacro ("__DATE__", DateStr);
322     DefineTextMacro ("__TIME__", TimeStr);
323
324     /* Initialize the literal pool */
325     InitLiteralPool ();
326
327     /* Create the base lexical level */
328     EnterGlobalLevel ();
329
330     /* Generate the code generator preamble */
331     g_preamble ();
332
333     /* Open the input file */
334     OpenMainFile (FileName);
335
336     /* Ok, start the ball rolling... */
337     Parse ();
338
339     /* Dump the literal pool. */
340     DumpLiteralPool ();
341
342     /* Write imported/exported symbols */
343     EmitExternals ();
344
345     if (Debug) {
346         PrintLiteralPoolStats (stdout);
347         PrintMacroStats (stdout);
348     }
349
350     /* Leave the main lexical level */
351     LeaveGlobalLevel ();
352
353     /* Print an error report */
354     ErrorReport ();
355 }
356
357
358