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