]> git.sur5r.net Git - cc65/blob - src/cc65/input.c
Fixed a bug
[cc65] / src / cc65 / input.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  input.c                                  */
4 /*                                                                           */
5 /*                            Input file handling                            */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000      Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@musoftware.de                                            */
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 <stdio.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41
42 /* common */
43 #include "check.h"
44 #include "coll.h"
45 #include "print.h"
46 #include "xmalloc.h"
47
48 /* cc65 */
49 #include "asmcode.h"
50 #include "codegen.h"
51 #include "error.h"
52 #include "incpath.h"
53 #include "lineinfo.h"
54 #include "input.h"
55
56
57
58 /*****************************************************************************/
59 /*                                   Data                                    */
60 /*****************************************************************************/
61
62
63
64 /* Input line stuff */
65 static char LineBuf [LINESIZE];
66 char* line = LineBuf;
67 const char* lptr = LineBuf;
68
69 /* Current and next input character */
70 char CurC  = '\0';
71 char NextC = '\0';
72
73 /* Maximum count of nested includes */
74 #define MAX_INC_NESTING         16
75
76 /* Struct that describes an active input file */
77 typedef struct AFile AFile;
78 struct AFile {
79     unsigned    Line;           /* Line number for this file            */
80     FILE*       F;              /* Input file stream                    */
81     IFile*      Input;          /* Points to corresponding IFile        */
82 };
83
84 /* List of all input files */
85 static Collection IFiles = STATIC_COLLECTION_INITIALIZER;
86
87 /* List of all active files */
88 static Collection AFiles = STATIC_COLLECTION_INITIALIZER;
89
90
91
92 /*****************************************************************************/
93 /*                               struct IFile                                */
94 /*****************************************************************************/
95
96
97
98 static IFile* NewIFile (const char* Name)
99 /* Create and return a new IFile */
100 {
101     /* Get the length of the name */
102     unsigned Len = strlen (Name);
103
104     /* Allocate a IFile structure */
105     IFile* IF = (IFile*) xmalloc (sizeof (IFile) + Len);
106
107     /* Initialize the fields */
108     IF->Index = CollCount (&IFiles) + 1;
109     IF->Usage = 0;
110     IF->Size  = 0;
111     IF->MTime = 0;
112     memcpy (IF->Name, Name, Len+1);
113
114     /* Insert the new structure into the IFile collection */
115     CollAppend (&IFiles, IF);
116
117     /* Return the new struct */
118     return IF;
119 }
120
121
122
123 /*****************************************************************************/
124 /*                               struct AFile                                */
125 /*****************************************************************************/
126
127
128
129 static AFile* NewAFile (IFile* IF, FILE* F)
130 /* Create and return a new AFile */
131 {
132     /* Allocate a AFile structure */
133     AFile* AF = (AFile*) xmalloc (sizeof (AFile));
134
135     /* Initialize the fields */
136     AF->Line  = 0;
137     AF->F     = F;
138     AF->Input = IF;
139
140     /* Increment the usage counter of the corresponding IFile. If this
141      * is the first use, set the file data and output debug info if
142      * requested.
143      */
144     if (IF->Usage++ == 0) {
145
146         /* Get file size and modification time */
147         struct stat Buf;
148         if (fstat (fileno (F), &Buf) != 0) {
149             /* Error */
150             Fatal ("Cannot stat `%s': %s", IF->Name, strerror (errno));
151         }
152         IF->Size  = (unsigned long) Buf.st_size;
153         IF->MTime = (unsigned long) Buf.st_mtime;
154
155         /* Set the debug data */
156         g_fileinfo (IF->Name, IF->Size, IF->MTime);
157     }
158
159     /* Insert the new structure into the AFile collection */
160     CollAppend (&AFiles, AF);
161
162     /* Return the new struct */
163     return AF;
164 }
165
166
167
168 static void FreeAFile (AFile* AF)
169 /* Free an AFile structure */
170 {
171     xfree (AF);
172 }
173
174
175
176 /*****************************************************************************/
177 /*                                   Code                                    */
178 /*****************************************************************************/
179
180
181
182 static IFile* FindFile (const char* Name)
183 /* Find the file with the given name in the list of all files. Since the list
184  * is not large (usually less than 10), I don't care about using hashes or
185  * similar things and do a linear search.
186  */
187 {
188     unsigned I;
189     for (I = 0; I < CollCount (&IFiles); ++I) {
190         /* Get the file struct */
191         IFile* IF = (IFile*) CollAt (&IFiles, I);
192         /* Check the name */
193         if (strcmp (Name, IF->Name) == 0) {
194             /* Found, return the struct */
195             return IF;
196         }
197     }
198
199     /* Not found */
200     return 0;
201 }
202
203
204
205 void OpenMainFile (const char* Name)
206 /* Open the main file. Will call Fatal() in case of failures. */
207 {
208     /* Setup a new IFile structure for the main file */
209     IFile* IF = NewIFile (Name);
210
211     /* Open the file for reading */
212     FILE* F = fopen (Name, "r");
213     if (F == 0) {
214         /* Cannot open */
215         Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
216     }
217
218     /* Allocate a new AFile structure for the file */
219     (void) NewAFile (IF, F);
220 }
221
222
223
224 void OpenIncludeFile (const char* Name, unsigned DirSpec)
225 /* Open an include file and insert it into the tables. */
226 {
227     char*  N;
228     FILE*  F;
229     IFile* IF;
230
231     /* Check for the maximum include nesting */
232     if (CollCount (&AFiles) > MAX_INC_NESTING) {
233         PPError ("Include nesting too deep");
234         return;
235     }
236
237     /* Search for the file */
238     N = FindInclude (Name, DirSpec);
239     if (N == 0) {
240         PPError ("Include file `%s' not found", Name);
241         return;
242     }
243
244     /* Search the list of all input files for this file. If we don't find
245      * it, create a new IFile object.
246      */
247     IF = FindFile (N);
248     if (IF == 0) {
249         IF = NewIFile (N);
250     }
251
252     /* We don't need N any longer, since we may now use IF->Name */
253     xfree (N);
254
255     /* Open the file */
256     F = fopen (IF->Name, "r");
257     if (F == 0) {
258         /* Error opening the file */
259         PPError ("Cannot open include file `%s': %s", IF->Name, strerror (errno));
260         return;
261     }
262
263     /* Debugging output */
264     Print (stdout, 1, "Opened include file `%s'\n", IF->Name);
265
266     /* Allocate a new AFile structure */
267     (void) NewAFile (IF, F);
268 }
269
270
271
272 static void CloseIncludeFile (void)
273 /* Close an include file and switch to the higher level file. Set Input to
274  * NULL if this was the main file.
275  */
276 {
277     AFile* Input;
278
279     /* Get the number of active input files */
280     unsigned AFileCount = CollCount (&AFiles);
281
282     /* Must have an input file when called */
283     PRECONDITION (AFileCount > 0);
284
285     /* Get the current active input file */
286     Input = (AFile*) CollLast (&AFiles);
287
288     /* Close the current input file (we're just reading so no error check) */
289     fclose (Input->F);
290
291     /* Delete the last active file from the active file collection */
292     CollDelete (&AFiles, AFileCount-1);
293
294     /* Delete the active file structure */
295     FreeAFile (Input);
296 }
297
298
299
300 void ClearLine (void)
301 /* Clear the current input line */
302 {
303     line[0] = '\0';
304     lptr    = line;
305     CurC    = '\0';
306     NextC   = '\0';
307 }
308
309
310
311 void InitLine (const char* Buf)
312 /* Initialize lptr from Buf and read CurC and NextC from the new input line */
313 {
314     lptr = Buf;
315     CurC = lptr[0];
316     if (CurC != '\0') {
317         NextC = lptr[1];
318     } else {
319         NextC = '\0';
320     }
321 }
322
323
324
325 void NextChar (void)
326 /* Read the next character from the input stream and make CurC and NextC
327  * valid. If end of line is reached, both are set to NUL, no more lines
328  * are read by this function.
329  */
330 {
331     if (lptr[0] != '\0') {
332         ++lptr;
333         CurC = lptr[0];
334         if (CurC != '\0') {
335             NextC = lptr[1];
336         } else {
337             NextC = '\0';
338         }
339     } else {
340         CurC = NextC = '\0';
341     }
342 }
343
344
345
346 int NextLine (void)
347 /* Get a line from the current input. Returns 0 on end of file. */
348 {
349     AFile*      Input;
350     unsigned    Len;
351     unsigned    Part;
352     unsigned    Start;
353     int         Done;
354
355     /* Setup the line */
356     ClearLine ();
357
358     /* If there is no file open, bail out, otherwise get the current input file */
359     if (CollCount (&AFiles) == 0) {
360         return 0;
361     }
362     Input = (AFile*) CollLast (&AFiles);
363
364     /* Read lines until we get one with real contents */
365     Len = 0;
366     Done = 0;
367     while (!Done && Len < LINESIZE) {
368
369         while (fgets (line + Len, LINESIZE - Len, Input->F) == 0) {
370
371             /* Assume EOF */
372             ClearLine ();
373
374             /* Leave the current file */
375             CloseIncludeFile ();
376
377             /* If there is no file open, bail out, otherwise get the
378              * current input file
379              */
380             if (CollCount (&AFiles) == 0) {
381                 return 0;
382             }
383             Input = (AFile*) CollLast (&AFiles);
384
385         }
386
387         /* We got a new line */
388         ++Input->Line;
389
390         /* Remove the trailing cr/lf if we have one. We will ignore both, cr
391          * and lf on all systems since this enables us to compile DOS/Windows
392          * stuff also on unix systems (where fgets does not remove the cr).
393          */
394         Part = strlen (line + Len);
395         Start = Len;
396         Len += Part;
397         while (Len > 0 && (line[Len-1] == '\n' || line[Len-1] == '\r')) {
398             --Len;
399         }
400         line [Len] = '\0';
401
402         /* Check if we have a line continuation character at the end. If not,
403          * we're done.
404          */
405         if (Len > 0 && line[Len-1] == '\\') {
406             line[Len-1] = '\n';         /* Replace by newline */
407         } else {
408             Done = 1;
409         }
410     }
411
412     /* Got a line. Initialize the current and next characters. */
413     InitLine (line);
414
415     /* Create line information for this line */
416     UpdateLineInfo (Input->Input, Input->Line, line);
417
418     /* Done */
419     return 1;
420 }
421
422
423
424 const char* GetCurrentFile (void)
425 /* Return the name of the current input file */
426 {
427     unsigned AFileCount = CollCount (&AFiles);
428     if (AFileCount > 0) {
429         const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
430         return AF->Input->Name;
431     } else {
432         /* No open file. Use the main file if we have one. */
433         unsigned IFileCount = CollCount (&IFiles);
434         if (IFileCount > 0) {
435             const IFile* IF = (const IFile*) CollAt (&IFiles, 0);
436             return IF->Name;
437         } else {
438             return "(outside file scope)";
439         }
440     }
441 }
442
443
444
445 unsigned GetCurrentLine (void)
446 /* Return the line number in the current input file */
447 {
448     unsigned AFileCount = CollCount (&AFiles);
449     if (AFileCount > 0) {
450         const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
451         return AF->Line;
452     } else {
453         /* No open file */
454         return 0;
455     }
456 }
457
458
459
460 void WriteDependencies (FILE* F, const char* OutputFile)
461 /* Write a makefile dependency list to the given file */
462 {
463     unsigned I;
464
465     /* Get the number of input files */
466     unsigned IFileCount = CollCount (&IFiles);
467
468     /* Print the output file followed by a tab char */
469     fprintf (F, "%s:\t", OutputFile);
470
471     /* Loop over all files */
472     for (I = 0; I < IFileCount; ++I) {
473         /* Get the next input file */
474         const IFile* IF = (const IFile*) CollAt (&IFiles, I);
475         /* If this is not the first file, add a space */
476         const char* Format = (I == 0)? "%s" : " %s";
477         /* Print the dependency */
478         fprintf (F, Format, IF->Name);
479     }
480
481     /* End the line */
482     fprintf (F, "\n\n");
483 }
484
485
486