1 /*****************************************************************************/
5 /* Input file handling */
9 /* (C) 2000-2010, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
39 #include <sys/types.h>
57 /*****************************************************************************/
59 /*****************************************************************************/
63 /* The current input line */
66 /* Current and next input character */
70 /* Maximum count of nested includes */
71 #define MAX_INC_NESTING 16
73 /* Struct that describes an active input file */
74 typedef struct AFile AFile;
76 unsigned Line; /* Line number for this file */
77 FILE* F; /* Input file stream */
78 IFile* Input; /* Points to corresponding IFile */
81 /* List of all input files */
82 static Collection IFiles = STATIC_COLLECTION_INITIALIZER;
84 /* List of all active files */
85 static Collection AFiles = STATIC_COLLECTION_INITIALIZER;
87 /* Input stack used when preprocessing. */
88 static Collection InputStack = STATIC_COLLECTION_INITIALIZER;
92 /*****************************************************************************/
94 /*****************************************************************************/
98 static IFile* NewIFile (const char* Name, InputType Type)
99 /* Create and return a new IFile */
101 /* Get the length of the name */
102 unsigned Len = strlen (Name);
104 /* Allocate a IFile structure */
105 IFile* IF = (IFile*) xmalloc (sizeof (IFile) + Len);
107 /* Initialize the fields */
108 IF->Index = CollCount (&IFiles) + 1;
113 memcpy (IF->Name, Name, Len+1);
115 /* Insert the new structure into the IFile collection */
116 CollAppend (&IFiles, IF);
118 /* Return the new struct */
124 /*****************************************************************************/
126 /*****************************************************************************/
130 static AFile* NewAFile (IFile* IF, FILE* F)
131 /* Create and return a new AFile */
133 /* Allocate a AFile structure */
134 AFile* AF = (AFile*) xmalloc (sizeof (AFile));
136 /* Initialize the fields */
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
145 if (IF->Usage++ == 0) {
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
156 if (stat (IF->Name, &Buf) != 0) {
158 Fatal ("Cannot stat `%s': %s", IF->Name, strerror (errno));
160 IF->Size = (unsigned long) Buf.st_size;
161 IF->MTime = (unsigned long) Buf.st_mtime;
163 /* Set the debug data */
164 g_fileinfo (IF->Name, IF->Size, IF->MTime);
167 /* Insert the new structure into the AFile collection */
168 CollAppend (&AFiles, AF);
170 /* Return the new struct */
176 static void FreeAFile (AFile* AF)
177 /* Free an AFile structure */
184 /*****************************************************************************/
186 /*****************************************************************************/
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.
197 for (I = 0; I < CollCount (&IFiles); ++I) {
198 /* Get the file struct */
199 IFile* IF = (IFile*) CollAt (&IFiles, I);
201 if (strcmp (Name, IF->Name) == 0) {
202 /* Found, return the struct */
213 void OpenMainFile (const char* Name)
214 /* Open the main file. Will call Fatal() in case of failures. */
219 /* Setup a new IFile structure for the main file */
220 IFile* IF = NewIFile (Name, IT_MAIN);
222 /* Open the file for reading */
223 FILE* F = fopen (Name, "r");
226 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
229 /* Allocate a new AFile structure for the file */
230 MainFile = NewAFile (IF, F);
232 /* Allocate the input line buffer */
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.
238 UpdateLineInfo (MainFile->Input, MainFile->Line, Line);
243 void OpenIncludeFile (const char* Name, unsigned DirSpec)
244 /* Open an include file and insert it into the tables. */
250 /* Check for the maximum include nesting */
251 if (CollCount (&AFiles) > MAX_INC_NESTING) {
252 PPError ("Include nesting too deep");
256 /* Search for the file */
257 N = FindInclude (Name, DirSpec);
259 PPError ("Include file `%s' not found", Name);
263 /* Search the list of all input files for this file. If we don't find
264 * it, create a new IFile object.
268 IF = NewIFile (N, (DirSpec == INC_SYS)? IT_SYSINC : IT_USERINC);
271 /* We don't need N any longer, since we may now use IF->Name */
275 F = fopen (IF->Name, "r");
277 /* Error opening the file */
278 PPError ("Cannot open include file `%s': %s", IF->Name, strerror (errno));
282 /* Debugging output */
283 Print (stdout, 1, "Opened include file `%s'\n", IF->Name);
285 /* Allocate a new AFile structure */
286 (void) NewAFile (IF, F);
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.
298 /* Get the number of active input files */
299 unsigned AFileCount = CollCount (&AFiles);
301 /* Must have an input file when called */
302 PRECONDITION (AFileCount > 0);
304 /* Get the current active input file */
305 Input = (AFile*) CollLast (&AFiles);
307 /* Close the current input file (we're just reading so no error check) */
310 /* Delete the last active file from the active file collection */
311 CollDelete (&AFiles, AFileCount-1);
313 /* Delete the active file structure */
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.
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 */
333 Line = CollPop (&InputStack);
336 /* Now get the next characters from the line */
337 if (SB_GetIndex (Line) >= SB_GetLen (Line)) {
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);
345 /* NextC comes from next fragment */
346 if (CollCount (&InputStack) > 0) {
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.
363 /* Skip the last character read */
366 /* Read the next one */
372 void ClearLine (void)
373 /* Clear the current input line */
377 /* Remove all pushed fragments from the input stack */
378 for (I = 0; I < CollCount (&InputStack); ++I) {
379 FreeStrBuf (CollAtUnchecked (&InputStack, I));
381 CollDeleteAll (&InputStack);
383 /* Clear the contents of Line */
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.
396 StrBuf* OldLine = Line;
398 CurC = SB_LookAt (Buf, SB_GetIndex (Buf));
399 NextC = SB_LookAt (Buf, SB_GetIndex (Buf) + 1);
406 /* Get a line from the current input. Returns 0 on end of file. */
410 /* Clear the current line */
413 /* If there is no file open, bail out, otherwise get the current input file */
414 if (CollCount (&AFiles) == 0) {
417 Input = CollLast (&AFiles);
419 /* Read characters until we have one complete line */
422 /* Read the next character */
423 int C = fgetc (Input->F);
428 /* Accept files without a newline at the end */
429 if (SB_NotEmpty (Line)) {
434 /* Leave the current file */
437 /* If there is no file open, bail out, otherwise get the
438 * previous input file and start over.
440 if (CollCount (&AFiles) == 0) {
443 Input = CollLast (&AFiles);
447 /* Check for end of line */
450 /* We got a new line */
453 /* If the \n is preceeded by a \r, remove the \r, so we can read
454 * DOS/Windows files under *nix.
456 if (SB_LookAtLast (Line) == '\r') {
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.
464 if (SB_LookAtLast (Line) == '\\') {
465 Line->Buf[Line->Len-1] = '\n';
470 } else if (C != '\0') { /* Ignore embedded NULs */
472 /* Just some character, add it to the line */
473 SB_AppendChar (Line, C);
478 /* Add a termination character to the string buffer */
481 /* Initialize the current and next characters. */
484 /* Create line information for this line */
485 UpdateLineInfo (Input->Input, Input->Line, Line);
493 const char* GetCurrentFile (void)
494 /* Return the name of the current input file */
496 unsigned AFileCount = CollCount (&AFiles);
497 if (AFileCount > 0) {
498 const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
499 return AF->Input->Name;
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);
507 return "(outside file scope)";
514 unsigned GetCurrentLine (void)
515 /* Return the line number in the current input file */
517 unsigned AFileCount = CollCount (&AFiles);
518 if (AFileCount > 0) {
519 const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
529 void WriteDependencies (FILE* F, const char* OutputFile)
530 /* Write a makefile dependency list to the given file */
534 /* Get the number of input files */
535 unsigned IFileCount = CollCount (&IFiles);
537 /* Print the output file followed by a tab char */
538 fprintf (F, "%s:\t", OutputFile);
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);