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>
61 /*****************************************************************************/
63 /*****************************************************************************/
67 /* The current input line */
70 /* Current and next input character */
74 /* Maximum count of nested includes */
75 #define MAX_INC_NESTING 16
77 /* Struct that describes an input file */
78 typedef struct IFile IFile;
80 unsigned Index; /* File index */
81 unsigned Usage; /* Usage counter */
82 unsigned long Size; /* File size */
83 unsigned long MTime; /* Time of last modification */
84 InputType Type; /* Type of input file */
85 char Name[1]; /* Name of file (dynamically allocated) */
88 /* Struct that describes an active input file */
89 typedef struct AFile AFile;
91 unsigned Line; /* Line number for this file */
92 FILE* F; /* Input file stream */
93 IFile* Input; /* Points to corresponding IFile */
94 int SearchPath; /* True if we've added a path for this file */
97 /* List of all input files */
98 static Collection IFiles = STATIC_COLLECTION_INITIALIZER;
100 /* List of all active files */
101 static Collection AFiles = STATIC_COLLECTION_INITIALIZER;
103 /* Input stack used when preprocessing. */
104 static Collection InputStack = STATIC_COLLECTION_INITIALIZER;
108 /*****************************************************************************/
110 /*****************************************************************************/
114 static IFile* NewIFile (const char* Name, InputType Type)
115 /* Create and return a new IFile */
117 /* Get the length of the name */
118 unsigned Len = strlen (Name);
120 /* Allocate a IFile structure */
121 IFile* IF = (IFile*) xmalloc (sizeof (IFile) + Len);
123 /* Initialize the fields */
124 IF->Index = CollCount (&IFiles) + 1;
129 memcpy (IF->Name, Name, Len+1);
131 /* Insert the new structure into the IFile collection */
132 CollAppend (&IFiles, IF);
134 /* Return the new struct */
140 /*****************************************************************************/
142 /*****************************************************************************/
146 static AFile* NewAFile (IFile* IF, FILE* F)
147 /* Create a new AFile, push it onto the stack, add the path of the file to
148 * the path search list, and finally return a pointer to the new AFile struct.
151 StrBuf Path = AUTO_STRBUF_INITIALIZER;
153 /* Allocate a AFile structure */
154 AFile* AF = (AFile*) xmalloc (sizeof (AFile));
156 /* Initialize the fields */
161 /* Increment the usage counter of the corresponding IFile. If this
162 * is the first use, set the file data and output debug info if
165 if (IF->Usage++ == 0) {
167 /* Get file size and modification time. There a race condition here,
168 * since we cannot use fileno() (non standard identifier in standard
169 * header file), and therefore not fstat. When using stat with the
170 * file name, there's a risk that the file was deleted and recreated
171 * while it was open. Since mtime and size are only used to check
172 * if a file has changed in the debugger, we will ignore this problem
176 if (stat (IF->Name, &Buf) != 0) {
178 Fatal ("Cannot stat `%s': %s", IF->Name, strerror (errno));
180 IF->Size = (unsigned long) Buf.st_size;
181 IF->MTime = (unsigned long) Buf.st_mtime;
183 /* Set the debug data */
184 g_fileinfo (IF->Name, IF->Size, IF->MTime);
187 /* Insert the new structure into the AFile collection */
188 CollAppend (&AFiles, AF);
190 /* Get the path of this file and add it as an extra search path.
191 * To avoid file search overhead, we will add one path only once.
192 * This is checked by the PushSearchPath function.
194 SB_CopyBuf (&Path, IF->Name, FindName (IF->Name) - IF->Name);
195 SB_Terminate (&Path);
196 AF->SearchPath = PushSearchPath (UsrIncSearchPath, SB_GetConstBuf (&Path));
199 /* Return the new struct */
205 static void FreeAFile (AFile* AF)
206 /* Free an AFile structure */
213 /*****************************************************************************/
215 /*****************************************************************************/
219 static IFile* FindFile (const char* Name)
220 /* Find the file with the given name in the list of all files. Since the list
221 * is not large (usually less than 10), I don't care about using hashes or
222 * similar things and do a linear search.
226 for (I = 0; I < CollCount (&IFiles); ++I) {
227 /* Get the file struct */
228 IFile* IF = (IFile*) CollAt (&IFiles, I);
230 if (strcmp (Name, IF->Name) == 0) {
231 /* Found, return the struct */
242 void OpenMainFile (const char* Name)
243 /* Open the main file. Will call Fatal() in case of failures. */
248 /* Setup a new IFile structure for the main file */
249 IFile* IF = NewIFile (Name, IT_MAIN);
251 /* Open the file for reading */
252 FILE* F = fopen (Name, "r");
255 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
258 /* Allocate a new AFile structure for the file */
259 MainFile = NewAFile (IF, F);
261 /* Allocate the input line buffer */
264 /* Update the line infos, so we have a valid line info even at start of
265 * the main file before the first line is read.
267 UpdateLineInfo (MainFile->Input, MainFile->Line, Line);
272 void OpenIncludeFile (const char* Name, InputType IT)
273 /* Open an include file and insert it into the tables. */
279 /* Check for the maximum include nesting */
280 if (CollCount (&AFiles) > MAX_INC_NESTING) {
281 PPError ("Include nesting too deep");
285 /* Search for the file */
286 N = SearchFile ((IT == IT_SYSINC)? SysIncSearchPath : UsrIncSearchPath, Name);
288 PPError ("Include file `%s' not found", Name);
292 /* Search the list of all input files for this file. If we don't find
293 * it, create a new IFile object.
297 IF = NewIFile (N, IT);
300 /* We don't need N any longer, since we may now use IF->Name */
304 F = fopen (IF->Name, "r");
306 /* Error opening the file */
307 PPError ("Cannot open include file `%s': %s", IF->Name, strerror (errno));
311 /* Debugging output */
312 Print (stdout, 1, "Opened include file `%s'\n", IF->Name);
314 /* Allocate a new AFile structure */
315 (void) NewAFile (IF, F);
320 static void CloseIncludeFile (void)
321 /* Close an include file and switch to the higher level file. Set Input to
322 * NULL if this was the main file.
327 /* Get the number of active input files */
328 unsigned AFileCount = CollCount (&AFiles);
330 /* Must have an input file when called */
331 PRECONDITION (AFileCount > 0);
333 /* Get the current active input file */
334 Input = (AFile*) CollLast (&AFiles);
336 /* Close the current input file (we're just reading so no error check) */
339 /* Delete the last active file from the active file collection */
340 CollDelete (&AFiles, AFileCount-1);
342 /* If we had added an extra search path for this AFile, remove it */
343 if (Input->SearchPath) {
344 PopSearchPath (UsrIncSearchPath);
347 /* Delete the active file structure */
353 static void GetInputChar (void)
354 /* Read the next character from the input stream and make CurC and NextC
355 * valid. If end of line is reached, both are set to NUL, no more lines
356 * are read by this function.
359 /* Drop all pushed fragments that don't have data left */
360 while (SB_GetIndex (Line) >= SB_GetLen (Line)) {
361 /* Cannot read more from this line, check next line on stack if any */
362 if (CollCount (&InputStack) == 0) {
363 /* This is THE line */
367 Line = CollPop (&InputStack);
370 /* Now get the next characters from the line */
371 if (SB_GetIndex (Line) >= SB_GetLen (Line)) {
374 CurC = SB_AtUnchecked (Line, SB_GetIndex (Line));
375 if (SB_GetIndex (Line) + 1 < SB_GetLen (Line)) {
376 /* NextC comes from this fragment */
377 NextC = SB_AtUnchecked (Line, SB_GetIndex (Line) + 1);
379 /* NextC comes from next fragment */
380 if (CollCount (&InputStack) > 0) {
392 /* Skip the current input character and read the next one from the input
393 * stream. CurC and NextC are valid after the call. If end of line is
394 * reached, both are set to NUL, no more lines are read by this function.
397 /* Skip the last character read */
400 /* Read the next one */
406 void ClearLine (void)
407 /* Clear the current input line */
411 /* Remove all pushed fragments from the input stack */
412 for (I = 0; I < CollCount (&InputStack); ++I) {
413 FreeStrBuf (CollAtUnchecked (&InputStack, I));
415 CollDeleteAll (&InputStack);
417 /* Clear the contents of Line */
425 StrBuf* InitLine (StrBuf* Buf)
426 /* Initialize Line from Buf and read CurC and NextC from the new input line.
427 * The function returns the old input line.
430 StrBuf* OldLine = Line;
432 CurC = SB_LookAt (Buf, SB_GetIndex (Buf));
433 NextC = SB_LookAt (Buf, SB_GetIndex (Buf) + 1);
440 /* Get a line from the current input. Returns 0 on end of file. */
444 /* Clear the current line */
447 /* If there is no file open, bail out, otherwise get the current input file */
448 if (CollCount (&AFiles) == 0) {
451 Input = CollLast (&AFiles);
453 /* Read characters until we have one complete line */
456 /* Read the next character */
457 int C = fgetc (Input->F);
462 /* Accept files without a newline at the end */
463 if (SB_NotEmpty (Line)) {
468 /* Leave the current file */
471 /* If there is no file open, bail out, otherwise get the
472 * previous input file and start over.
474 if (CollCount (&AFiles) == 0) {
477 Input = CollLast (&AFiles);
481 /* Check for end of line */
484 /* We got a new line */
487 /* If the \n is preceeded by a \r, remove the \r, so we can read
488 * DOS/Windows files under *nix.
490 if (SB_LookAtLast (Line) == '\r') {
494 /* If we don't have a line continuation character at the end,
495 * we're done with this line. Otherwise replace the character
496 * by a newline and continue reading.
498 if (SB_LookAtLast (Line) == '\\') {
499 Line->Buf[Line->Len-1] = '\n';
504 } else if (C != '\0') { /* Ignore embedded NULs */
506 /* Just some character, add it to the line */
507 SB_AppendChar (Line, C);
512 /* Add a termination character to the string buffer */
515 /* Initialize the current and next characters. */
518 /* Create line information for this line */
519 UpdateLineInfo (Input->Input, Input->Line, Line);
527 const char* GetInputFile (const struct IFile* IF)
528 /* Return a filename from an IFile struct */
535 const char* GetCurrentFile (void)
536 /* Return the name of the current input file */
538 unsigned AFileCount = CollCount (&AFiles);
539 if (AFileCount > 0) {
540 const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
541 return AF->Input->Name;
543 /* No open file. Use the main file if we have one. */
544 unsigned IFileCount = CollCount (&IFiles);
545 if (IFileCount > 0) {
546 const IFile* IF = (const IFile*) CollAt (&IFiles, 0);
549 return "(outside file scope)";
556 unsigned GetCurrentLine (void)
557 /* Return the line number in the current input file */
559 unsigned AFileCount = CollCount (&AFiles);
560 if (AFileCount > 0) {
561 const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1);
571 static void WriteEscaped (FILE* F, const char* Name)
572 /* Write a file name to a dependency file escaping spaces */
586 static void WriteDep (FILE* F, InputType Types)
587 /* Helper function. Writes all file names that match Types to the output */
591 /* Loop over all files */
592 unsigned FileCount = CollCount (&IFiles);
593 for (I = 0; I < FileCount; ++I) {
595 /* Get the next input file */
596 const IFile* IF = (const IFile*) CollAt (&IFiles, I);
598 /* Ignore it if it is not of the correct type */
599 if ((IF->Type & Types) == 0) {
603 /* If this is not the first file, add a space */
608 /* Print the dependency escaping spaces */
609 WriteEscaped (F, IF->Name);
615 static void CreateDepFile (const char* Name, InputType Types)
616 /* Create a dependency file with the given name and place dependencies for
617 * all files with the given types there.
621 FILE* F = fopen (Name, "w");
623 Fatal ("Cannot open dependency file `%s': %s", Name, strerror (errno));
626 /* If a dependency target was given, use it, otherwise use the output
627 * file name as target, followed by a tab character.
629 if (SB_IsEmpty (&DepTarget)) {
630 WriteEscaped (F, OutputFilename);
632 WriteEscaped (F, SB_GetConstBuf (&DepTarget));
636 /* Write out the dependencies for the output file */
640 /* Write out a phony dependency for the included files */
644 /* Close the file, check for errors */
645 if (fclose (F) != 0) {
647 Fatal ("Cannot write to dependeny file (disk full?)");
653 void CreateDependencies (void)
654 /* Create dependency files requested by the user */
656 if (SB_NotEmpty (&DepName)) {
657 CreateDepFile (SB_GetConstBuf (&DepName),
658 IT_MAIN | IT_USRINC);
660 if (SB_NotEmpty (&FullDepName)) {
661 CreateDepFile (SB_GetConstBuf (&FullDepName),
662 IT_MAIN | IT_SYSINC | IT_USRINC);