]> git.sur5r.net Git - cc65/blob - src/cc65/input.c
Fixed an error handling SC_EXTERN.
[cc65] / src / cc65 / input.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  input.c                                  */
4 /*                                                                           */
5 /*                            Input file handling                            */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2004 Ullrich von Bassewitz                                       */
10 /*               Römerstrasse 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 <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 "codegen.h"
50 #include "error.h"
51 #include "incpath.h"
52 #include "lineinfo.h"
53 #include "input.h"
54
55
56
57 /*****************************************************************************/
58 /*                                   Data                                    */
59 /*****************************************************************************/
60
61
62
63 /* The current input line */
64 StrBuf* Line;
65
66 /* Current and next input character */
67 char CurC  = '\0';
68 char NextC = '\0';
69
70 /* Maximum count of nested includes */
71 #define MAX_INC_NESTING         16
72
73 /* Struct that describes an active input file */
74 typedef struct AFile AFile;
75 struct AFile {
76     unsigned    Line;           /* Line number for this file            */
77     FILE*       F;              /* Input file stream                    */
78     IFile*      Input;          /* Points to corresponding IFile        */
79 };
80
81 /* List of all input files */
82 static Collection IFiles = STATIC_COLLECTION_INITIALIZER;
83
84 /* List of all active files */
85 static Collection AFiles = STATIC_COLLECTION_INITIALIZER;
86
87 /* Input stack used when preprocessing. */
88 static Collection InputStack = 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. There a race condition here,
147          * since we cannot use fileno() (non standard identifier in standard
148          * header file), and therefore not fstat. When using stat with the
149          * file name, there's a risk that the file was deleted and recreated
150          * while it was open. Since mtime and size are only used to check
151          * if a file has changed in the debugger, we will ignore this problem
152          * here.
153          */
154         struct stat Buf;
155         if (stat (IF->Name, &Buf) != 0) {
156             /* Error */
157             Fatal ("Cannot stat `%s': %s", IF->Name, strerror (errno));
158         }
159         IF->Size  = (unsigned long) Buf.st_size;
160         IF->MTime = (unsigned long) Buf.st_mtime;
161
162         /* Set the debug data */
163         g_fileinfo (IF->Name, IF->Size, IF->MTime);
164     }
165
166     /* Insert the new structure into the AFile collection */
167     CollAppend (&AFiles, AF);
168
169     /* Return the new struct */
170     return AF;
171 }
172
173
174
175 static void FreeAFile (AFile* AF)
176 /* Free an AFile structure */
177 {
178     xfree (AF);
179 }
180
181
182
183 /*****************************************************************************/
184 /*                                   Code                                    */
185 /*****************************************************************************/
186
187
188
189 static IFile* FindFile (const char* Name)
190 /* Find the file with the given name in the list of all files. Since the list
191  * is not large (usually less than 10), I don't care about using hashes or
192  * similar things and do a linear search.
193  */
194 {
195     unsigned I;
196     for (I = 0; I < CollCount (&IFiles); ++I) {
197         /* Get the file struct */
198         IFile* IF = (IFile*) CollAt (&IFiles, I);
199         /* Check the name */
200         if (strcmp (Name, IF->Name) == 0) {
201             /* Found, return the struct */
202             return IF;
203         }
204     }
205
206     /* Not found */
207     return 0;
208 }
209
210
211
212 void OpenMainFile (const char* Name)
213 /* Open the main file. Will call Fatal() in case of failures. */
214 {
215     AFile* MainFile;
216
217
218     /* Setup a new IFile structure for the main file */
219     IFile* IF = NewIFile (Name);
220
221     /* Open the file for reading */
222     FILE* F = fopen (Name, "r");
223     if (F == 0) {
224         /* Cannot open */
225         Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
226     }
227
228     /* Allocate a new AFile structure for the file */
229     MainFile = NewAFile (IF, F);
230
231     /* Allocate the input line buffer */
232     Line = NewStrBuf ();
233
234     /* Update the line infos, so we have a valid line info even at start of
235      * the main file before the first line is read.
236      */
237     UpdateLineInfo (MainFile->Input, MainFile->Line, Line);
238 }
239
240
241
242 void OpenIncludeFile (const char* Name, unsigned DirSpec)
243 /* Open an include file and insert it into the tables. */
244 {
245     char*  N;
246     FILE*  F;
247     IFile* IF;
248
249     /* Check for the maximum include nesting */
250     if (CollCount (&AFiles) > MAX_INC_NESTING) {
251         PPError ("Include nesting too deep");
252         return;
253     }
254
255     /* Search for the file */
256     N = FindInclude (Name, DirSpec);
257     if (N == 0) {
258         PPError ("Include file `%s' not found", Name);
259         return;
260     }
261
262     /* Search the list of all input files for this file. If we don't find
263      * it, create a new IFile object.
264      */
265     IF = FindFile (N);
266     if (IF == 0) {
267         IF = NewIFile (N);
268     }
269
270     /* We don't need N any longer, since we may now use IF->Name */
271     xfree (N);
272
273     /* Open the file */
274     F = fopen (IF->Name, "r");
275     if (F == 0) {
276         /* Error opening the file */
277         PPError ("Cannot open include file `%s': %s", IF->Name, strerror (errno));
278         return;
279     }
280
281     /* Debugging output */
282     Print (stdout, 1, "Opened include file `%s'\n", IF->Name);
283
284     /* Allocate a new AFile structure */
285     (void) NewAFile (IF, F);
286 }
287
288
289
290 static void CloseIncludeFile (void)
291 /* Close an include file and switch to the higher level file. Set Input to
292  * NULL if this was the main file.
293  */
294 {
295     AFile* Input;
296
297     /* Get the number of active input files */
298     unsigned AFileCount = CollCount (&AFiles);
299
300     /* Must have an input file when called */
301     PRECONDITION (AFileCount > 0);
302
303     /* Get the current active input file */
304     Input = (AFile*) CollLast (&AFiles);
305
306     /* Close the current input file (we're just reading so no error check) */
307     fclose (Input->F);
308
309     /* Delete the last active file from the active file collection */
310     CollDelete (&AFiles, AFileCount-1);
311
312     /* Delete the active file structure */
313     FreeAFile (Input);
314 }
315
316
317
318 static void GetInputChar (void)
319 /* Read the next character from the input stream and make CurC and NextC
320  * valid. If end of line is reached, both are set to NUL, no more lines
321  * are read by this function.
322  */
323 {
324     /* Drop all pushed fragments that don't have data left */
325     while (SB_GetIndex (Line) >= SB_GetLen (Line)) {
326         /* Cannot read more from this line, check next line on stack if any */
327         if (CollCount (&InputStack) == 0) {
328             /* This is THE line */
329             break;
330         }
331         FreeStrBuf (Line);
332         Line = CollPop (&InputStack);
333     }
334
335     /* Now get the next characters from the line */
336     if (SB_GetIndex (Line) >= SB_GetLen (Line)) {
337         CurC = NextC = '\0';
338     } else {
339         CurC = SB_AtUnchecked (Line, SB_GetIndex (Line));
340         if (SB_GetIndex (Line) + 1 < SB_GetLen (Line)) {
341             /* NextC comes from this fragment */
342             NextC = SB_AtUnchecked (Line, SB_GetIndex (Line) + 1);
343         } else {
344             /* NextC comes from next fragment */
345             if (CollCount (&InputStack) > 0) {
346                 NextC = ' ';
347             } else {
348                 NextC = '\0';
349             }
350         }
351     }
352 }
353
354
355
356 void NextChar (void)
357 /* Skip the current input character and read the next one from the input
358  * stream. CurC and NextC are valid after the call. If end of line is
359  * reached, both are set to NUL, no more lines are read by this function.
360  */
361 {
362     /* Skip the last character read */
363     SB_Skip (Line);
364
365     /* Read the next one */
366     GetInputChar ();
367 }
368
369
370
371 void ClearLine (void)
372 /* Clear the current input line */
373 {
374     unsigned I;
375
376     /* Remove all pushed fragments from the input stack */
377     for (I = 0; I < CollCount (&InputStack); ++I) {
378         FreeStrBuf (CollAtUnchecked (&InputStack, I));
379     }
380     CollDeleteAll (&InputStack);
381
382     /* Clear the contents of Line */
383     SB_Clear (Line);
384     CurC    = '\0';
385     NextC   = '\0';
386 }
387
388
389
390 StrBuf* InitLine (StrBuf* Buf)
391 /* Initialize Line from Buf and read CurC and NextC from the new input line.
392  * The function returns the old input line.
393  */
394 {
395     StrBuf* OldLine = Line;
396     Line  = Buf;
397     CurC  = SB_LookAt (Buf, SB_GetIndex (Buf));
398     NextC = SB_LookAt (Buf, SB_GetIndex (Buf) + 1);
399     return OldLine;
400 }
401
402
403
404 void PushLine (const StrBuf* Buf)
405 /* Push a copy of Buf onto the input stack */
406 {
407     CollAppend (&InputStack, Line);
408     Line = NewStrBuf ();
409     SB_Copy (Line, Buf);
410
411     /* Make CurC and NextC valid */
412     GetInputChar ();
413 }
414
415
416
417 int NextLine (void)
418 /* Get a line from the current input. Returns 0 on end of file. */
419 {
420     AFile*      Input;
421
422     /* Clear the current line */
423     ClearLine ();
424
425     /* If there is no file open, bail out, otherwise get the current input file */
426     if (CollCount (&AFiles) == 0) {
427         return 0;
428     }
429     Input = CollLast (&AFiles);
430
431     /* Read characters until we have one complete line */
432     while (1) {
433
434         /* Read the next character */
435         int C = fgetc (Input->F);
436
437         /* Check for EOF */
438         if (C == EOF) {
439
440             /* Accept files without a newline at the end */
441             if (SB_NotEmpty (Line)) {
442                 ++Input->Line;
443                 break;
444             }
445
446             /* Leave the current file */
447             CloseIncludeFile ();
448
449             /* If there is no file open, bail out, otherwise get the
450              * previous input file and start over.
451              */
452             if (CollCount (&AFiles) == 0) {
453                 return 0;
454             }
455             Input = CollLast (&AFiles);
456             continue;
457         }
458
459         /* Check for end of line */
460         if (C == '\n') {
461
462             /* We got a new line */
463             ++Input->Line;
464
465             /* If the \n is preceeded by a \r, remove the \r, so we can read
466              * DOS/Windows files under *nix.
467              */
468             if (SB_LookAtLast (Line) == '\r') {
469                 SB_Drop (Line, 1);
470             }
471
472             /* If we don't have a line continuation character at the end,
473              * we're done with this line. Otherwise replace the character
474              * by a newline and continue reading.
475              */
476             if (SB_LookAtLast (Line) == '\\') {
477                 Line->Buf[Line->Len-1] = '\n';
478             } else {
479                 break;
480             }
481
482         } else if (C != '\0') {         /* Ignore embedded NULs */
483
484             /* Just some character, add it to the line */
485             SB_AppendChar (Line, C);
486
487         }
488     }
489
490     /* Add a termination character to the string buffer */
491     SB_Terminate (Line);
492
493     /* Initialize the current and next characters. */
494     InitLine (Line);
495
496     /* Create line information for this line */
497     UpdateLineInfo (Input->Input, Input->Line, Line);
498
499     /* Done */
500     return 1;
501 }
502
503
504
505 const char* GetCurrentFile (void)
506 /* Return the name of the current input file */
507 {
508     unsigned AFileCount = CollCount (&AFiles);
509     if (AFileCount > 0) {
510         const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
511         return AF->Input->Name;
512     } else {
513         /* No open file. Use the main file if we have one. */
514         unsigned IFileCount = CollCount (&IFiles);
515         if (IFileCount > 0) {
516             const IFile* IF = (const IFile*) CollAt (&IFiles, 0);
517             return IF->Name;
518         } else {
519             return "(outside file scope)";
520         }
521     }
522 }
523
524
525
526 unsigned GetCurrentLine (void)
527 /* Return the line number in the current input file */
528 {
529     unsigned AFileCount = CollCount (&AFiles);
530     if (AFileCount > 0) {
531         const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
532         return AF->Line;
533     } else {
534         /* No open file */
535         return 0;
536     }
537 }
538
539
540
541 void WriteDependencies (FILE* F, const char* OutputFile)
542 /* Write a makefile dependency list to the given file */
543 {
544     unsigned I;
545
546     /* Get the number of input files */
547     unsigned IFileCount = CollCount (&IFiles);
548
549     /* Print the output file followed by a tab char */
550     fprintf (F, "%s:\t", OutputFile);
551
552     /* Loop over all files */
553     for (I = 0; I < IFileCount; ++I) {
554         /* Get the next input file */
555         const IFile* IF = (const IFile*) CollAt (&IFiles, I);
556         /* If this is not the first file, add a space */
557         const char* Format = (I == 0)? "%s" : " %s";
558         /* Print the dependency */
559         fprintf (F, Format, IF->Name);
560     }
561
562     /* End the line */
563     fprintf (F, "\n\n");
564 }
565
566
567