fix __AROS_SETVECADDR invocations.
[AROS.git] / tools / cxref / cpp / cccp.c
blob030faa7b0f96ec08f8b369126d0e10db3b48fc2c
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92, 93, 94, 1995 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
6 Modified by Andrew M. Bishop to provide better input to
7 C documentation program `cxref' 1995,1996.
8 All AMB hacks are indicated as such in the code (grep AMB).
10 This program is free software; you can redistribute it and/or modify it
11 under the terms of the GNU General Public License as published by the
12 Free Software Foundation; either version 2, or (at your option) any
13 later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, 59 Temple Place - Suite 330,
23 Boston, MA 02111-1307, USA.
25 In other words, you are welcome to use, share and improve this program.
26 You are forbidden to forbid anyone else to use, share and improve
27 what you give them. Help stamp out software-hoarding! */
29 typedef unsigned char U_CHAR;
31 #ifdef EMACS
32 #define NO_SHORTNAMES
33 #include "../src/config.h"
34 #ifdef open
35 #undef open
36 #undef read
37 #undef write
38 #endif /* open */
39 #endif /* EMACS */
41 /* The macro EMACS is defined when cpp is distributed as part of Emacs,
42 for the sake of machines with limited C compilers. */
43 #ifndef EMACS
44 #include "config.h"
45 #endif /* not EMACS */
47 #ifndef STANDARD_INCLUDE_DIR
48 #define STANDARD_INCLUDE_DIR "/usr/include"
49 #endif
51 #ifndef LOCAL_INCLUDE_DIR
52 #define LOCAL_INCLUDE_DIR "/usr/local/include"
53 #endif
55 #if 0 /* We can't get ptrdiff_t, so I arranged not to need PTR_INT_TYPE. */
56 #ifdef __STDC__
57 #define PTR_INT_TYPE ptrdiff_t
58 #else
59 #define PTR_INT_TYPE long
60 #endif
61 #endif /* 0 */
63 #include "pcp.h"
65 /* By default, colon separates directories in a path. */
66 #ifndef PATH_SEPARATOR
67 #define PATH_SEPARATOR ':'
68 #endif
70 #include <sys/types.h>
71 #include <sys/stat.h>
72 #include <ctype.h>
73 #include <stdio.h>
74 #include <signal.h>
76 /* The following symbols should be autoconfigured:
77 HAVE_ALLOCA_H - already in autoconfig.h, but not used, added by AMB
78 HAVE_FCNTL_H
79 HAVE_STDLIB_H
80 HAVE_SYS_TIME_H
81 HAVE_UNISTD_H
82 STDC_HEADERS
83 TIME_WITH_SYS_TIME
84 In the mean time, we'll get by with approximations based
85 on existing GCC configuration symbols. */
87 #ifdef POSIX
88 # ifndef HAVE_STDLIB_H
89 # define HAVE_STDLIB_H 1
90 # endif
91 # ifndef HAVE_UNISTD_H
92 # define HAVE_UNISTD_H 1
93 # endif
94 # ifndef STDC_HEADERS
95 # define STDC_HEADERS 1
96 # endif
97 #endif /* defined (POSIX) */
99 #if defined (POSIX) || (defined (USG) && !defined (VMS))
100 # ifndef HAVE_FCNTL_H
101 # define HAVE_FCNTL_H 1
102 # endif
103 #endif
105 #ifndef RLIMIT_STACK
106 # include <time.h>
107 #else
108 # if TIME_WITH_SYS_TIME
109 # include <sys/time.h>
110 # include <time.h>
111 # else
112 # if HAVE_SYS_TIME_H
113 # include <sys/time.h>
114 # else
115 # include <time.h>
116 # endif
117 # endif
118 # include <sys/resource.h>
119 #endif
121 #if HAVE_FCNTL_H
122 # include <fcntl.h>
123 #endif
125 /* Start new include added by AMB */
127 #if HAVE_ALLOCA_H
128 # include <alloca.h>
129 #endif
131 /* End new include added by AMB */
133 /* This defines "errno" properly for VMS, and gives us EACCES. */
134 #include <errno.h>
136 #if HAVE_STDLIB_H
137 # include <stdlib.h>
138 #else
139 char *getenv ();
140 #endif
142 #if STDC_HEADERS
143 # include <string.h>
144 # ifndef bcmp
145 # define bcmp(a, b, n) memcmp (a, b, n)
146 # endif
147 # ifndef bcopy
148 # define bcopy(s, d, n) memcpy (d, s, n)
149 # endif
150 # ifndef bzero
151 # define bzero(d, n) memset (d, 0, n)
152 # endif
153 #else /* !STDC_HEADERS */
154 char *index ();
155 char *rindex ();
157 # if !defined (BSTRING) && (defined (USG) || defined (VMS))
159 # ifndef bcmp
160 # define bcmp my_bcmp
161 static int
162 my_bcmp (a, b, n)
163 register char *a;
164 register char *b;
165 register unsigned n;
167 while (n-- > 0)
168 if (*a++ != *b++)
169 return 1;
171 return 0;
173 # endif /* !defined (bcmp) */
175 # ifndef bcopy
176 # define bcopy my_bcopy
177 static void
178 my_bcopy (s, d, n)
179 register char *s;
180 register char *d;
181 register unsigned n;
183 while (n-- > 0)
184 *d++ = *s++;
186 # endif /* !defined (bcopy) */
188 # ifndef bzero
189 # define bzero my_bzero
190 static void
191 my_bzero (b, length)
192 register char *b;
193 register unsigned length;
195 while (length-- > 0)
196 *b++ = 0;
198 # endif /* !defined (bzero) */
200 # endif /* !defined (BSTRING) && (defined (USG) || defined (VMS)) */
201 #endif /* ! STDC_HEADERS */
203 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 6)
204 # define __attribute__(x)
205 #endif
207 #ifndef PROTO
208 # if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
209 # define PROTO(ARGS) ARGS
210 # else
211 # define PROTO(ARGS) ()
212 # endif
213 #endif
215 #if defined (__STDC__) && defined (HAVE_VPRINTF)
216 # include <stdarg.h>
217 # define VA_START(va_list, var) va_start (va_list, var)
218 # define PRINTF_ALIST(msg) char *msg, ...
219 # define PRINTF_DCL(msg)
220 # define PRINTF_PROTO(ARGS, m, n) PROTO (ARGS) __attribute__ ((format (printf, m, n)))
221 #else
222 # include <varargs.h>
223 # define VA_START(va_list, var) va_start (va_list)
224 # define PRINTF_ALIST(msg) msg, va_alist
225 # define PRINTF_DCL(msg) char *msg; va_dcl
226 # define PRINTF_PROTO(ARGS, m, n) () __attribute__ ((format (printf, m, n)))
227 # define vfprintf(file, msg, args) \
229 char *a0 = va_arg(args, char *); \
230 char *a1 = va_arg(args, char *); \
231 char *a2 = va_arg(args, char *); \
232 char *a3 = va_arg(args, char *); \
233 fprintf (file, msg, a0, a1, a2, a3); \
235 #endif
237 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
238 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
239 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
241 #if HAVE_UNISTD_H
242 # include <unistd.h>
243 #endif
245 /* VMS-specific definitions */
246 #ifdef VMS
247 #include <descrip.h>
248 #define O_RDONLY 0 /* Open arg for Read/Only */
249 #define O_WRONLY 1 /* Open arg for Write/Only */
250 #define read(fd,buf,size) VMS_read (fd,buf,size)
251 #define write(fd,buf,size) VMS_write (fd,buf,size)
252 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
253 #define fopen(fname,mode) VMS_fopen (fname,mode)
254 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
255 #define strncat(dst,src,cnt) VMS_strncat (dst,src,cnt)
256 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
257 static int VMS_fstat (), VMS_stat ();
258 static char * VMS_strncat ();
259 static int VMS_read ();
260 static int VMS_write ();
261 static int VMS_open ();
262 static FILE * VMS_fopen ();
263 static FILE * VMS_freopen ();
264 static void hack_vms_include_specification ();
265 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
266 #define ino_t vms_ino_t
267 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
268 #ifdef __GNUC__
269 #define BSTRING /* VMS/GCC supplies the bstring routines */
270 #endif /* __GNUC__ */
271 #endif /* VMS */
273 #ifndef O_RDONLY
274 #define O_RDONLY 0
275 #endif
277 #undef MIN
278 #undef MAX
279 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
280 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
282 /* Find the largest host integer type and set its size and type. */
284 #ifndef HOST_BITS_PER_WIDE_INT
286 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
287 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
288 #define HOST_WIDE_INT long
289 #else
290 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
291 #define HOST_WIDE_INT int
292 #endif
294 #endif
296 #ifndef S_ISREG
297 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
298 #endif
300 #ifndef S_ISDIR
301 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
302 #endif
304 /* Define a generic NULL if one hasn't already been defined. */
306 #ifndef NULL
307 #define NULL 0
308 #endif
310 #ifndef GENERIC_PTR
311 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
312 #define GENERIC_PTR void *
313 #else
314 #define GENERIC_PTR char *
315 #endif
316 #endif
318 #ifndef NULL_PTR
319 #define NULL_PTR ((GENERIC_PTR)0)
320 #endif
322 #ifndef INCLUDE_LEN_FUDGE
323 #define INCLUDE_LEN_FUDGE 0
324 #endif
326 /* External declarations. */
328 extern char *version_string;
329 #ifndef VMS
330 #ifndef HAVE_STRERROR
331 extern int sys_nerr;
332 #if defined(bsd4_4)
333 extern const char *const sys_errlist[];
334 #else
335 extern char *sys_errlist[];
336 #endif
337 #else /* HAVE_STRERROR */
338 char *strerror ();
339 #endif
340 #else /* VMS */
341 char *strerror (int,...);
342 #endif
343 int parse_escape PROTO((char **));
344 HOST_WIDE_INT parse_c_expression PROTO((char *));
346 #ifndef errno
347 extern int errno;
348 #endif
350 /* Name under which this program was invoked. */
352 static char *progname;
354 /* Nonzero means use extra default include directories for C++. */
356 static int cplusplus;
358 /* Nonzero means handle cplusplus style comments */
360 static int cplusplus_comments;
362 /* Nonzero means handle #import, for objective C. */
364 static int objc;
366 /* Nonzero means this is an assembly file, and allow
367 unknown directives, which could be comments. */
369 static int lang_asm;
371 /* Current maximum length of directory names in the search path
372 for include files. (Altered as we get more of them.) */
374 static int max_include_len;
376 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
378 static int for_lint = 0;
380 /* Nonzero means copy comments into the output file. */
382 static int put_out_comments = 0;
384 /* Nonzero means don't process the ANSI trigraph sequences. */
386 static int no_trigraphs = 0;
388 /* Nonzero means print the names of included files rather than
389 the preprocessed output. 1 means just the #include "...",
390 2 means #include <...> as well. */
392 static int print_deps = 0;
394 /* Nonzero if missing .h files in -M output are assumed to be generated
395 files and not errors. */
397 static int print_deps_missing_files = 0;
399 /* Nonzero means print names of header files (-H). */
401 static int print_include_names = 0;
403 /* Nonzero means don't output line number information. */
405 static int no_line_directives;
407 /* Nonzero means output the text in failing conditionals,
408 inside #failed ... #endfailed. */
410 static int output_conditionals;
412 /* dump_only means inhibit output of the preprocessed text
413 and instead output the definitions of all user-defined
414 macros in a form suitable for use as input to cccp.
415 dump_names means pass #define and the macro name through to output.
416 dump_definitions means pass the whole definition (plus #define) through
419 static enum {dump_none, dump_only, dump_names, dump_definitions}
420 dump_macros = dump_none;
422 /* Start new option added by AMB */
424 /* Nonzero means that the #include lines are to be passed through to
425 output.
428 static int dump_includes = 0;
430 /* End new option added by AMB */
432 /* Nonzero means pass all #define and #undef directives which we actually
433 process through to the output stream. This feature is used primarily
434 to allow cc1 to record the #defines and #undefs for the sake of
435 debuggers which understand about preprocessor macros, but it may
436 also be useful with -E to figure out how symbols are defined, and
437 where they are defined. */
438 static int debug_output = 0;
440 /* Nonzero indicates special processing used by the pcp program. The
441 special effects of this mode are:
443 Inhibit all macro expansion, except those inside #if directives.
445 Process #define directives normally, and output their contents
446 to the output file.
448 Output preconditions to pcp_outfile indicating all the relevant
449 preconditions for use of this file in a later cpp run.
451 static FILE *pcp_outfile;
453 /* Nonzero means we are inside an IF during a -pcp run. In this mode
454 macro expansion is done, and preconditions are output for all macro
455 uses requiring them. */
456 static int pcp_inside_if;
458 /* Nonzero means never to include precompiled files.
459 This is 1 since there's no way now to make precompiled files,
460 so it's not worth testing for them. */
461 static int no_precomp = 1;
463 /* Nonzero means give all the error messages the ANSI standard requires. */
465 int pedantic;
467 /* Nonzero means try to make failure to fit ANSI C an error. */
469 static int pedantic_errors;
471 /* Nonzero means don't print warning messages. -w. */
473 static int inhibit_warnings = 0;
475 /* Nonzero means warn if slash-star appears in a comment. */
477 static int warn_comments;
479 /* Nonzero means warn if a macro argument is (or would be)
480 stringified with -traditional. */
482 static int warn_stringify;
484 /* Nonzero means warn if there are any trigraphs. */
486 static int warn_trigraphs;
488 /* Nonzero means warn if #import is used. */
490 static int warn_import = 1;
492 /* Nonzero means turn warnings into errors. */
494 static int warnings_are_errors;
496 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
498 int traditional;
500 /* Nonzero causes output not to be done,
501 but directives such as #define that have side effects
502 are still obeyed. */
504 static int no_output;
506 /* Nonzero means this file was included with a -imacros or -include
507 command line and should not be recorded as an include file. */
509 static int no_record_file;
511 /* Nonzero means that we have finished processing the command line options.
512 This flag is used to decide whether or not to issue certain errors
513 and/or warnings. */
515 static int done_initializing = 0;
517 /* Line where a newline was first seen in a string constant. */
519 static int multiline_string_line = 0;
521 /* I/O buffer structure.
522 The `fname' field is nonzero for source files and #include files
523 and for the dummy text used for -D and -U.
524 It is zero for rescanning results of macro expansion
525 and for expanding macro arguments. */
526 #define INPUT_STACK_MAX 400
527 static struct file_buf {
528 char *fname;
529 /* Filename specified with #line directive. */
530 char *nominal_fname;
531 /* Record where in the search path this file was found.
532 For #include_next. */
533 struct file_name_list *dir;
534 int lineno;
535 int length;
536 U_CHAR *buf;
537 U_CHAR *bufp;
538 /* Macro that this level is the expansion of.
539 Included so that we can reenable the macro
540 at the end of this level. */
541 struct hashnode *macro;
542 /* Value of if_stack at start of this file.
543 Used to prohibit unmatched #endif (etc) in an include file. */
544 struct if_stack *if_stack;
545 /* Object to be freed at end of input at this level. */
546 U_CHAR *free_ptr;
547 /* True if this is a header file included using <FILENAME>. */
548 char system_header_p;
549 } instack[INPUT_STACK_MAX];
551 static int last_error_tick; /* Incremented each time we print it. */
552 static int input_file_stack_tick; /* Incremented when the status changes. */
554 /* Current nesting level of input sources.
555 `instack[indepth]' is the level currently being read. */
556 static int indepth = -1;
557 #define CHECK_DEPTH(code) \
558 if (indepth >= (INPUT_STACK_MAX - 1)) \
560 error_with_line (line_for_error (instack[indepth].lineno), \
561 "macro or `#include' recursion too deep"); \
562 code; \
565 /* Current depth in #include directives that use <...>. */
566 static int system_include_depth = 0;
568 typedef struct file_buf FILE_BUF;
570 /* The output buffer. Its LENGTH field is the amount of room allocated
571 for the buffer, not the number of chars actually present. To get
572 that, subtract outbuf.buf from outbuf.bufp. */
574 #define OUTBUF_SIZE 10 /* initial size of output buffer */
575 static FILE_BUF outbuf;
577 /* Grow output buffer OBUF points at
578 so it can hold at least NEEDED more chars. */
580 #define check_expand(OBUF, NEEDED) \
581 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
582 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
584 struct file_name_list
586 struct file_name_list *next;
587 char *fname;
588 /* If the following is nonzero, it is a macro name.
589 Don't include the file again if that macro is defined. */
590 U_CHAR *control_macro;
591 /* If the following is nonzero, it is a C-language system include
592 directory. */
593 int c_system_include_path;
594 /* Mapping of file names for this directory. */
595 struct file_name_map *name_map;
596 /* Non-zero if name_map is valid. */
597 int got_name_map;
600 /* #include "file" looks in source file dir, then stack. */
601 /* #include <file> just looks in the stack. */
602 /* -I directories are added to the end, then the defaults are added. */
603 /* The */
604 static struct default_include {
605 char *fname; /* The name of the directory. */
606 int cplusplus; /* Only look here if we're compiling C++. */
607 int cxx_aware; /* Includes in this directory don't need to
608 be wrapped in extern "C" when compiling
609 C++. */
610 } include_defaults_array[]
611 #ifdef INCLUDE_DEFAULTS
612 = INCLUDE_DEFAULTS;
613 #else
615 /* Pick up GNU C++ specific include files. */
616 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
617 #ifdef CROSS_COMPILE
618 /* This is the dir for fixincludes. Put it just before
619 the files that we fix. */
620 { GCC_INCLUDE_DIR, 0, 0 },
621 /* For cross-compilation, this dir name is generated
622 automatically in Makefile.in. */
623 { CROSS_INCLUDE_DIR, 0, 0 },
624 /* This is another place that the target system's headers might be. */
625 { TOOL_INCLUDE_DIR, 0, 0 },
626 #else /* not CROSS_COMPILE */
627 /* This should be /usr/local/include and should come before
628 the fixincludes-fixed header files. */
629 { LOCAL_INCLUDE_DIR, 0, 1 },
630 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
631 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
632 { TOOL_INCLUDE_DIR, 0, 0 },
633 /* This is the dir for fixincludes. Put it just before
634 the files that we fix. */
635 { GCC_INCLUDE_DIR, 0, 0 },
636 /* Some systems have an extra dir of include files. */
637 #ifdef SYSTEM_INCLUDE_DIR
638 { SYSTEM_INCLUDE_DIR, 0, 0 },
639 #endif
640 { STANDARD_INCLUDE_DIR, 0, 0 },
641 #endif /* not CROSS_COMPILE */
642 { 0, 0, 0 }
644 #endif /* no INCLUDE_DEFAULTS */
646 /* The code looks at the defaults through this pointer, rather than through
647 the constant structure above. This pointer gets changed if an environment
648 variable specifies other defaults. */
649 static struct default_include *include_defaults = include_defaults_array;
651 static struct file_name_list *include = 0; /* First dir to search */
652 /* First dir to search for <file> */
653 /* This is the first element to use for #include <...>.
654 If it is 0, use the entire chain for such includes. */
655 static struct file_name_list *first_bracket_include = 0;
656 /* This is the first element in the chain that corresponds to
657 a directory of system header files. */
658 static struct file_name_list *first_system_include = 0;
659 static struct file_name_list *last_include = 0; /* Last in chain */
661 /* Chain of include directories to put at the end of the other chain. */
662 static struct file_name_list *after_include = 0;
663 static struct file_name_list *last_after_include = 0; /* Last in chain */
665 /* Chain to put at the start of the system include files. */
666 static struct file_name_list *before_system = 0;
667 static struct file_name_list *last_before_system = 0; /* Last in chain */
669 /* List of included files that contained #pragma once. */
670 static struct file_name_list *dont_repeat_files = 0;
672 /* List of other included files.
673 If ->control_macro if nonzero, the file had a #ifndef
674 around the entire contents, and ->control_macro gives the macro name. */
675 static struct file_name_list *all_include_files = 0;
677 /* Directory prefix that should replace `/usr' in the standard
678 include file directories. */
679 static char *include_prefix;
681 /* Global list of strings read in from precompiled files. This list
682 is kept in the order the strings are read in, with new strings being
683 added at the end through stringlist_tailp. We use this list to output
684 the strings at the end of the run.
686 static STRINGDEF *stringlist;
687 static STRINGDEF **stringlist_tailp = &stringlist;
690 /* Structure returned by create_definition */
691 typedef struct macrodef MACRODEF;
692 struct macrodef
694 struct definition *defn;
695 U_CHAR *symnam;
696 int symlen;
699 enum sharp_token_type {
700 NO_SHARP_TOKEN = 0, /* token not present */
702 SHARP_TOKEN = '#', /* token spelled with # only */
703 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
705 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
706 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
709 /* Structure allocated for every #define. For a simple replacement
710 such as
711 #define foo bar ,
712 nargs = -1, the `pattern' list is null, and the expansion is just
713 the replacement text. Nargs = 0 means a functionlike macro with no args,
714 e.g.,
715 #define getchar() getc (stdin) .
716 When there are args, the expansion is the replacement text with the
717 args squashed out, and the reflist is a list describing how to
718 build the output from the input: e.g., "3 chars, then the 1st arg,
719 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
720 The chars here come from the expansion. Whatever is left of the
721 expansion after the last arg-occurrence is copied after that arg.
722 Note that the reflist can be arbitrarily long---
723 its length depends on the number of times the arguments appear in
724 the replacement text, not how many args there are. Example:
725 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
726 pattern list
727 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
728 where (x, y) means (nchars, argno). */
730 typedef struct definition DEFINITION;
731 struct definition {
732 int nargs;
733 int length; /* length of expansion string */
734 int predefined; /* True if the macro was builtin or */
735 /* came from the command line */
736 U_CHAR *expansion;
737 int line; /* Line number of definition */
738 char *file; /* File of definition */
739 char rest_args; /* Nonzero if last arg. absorbs the rest */
740 struct reflist {
741 struct reflist *next;
743 enum sharp_token_type stringify; /* set if a # operator before arg */
744 enum sharp_token_type raw_before; /* set if a ## operator before arg */
745 enum sharp_token_type raw_after; /* set if a ## operator after arg */
747 char rest_args; /* Nonzero if this arg. absorbs the rest */
748 int nchars; /* Number of literal chars to copy before
749 this arg occurrence. */
750 int argno; /* Number of arg to substitute (origin-0) */
751 } *pattern;
752 union {
753 /* Names of macro args, concatenated in reverse order
754 with comma-space between them.
755 The only use of this is that we warn on redefinition
756 if this differs between the old and new definitions. */
757 U_CHAR *argnames;
758 } args;
761 /* different kinds of things that can appear in the value field
762 of a hash node. Actually, this may be useless now. */
763 union hashval {
764 char *cpval;
765 DEFINITION *defn;
766 KEYDEF *keydef;
770 * special extension string that can be added to the last macro argument to
771 * allow it to absorb the "rest" of the arguments when expanded. Ex:
772 * #define wow(a, b...) process (b, a, b)
773 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
774 * { wow (one, two); } -> { process (two, one, two); }
775 * if this "rest_arg" is used with the concat token '##' and if it is not
776 * supplied then the token attached to with ## will not be outputted. Ex:
777 * #define wow (a, b...) process (b ## , a, ## b)
778 * { wow (1, 2); } -> { process (2, 1, 2); }
779 * { wow (one); } -> { process (one); {
781 static char rest_extension[] = "...";
782 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
784 /* The structure of a node in the hash table. The hash table
785 has entries for all tokens defined by #define directives (type T_MACRO),
786 plus some special tokens like __LINE__ (these each have their own
787 type, and the appropriate code is run when that type of node is seen.
788 It does not contain control words like "#define", which are recognized
789 by a separate piece of code. */
791 /* different flavors of hash nodes --- also used in keyword table */
792 enum node_type {
793 T_DEFINE = 1, /* the `#define' keyword */
794 T_INCLUDE, /* the `#include' keyword */
795 T_INCLUDE_NEXT, /* the `#include_next' keyword */
796 T_IMPORT, /* the `#import' keyword */
797 T_IFDEF, /* the `#ifdef' keyword */
798 T_IFNDEF, /* the `#ifndef' keyword */
799 T_IF, /* the `#if' keyword */
800 T_ELSE, /* `#else' */
801 T_PRAGMA, /* `#pragma' */
802 T_ELIF, /* `#elif' */
803 T_UNDEF, /* `#undef' */
804 T_LINE, /* `#line' */
805 T_ERROR, /* `#error' */
806 T_WARNING, /* `#warning' */
807 T_ENDIF, /* `#endif' */
808 T_SCCS, /* `#sccs', used on system V. */
809 T_IDENT, /* `#ident', used on system V. */
810 T_ASSERT, /* `#assert', taken from system V. */
811 T_UNASSERT, /* `#unassert', taken from system V. */
812 T_SPECLINE, /* special symbol `__LINE__' */
813 T_DATE, /* `__DATE__' */
814 T_FILE, /* `__FILE__' */
815 T_BASE_FILE, /* `__BASE_FILE__' */
816 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
817 T_VERSION, /* `__VERSION__' */
818 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
819 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
820 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
821 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
822 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
823 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
824 T_TIME, /* `__TIME__' */
825 T_CONST, /* Constant value, used by `__STDC__' */
826 T_MACRO, /* macro defined by `#define' */
827 T_DISABLED, /* macro temporarily turned off for rescan */
828 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
829 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
830 T_UNUSED /* Used for something not defined. */
833 struct hashnode {
834 struct hashnode *next; /* double links for easy deletion */
835 struct hashnode *prev;
836 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
837 chain is kept, in case the node is the head
838 of the chain and gets deleted. */
839 enum node_type type; /* type of special token */
840 int length; /* length of token, for quick comparison */
841 U_CHAR *name; /* the actual name */
842 union hashval value; /* pointer to expansion, or whatever */
845 typedef struct hashnode HASHNODE;
847 /* Some definitions for the hash table. The hash function MUST be
848 computed as shown in hashf () below. That is because the rescan
849 loop computes the hash value `on the fly' for most tokens,
850 in order to avoid the overhead of a lot of procedure calls to
851 the hashf () function. Hashf () only exists for the sake of
852 politeness, for use when speed isn't so important. */
854 #define HASHSIZE 1403
855 static HASHNODE *hashtab[HASHSIZE];
856 #define HASHSTEP(old, c) ((old << 2) + c)
857 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
859 /* Symbols to predefine. */
861 #ifdef CPP_PREDEFINES
862 static char *predefs = CPP_PREDEFINES;
863 #else
864 static char *predefs = "";
865 #endif
867 /* We let tm.h override the types used here, to handle trivial differences
868 such as the choice of unsigned int or long unsigned int for size_t.
869 When machines start needing nontrivial differences in the size type,
870 it would be best to do something here to figure out automatically
871 from other information what type to use. */
873 /* The string value for __SIZE_TYPE__. */
875 #ifndef SIZE_TYPE
876 #define SIZE_TYPE "long unsigned int"
877 #endif
879 /* The string value for __PTRDIFF_TYPE__. */
881 #ifndef PTRDIFF_TYPE
882 #define PTRDIFF_TYPE "long int"
883 #endif
885 /* The string value for __WCHAR_TYPE__. */
887 #ifndef WCHAR_TYPE
888 #define WCHAR_TYPE "int"
889 #endif
890 char * wchar_type = WCHAR_TYPE;
891 #undef WCHAR_TYPE
893 /* The string value for __USER_LABEL_PREFIX__ */
895 #ifndef USER_LABEL_PREFIX
896 #define USER_LABEL_PREFIX ""
897 #endif
899 /* The string value for __REGISTER_PREFIX__ */
901 #ifndef REGISTER_PREFIX
902 #define REGISTER_PREFIX ""
903 #endif
905 /* The string value for __IMMEDIATE_PREFIX__ */
907 #ifndef IMMEDIATE_PREFIX
908 #define IMMEDIATE_PREFIX ""
909 #endif
911 /* In the definition of a #assert name, this structure forms
912 a list of the individual values asserted.
913 Each value is itself a list of "tokens".
914 These are strings that are compared by name. */
916 struct tokenlist_list {
917 struct tokenlist_list *next;
918 struct arglist *tokens;
921 struct assertion_hashnode {
922 struct assertion_hashnode *next; /* double links for easy deletion */
923 struct assertion_hashnode *prev;
924 /* also, a back pointer to this node's hash
925 chain is kept, in case the node is the head
926 of the chain and gets deleted. */
927 struct assertion_hashnode **bucket_hdr;
928 int length; /* length of token, for quick comparison */
929 U_CHAR *name; /* the actual name */
930 /* List of token-sequences. */
931 struct tokenlist_list *value;
934 typedef struct assertion_hashnode ASSERTION_HASHNODE;
936 /* Some definitions for the hash table. The hash function MUST be
937 computed as shown in hashf below. That is because the rescan
938 loop computes the hash value `on the fly' for most tokens,
939 in order to avoid the overhead of a lot of procedure calls to
940 the hashf function. hashf only exists for the sake of
941 politeness, for use when speed isn't so important. */
943 #define ASSERTION_HASHSIZE 37
944 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
946 /* Nonzero means inhibit macroexpansion of what seem to be
947 assertion tests, in rescan. For #if. */
948 static int assertions_flag;
950 /* `struct directive' defines one #-directive, including how to handle it. */
952 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
954 struct directive {
955 int length; /* Length of name */
956 int (*func) DO_PROTO; /* Function to handle directive */
957 char *name; /* Name of directive */
958 enum node_type type; /* Code which describes which directive. */
959 char angle_brackets; /* Nonzero => <...> is special. */
960 char traditional_comments; /* Nonzero: keep comments if -traditional. */
961 char pass_thru; /* Copy preprocessed directive to output file. */
964 /* These functions are declared to return int instead of void since they
965 are going to be placed in the table and some old compilers have trouble with
966 pointers to functions returning void. */
968 static int do_assert DO_PROTO;
969 static int do_define DO_PROTO;
970 static int do_elif DO_PROTO;
971 static int do_else DO_PROTO;
972 static int do_endif DO_PROTO;
973 static int do_error DO_PROTO;
974 static int do_ident DO_PROTO;
975 static int do_if DO_PROTO;
976 static int do_include DO_PROTO;
977 static int do_line DO_PROTO;
978 static int do_pragma DO_PROTO;
979 #ifdef SCCS_DIRECTIVE
980 static int do_sccs DO_PROTO;
981 #endif
982 static int do_unassert DO_PROTO;
983 static int do_undef DO_PROTO;
984 static int do_warning DO_PROTO;
985 static int do_xifdef DO_PROTO;
987 /* Here is the actual list of #-directives, most-often-used first. */
989 static struct directive directive_table[] = {
990 { 6, do_define, "define", T_DEFINE, 0, 1, 1}, /* The last 1 is in future cccp.c added by AMB. */
991 { 2, do_if, "if", T_IF},
992 { 5, do_xifdef, "ifdef", T_IFDEF},
993 { 6, do_xifdef, "ifndef", T_IFNDEF},
994 { 5, do_endif, "endif", T_ENDIF},
995 { 4, do_else, "else", T_ELSE},
996 { 4, do_elif, "elif", T_ELIF},
997 { 4, do_line, "line", T_LINE},
998 { 7, do_include, "include", T_INCLUDE, 1},
999 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
1000 { 6, do_include, "import", T_IMPORT, 1},
1001 { 5, do_undef, "undef", T_UNDEF},
1002 { 5, do_error, "error", T_ERROR},
1003 { 7, do_warning, "warning", T_WARNING},
1004 #ifdef SCCS_DIRECTIVE
1005 { 4, do_sccs, "sccs", T_SCCS},
1006 #endif
1007 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
1008 { 5, do_ident, "ident", T_IDENT},
1009 { 6, do_assert, "assert", T_ASSERT},
1010 { 8, do_unassert, "unassert", T_UNASSERT},
1011 { -1, 0, "", T_UNUSED},
1014 /* When a directive handler is called,
1015 this points to the # (or the : of the %:) that started the directive. */
1016 U_CHAR *directive_start;
1018 /* table to tell if char can be part of a C identifier. */
1019 U_CHAR is_idchar[256];
1020 /* table to tell if char can be first char of a c identifier. */
1021 U_CHAR is_idstart[256];
1022 /* table to tell if c is horizontal space. */
1023 U_CHAR is_hor_space[256];
1024 /* table to tell if c is horizontal or vertical space. */
1025 static U_CHAR is_space[256];
1026 /* names of some characters */
1027 static char *char_name[256];
1029 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
1030 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
1032 static int errors = 0; /* Error counter for exit code */
1034 /* Name of output file, for error messages. */
1035 static char *out_fname;
1037 /* Zero means dollar signs are punctuation.
1038 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
1039 This must be 0 for correct processing of this ANSI C program:
1040 #define foo(a) #a
1041 #define lose(b) foo (b)
1042 #define test$
1043 lose (test) */
1044 static int dollars_in_ident;
1045 #ifndef DOLLARS_IN_IDENTIFIERS
1046 #define DOLLARS_IN_IDENTIFIERS 1
1047 #endif
1050 /* Stack of conditionals currently in progress
1051 (including both successful and failing conditionals). */
1053 struct if_stack {
1054 struct if_stack *next; /* for chaining to the next stack frame */
1055 char *fname; /* copied from input when frame is made */
1056 int lineno; /* similarly */
1057 int if_succeeded; /* true if a leg of this if-group
1058 has been passed through rescan */
1059 U_CHAR *control_macro; /* For #ifndef at start of file,
1060 this is the macro name tested. */
1061 enum node_type type; /* type of last directive seen in this group */
1063 typedef struct if_stack IF_STACK_FRAME;
1064 static IF_STACK_FRAME *if_stack = NULL;
1066 /* Buffer of -M output. */
1067 static char *deps_buffer;
1069 /* Number of bytes allocated in above. */
1070 static int deps_allocated_size;
1072 /* Number of bytes used. */
1073 static int deps_size;
1075 /* Number of bytes since the last newline. */
1076 static int deps_column;
1078 /* Nonzero means -I- has been seen,
1079 so don't look for #include "foo" the source-file directory. */
1080 static int ignore_srcdir;
1082 static int safe_read PROTO((int, char *, int));
1083 static void safe_write PROTO((int, char *, int));
1085 int main PROTO((int, char **));
1087 static void path_include PROTO((char *));
1089 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
1091 static void trigraph_pcp PROTO((FILE_BUF *));
1093 static void newline_fix PROTO((U_CHAR *));
1094 static void name_newline_fix PROTO((U_CHAR *));
1096 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
1098 static void rescan PROTO((FILE_BUF *, int));
1100 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
1102 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1104 static struct tm *timestamp PROTO((void));
1105 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1107 static int redundant_include_p PROTO((char *));
1108 static int is_system_include PROTO((char *));
1109 static char *skip_redundant_dir_prefix PROTO((char *));
1111 static char *read_filename_string PROTO((int, FILE *));
1112 static struct file_name_map *read_name_map PROTO((char *));
1113 static int open_include_file PROTO((char *, struct file_name_list *));
1115 static void finclude PROTO((int, char *, FILE_BUF *, int, struct file_name_list *));
1116 static void record_control_macro PROTO((char *, U_CHAR *));
1118 static int import_hash PROTO((char *));
1119 static int lookup_import PROTO((char *, struct file_name_list *));
1120 static void add_import PROTO((int, char *));
1122 static char *check_precompiled PROTO((int, char *, char **));
1123 static int check_preconditions PROTO((char *));
1124 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1125 static void pcstring_used PROTO((HASHNODE *));
1126 static void write_output PROTO((void));
1127 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1129 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1131 static int check_macro_name PROTO((U_CHAR *, char *));
1132 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1133 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1135 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1137 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1138 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1140 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1141 static void free_token_list PROTO((struct arglist *));
1143 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1144 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1145 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1147 static void do_once PROTO((void));
1149 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1150 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1151 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1152 static void validate_else PROTO((U_CHAR *));
1154 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1155 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1156 static char *quote_string PROTO((char *, char *));
1157 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1159 /* Last arg to output_line_directive. */
1160 enum file_change_code {same_file, enter_file, leave_file};
1161 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1163 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1165 struct argdata;
1166 static char *macarg PROTO((struct argdata *, int));
1168 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1170 static int discard_comments PROTO((U_CHAR *, int, int));
1172 static int change_newlines PROTO((U_CHAR *, int));
1174 char *my_strerror PROTO((int));
1175 void error PRINTF_PROTO_1((char *, ...));
1176 static void verror PROTO((char *, va_list));
1177 static void error_from_errno PROTO((char *));
1178 void warning PRINTF_PROTO_1((char *, ...));
1179 static void vwarning PROTO((char *, va_list));
1180 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1181 static void verror_with_line PROTO((int, char *, va_list));
1182 static void vwarning_with_line PROTO((int, char *, va_list));
1183 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1184 void pedwarn PRINTF_PROTO_1((char *, ...));
1185 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1186 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1188 static void print_containing_files PROTO((void));
1190 static int line_for_error PROTO((int));
1191 static int grow_outbuf PROTO((FILE_BUF *, int));
1193 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1194 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1195 static void delete_macro PROTO((HASHNODE *));
1196 static int hashf PROTO((U_CHAR *, int, int));
1198 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1199 static void dump_all_macros PROTO((void));
1200 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1201 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1203 static void initialize_char_syntax PROTO((void));
1204 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1206 static void make_definition PROTO((char *, FILE_BUF *));
1207 static void make_undef PROTO((char *, FILE_BUF *));
1209 static void make_assertion PROTO((char *, char *));
1211 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1213 static void deps_output PROTO((char *, int));
1215 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1216 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1217 static void perror_with_name PROTO((char *));
1218 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1219 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1221 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1222 GENERIC_PTR xmalloc PROTO((size_t));
1223 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1224 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1225 static char *savestring PROTO((char *));
1227 static int file_size_and_mode PROTO((int, int *, long int *));
1229 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1230 retrying if necessary. Return a negative value if an error occurs,
1231 otherwise return the actual number of bytes read,
1232 which must be LEN unless end-of-file was reached. */
1234 static int
1235 safe_read (desc, ptr, len)
1236 int desc;
1237 char *ptr;
1238 int len;
1240 int left = len;
1241 while (left > 0) {
1242 int nchars = read (desc, ptr, left);
1243 if (nchars < 0)
1245 #ifdef EINTR
1246 if (errno == EINTR)
1247 continue;
1248 #endif
1249 return nchars;
1251 if (nchars == 0)
1252 break;
1253 ptr += nchars;
1254 left -= nchars;
1256 return len - left;
1259 /* Write LEN bytes at PTR to descriptor DESC,
1260 retrying if necessary, and treating any real error as fatal. */
1262 static void
1263 safe_write (desc, ptr, len)
1264 int desc;
1265 char *ptr;
1266 int len;
1268 while (len > 0) {
1269 int written = write (desc, ptr, len);
1270 if (written < 0)
1272 #ifdef EINTR
1273 if (errno == EINTR)
1274 continue;
1275 #endif
1276 pfatal_with_name (out_fname);
1278 ptr += written;
1279 len -= written;
1284 main (argc, argv)
1285 int argc;
1286 char **argv;
1288 int st_mode;
1289 long st_size;
1290 char *in_fname;
1291 char *cp;
1292 int f, i;
1293 FILE_BUF *fp;
1294 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1295 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1296 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1297 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1298 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1300 /* Record the option used with each element of pend_assertions.
1301 This is preparation for supporting more than one option for making
1302 an assertion. */
1303 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1304 int inhibit_predefs = 0;
1305 int no_standard_includes = 0;
1306 int no_standard_cplusplus_includes = 0;
1307 int missing_newline = 0;
1309 /* Non-0 means don't output the preprocessed program. */
1310 int inhibit_output = 0;
1311 /* Non-0 means -v, so print the full set of include dirs. */
1312 int verbose = 0;
1314 /* File name which deps are being written to.
1315 This is 0 if deps are being written to stdout. */
1316 char *deps_file = 0;
1317 /* Fopen file mode to open deps_file with. */
1318 char *deps_mode = "a";
1319 /* Stream on which to print the dependency information. */
1320 FILE *deps_stream = 0;
1321 /* Target-name to write with the dependency information. */
1322 char *deps_target = 0;
1324 #ifdef RLIMIT_STACK
1325 /* Get rid of any avoidable limit on stack size. */
1327 struct rlimit rlim;
1329 /* Set the stack limit huge so that alloca (particularly stringtab
1330 * in dbxread.c) does not fail. */
1331 getrlimit (RLIMIT_STACK, &rlim);
1332 rlim.rlim_cur = rlim.rlim_max;
1333 setrlimit (RLIMIT_STACK, &rlim);
1335 #endif /* RLIMIT_STACK defined */
1337 #ifdef SIGPIPE
1338 signal (SIGPIPE, pipe_closed);
1339 #endif
1341 cp = argv[0] + strlen (argv[0]);
1342 while (cp != argv[0] && cp[-1] != '/'
1343 #ifdef DIR_SEPARATOR
1344 && cp[-1] != DIR_SEPARATOR
1345 #endif
1347 --cp;
1348 progname = cp;
1350 #ifdef VMS
1352 /* Remove directories from PROGNAME. */
1353 char *p;
1354 char *s = progname;
1356 if ((p = rindex (s, ':')) != 0) s = p + 1; /* skip device */
1357 if ((p = rindex (s, ']')) != 0) s = p + 1; /* skip directory */
1358 if ((p = rindex (s, '>')) != 0) s = p + 1; /* alternate (int'n'l) dir */
1359 s = progname = savestring (s);
1360 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1361 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1362 && (p[1] == 'e' || p[1] == 'E')
1363 && (p[2] == 'x' || p[2] == 'X')
1364 && (p[3] == 'e' || p[3] == 'E')
1365 && !p[4])
1366 *p = '\0';
1368 #endif
1370 in_fname = NULL;
1371 out_fname = NULL;
1373 /* Initialize is_idchar to allow $. */
1374 dollars_in_ident = 1;
1375 initialize_char_syntax ();
1376 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1378 no_line_directives = 0;
1379 no_trigraphs = 1;
1380 dump_macros = dump_none;
1381 /* Start new option added by AMB */
1382 dump_includes = 0;
1383 /* End new option added by AMB */
1384 no_output = 0;
1385 cplusplus = 0;
1386 cplusplus_comments = 1;
1388 bzero ((char *) pend_files, argc * sizeof (char *));
1389 bzero ((char *) pend_defs, argc * sizeof (char *));
1390 bzero ((char *) pend_undefs, argc * sizeof (char *));
1391 bzero ((char *) pend_assertions, argc * sizeof (char *));
1392 bzero ((char *) pend_includes, argc * sizeof (char *));
1394 /* Process switches and find input file name. */
1396 for (i = 1; i < argc; i++) {
1397 if (argv[i][0] != '-') {
1398 if (out_fname != NULL)
1399 fatal ("Usage: %s [switches] input output", argv[0]);
1400 else if (in_fname != NULL)
1401 out_fname = argv[i];
1402 else
1403 in_fname = argv[i];
1404 } else {
1405 switch (argv[i][1]) {
1407 case 'i':
1408 if (!strcmp (argv[i], "-include")) {
1409 if (i + 1 == argc)
1410 fatal ("Filename missing after `-include' option");
1411 else
1412 pend_includes[i] = argv[i+1], i++;
1414 if (!strcmp (argv[i], "-imacros")) {
1415 if (i + 1 == argc)
1416 fatal ("Filename missing after `-imacros' option");
1417 else
1418 pend_files[i] = argv[i+1], i++;
1420 if (!strcmp (argv[i], "-iprefix")) {
1421 if (i + 1 == argc)
1422 fatal ("Filename missing after `-iprefix' option");
1423 else
1424 include_prefix = argv[++i];
1426 if (!strcmp (argv[i], "-ifoutput")) {
1427 output_conditionals = 1;
1429 if (!strcmp (argv[i], "-isystem")) {
1430 struct file_name_list *dirtmp;
1432 if (i + 1 == argc)
1433 fatal ("Filename missing after `-isystem' option");
1435 dirtmp = (struct file_name_list *)
1436 xmalloc (sizeof (struct file_name_list));
1437 dirtmp->next = 0;
1438 dirtmp->control_macro = 0;
1439 dirtmp->c_system_include_path = 1;
1440 dirtmp->fname = xmalloc (strlen (argv[i+1]) + 1);
1441 strcpy (dirtmp->fname, argv[++i]);
1442 dirtmp->got_name_map = 0;
1444 if (before_system == 0)
1445 before_system = dirtmp;
1446 else
1447 last_before_system->next = dirtmp;
1448 last_before_system = dirtmp; /* Tail follows the last one */
1450 /* Add directory to end of path for includes,
1451 with the default prefix at the front of its name. */
1452 if (!strcmp (argv[i], "-iwithprefix")) {
1453 struct file_name_list *dirtmp;
1454 char *prefix;
1456 if (include_prefix != 0)
1457 prefix = include_prefix;
1458 else {
1459 prefix = savestring (GCC_INCLUDE_DIR);
1460 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1461 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1462 prefix[strlen (prefix) - 7] = 0;
1465 dirtmp = (struct file_name_list *)
1466 xmalloc (sizeof (struct file_name_list));
1467 dirtmp->next = 0; /* New one goes on the end */
1468 dirtmp->control_macro = 0;
1469 dirtmp->c_system_include_path = 0;
1470 if (i + 1 == argc)
1471 fatal ("Directory name missing after `-iwithprefix' option");
1473 dirtmp->fname = xmalloc (strlen (argv[i+1]) + strlen (prefix) + 1);
1474 strcpy (dirtmp->fname, prefix);
1475 strcat (dirtmp->fname, argv[++i]);
1476 dirtmp->got_name_map = 0;
1478 if (after_include == 0)
1479 after_include = dirtmp;
1480 else
1481 last_after_include->next = dirtmp;
1482 last_after_include = dirtmp; /* Tail follows the last one */
1484 /* Add directory to main path for includes,
1485 with the default prefix at the front of its name. */
1486 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1487 struct file_name_list *dirtmp;
1488 char *prefix;
1490 if (include_prefix != 0)
1491 prefix = include_prefix;
1492 else {
1493 prefix = savestring (GCC_INCLUDE_DIR);
1494 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1495 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1496 prefix[strlen (prefix) - 7] = 0;
1499 dirtmp = (struct file_name_list *)
1500 xmalloc (sizeof (struct file_name_list));
1501 dirtmp->next = 0; /* New one goes on the end */
1502 dirtmp->control_macro = 0;
1503 dirtmp->c_system_include_path = 0;
1504 if (i + 1 == argc)
1505 fatal ("Directory name missing after `-iwithprefixbefore' option");
1507 dirtmp->fname = xmalloc (strlen (argv[i+1]) + strlen (prefix) + 1);
1508 strcpy (dirtmp->fname, prefix);
1509 strcat (dirtmp->fname, argv[++i]);
1510 dirtmp->got_name_map = 0;
1512 append_include_chain (dirtmp, dirtmp);
1514 /* Add directory to end of path for includes. */
1515 if (!strcmp (argv[i], "-idirafter")) {
1516 struct file_name_list *dirtmp;
1518 dirtmp = (struct file_name_list *)
1519 xmalloc (sizeof (struct file_name_list));
1520 dirtmp->next = 0; /* New one goes on the end */
1521 dirtmp->control_macro = 0;
1522 dirtmp->c_system_include_path = 0;
1523 if (i + 1 == argc)
1524 fatal ("Directory name missing after `-idirafter' option");
1525 else
1526 dirtmp->fname = argv[++i];
1527 dirtmp->got_name_map = 0;
1529 if (after_include == 0)
1530 after_include = dirtmp;
1531 else
1532 last_after_include->next = dirtmp;
1533 last_after_include = dirtmp; /* Tail follows the last one */
1535 break;
1537 case 'o':
1538 if (out_fname != NULL)
1539 fatal ("Output filename specified twice");
1540 if (i + 1 == argc)
1541 fatal ("Filename missing after -o option");
1542 out_fname = argv[++i];
1543 if (!strcmp (out_fname, "-"))
1544 out_fname = "";
1545 break;
1547 case 'p':
1548 if (!strcmp (argv[i], "-pedantic"))
1549 pedantic = 1;
1550 else if (!strcmp (argv[i], "-pedantic-errors")) {
1551 pedantic = 1;
1552 pedantic_errors = 1;
1553 } else if (!strcmp (argv[i], "-pcp")) {
1554 char *pcp_fname;
1555 if (i + 1 == argc)
1556 fatal ("Filename missing after -pcp option");
1557 pcp_fname = argv[++i];
1558 pcp_outfile =
1559 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1560 ? fopen (pcp_fname, "w")
1561 : stdout);
1562 if (pcp_outfile == 0)
1563 pfatal_with_name (pcp_fname);
1564 no_precomp = 1;
1566 break;
1568 case 't':
1569 if (!strcmp (argv[i], "-traditional")) {
1570 traditional = 1;
1571 cplusplus_comments = 0;
1572 if (dollars_in_ident > 0)
1573 dollars_in_ident = 1;
1574 } else if (!strcmp (argv[i], "-trigraphs")) {
1575 no_trigraphs = 0;
1577 break;
1579 case 'l':
1580 if (! strcmp (argv[i], "-lang-c"))
1581 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1582 if (! strcmp (argv[i], "-lang-c89"))
1583 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1584 if (! strcmp (argv[i], "-lang-c++"))
1585 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1586 if (! strcmp (argv[i], "-lang-objc"))
1587 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1588 if (! strcmp (argv[i], "-lang-objc++"))
1589 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1590 if (! strcmp (argv[i], "-lang-asm"))
1591 lang_asm = 1;
1592 if (! strcmp (argv[i], "-lint"))
1593 for_lint = 1;
1594 break;
1596 case '+':
1597 cplusplus = 1, cplusplus_comments = 1;
1598 break;
1600 case 'w':
1601 inhibit_warnings = 1;
1602 break;
1604 case 'W':
1605 if (!strcmp (argv[i], "-Wtrigraphs"))
1606 warn_trigraphs = 1;
1607 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1608 warn_trigraphs = 0;
1609 else if (!strcmp (argv[i], "-Wcomment"))
1610 warn_comments = 1;
1611 else if (!strcmp (argv[i], "-Wno-comment"))
1612 warn_comments = 0;
1613 else if (!strcmp (argv[i], "-Wcomments"))
1614 warn_comments = 1;
1615 else if (!strcmp (argv[i], "-Wno-comments"))
1616 warn_comments = 0;
1617 else if (!strcmp (argv[i], "-Wtraditional"))
1618 warn_stringify = 1;
1619 else if (!strcmp (argv[i], "-Wno-traditional"))
1620 warn_stringify = 0;
1621 else if (!strcmp (argv[i], "-Wimport"))
1622 warn_import = 1;
1623 else if (!strcmp (argv[i], "-Wno-import"))
1624 warn_import = 0;
1625 else if (!strcmp (argv[i], "-Werror"))
1626 warnings_are_errors = 1;
1627 else if (!strcmp (argv[i], "-Wno-error"))
1628 warnings_are_errors = 0;
1629 else if (!strcmp (argv[i], "-Wall"))
1631 warn_trigraphs = 1;
1632 warn_comments = 1;
1634 break;
1636 case 'M':
1637 /* The style of the choices here is a bit mixed.
1638 The chosen scheme is a hybrid of keeping all options in one string
1639 and specifying each option in a separate argument:
1640 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1641 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1642 -M[M][G][D file]. This is awkward to handle in specs, and is not
1643 as extensible. */
1644 /* ??? -MG must be specified in addition to one of -M or -MM.
1645 This can be relaxed in the future without breaking anything.
1646 The converse isn't true. */
1648 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1649 if (!strcmp (argv[i], "-MG"))
1651 print_deps_missing_files = 1;
1652 break;
1654 if (!strcmp (argv[i], "-M"))
1655 print_deps = 2;
1656 else if (!strcmp (argv[i], "-MM"))
1657 print_deps = 1;
1658 else if (!strcmp (argv[i], "-MD"))
1659 print_deps = 2;
1660 else if (!strcmp (argv[i], "-MMD"))
1661 print_deps = 1;
1662 /* For -MD and -MMD options, write deps on file named by next arg. */
1663 if (!strcmp (argv[i], "-MD")
1664 || !strcmp (argv[i], "-MMD")) {
1665 if (i + 1 == argc)
1666 fatal ("Filename missing after %s option", argv[i]);
1667 i++;
1668 deps_file = argv[i];
1669 deps_mode = "w";
1670 } else {
1671 /* For -M and -MM, write deps on standard output
1672 and suppress the usual output. */
1673 deps_stream = stdout;
1674 inhibit_output = 1;
1676 break;
1678 case 'd':
1680 char *p = argv[i] + 2;
1681 char c;
1682 while ((c = *p++)) {
1683 /* Arg to -d specifies what parts of macros to dump */
1684 switch (c) {
1685 case 'M':
1686 dump_macros = dump_only;
1687 no_output = 1;
1688 break;
1689 case 'N':
1690 dump_macros = dump_names;
1691 break;
1692 case 'D':
1693 dump_macros = dump_definitions;
1694 break;
1695 /* Start new option added by AMB */
1696 case 'I':
1697 dump_includes = 1;
1698 break;
1699 /* End new option added by AMB */
1703 break;
1705 case 'g':
1706 if (argv[i][2] == '3')
1707 debug_output = 1;
1708 break;
1710 case 'v':
1711 fprintf (stderr, "GNU CPP version %s", version_string);
1712 #ifdef TARGET_VERSION
1713 TARGET_VERSION;
1714 #endif
1715 fprintf (stderr, "\n");
1716 verbose = 1;
1717 break;
1719 case 'H':
1720 print_include_names = 1;
1721 break;
1723 case 'D':
1724 if (argv[i][2] != 0)
1725 pend_defs[i] = argv[i] + 2;
1726 else if (i + 1 == argc)
1727 fatal ("Macro name missing after -D option");
1728 else
1729 i++, pend_defs[i] = argv[i];
1730 break;
1732 case 'A':
1734 char *p;
1736 if (argv[i][2] != 0)
1737 p = argv[i] + 2;
1738 else if (i + 1 == argc)
1739 fatal ("Assertion missing after -A option");
1740 else
1741 p = argv[++i];
1743 if (!strcmp (p, "-")) {
1744 /* -A- eliminates all predefined macros and assertions.
1745 Let's include also any that were specified earlier
1746 on the command line. That way we can get rid of any
1747 that were passed automatically in from GCC. */
1748 int j;
1749 inhibit_predefs = 1;
1750 for (j = 0; j < i; j++)
1751 pend_defs[j] = pend_assertions[j] = 0;
1752 } else {
1753 pend_assertions[i] = p;
1754 pend_assertion_options[i] = "-A";
1757 break;
1759 case 'U': /* JF #undef something */
1760 if (argv[i][2] != 0)
1761 pend_undefs[i] = argv[i] + 2;
1762 else if (i + 1 == argc)
1763 fatal ("Macro name missing after -U option");
1764 else
1765 pend_undefs[i] = argv[i+1], i++;
1766 break;
1768 case 'C':
1769 put_out_comments = 1;
1770 break;
1772 case 'E': /* -E comes from cc -E; ignore it. */
1773 break;
1775 case 'P':
1776 no_line_directives = 1;
1777 break;
1779 case '$': /* Don't include $ in identifiers. */
1780 dollars_in_ident = 0;
1781 break;
1783 case 'I': /* Add directory to path for includes. */
1785 struct file_name_list *dirtmp;
1787 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1788 ignore_srcdir = 1;
1789 /* Don't use any preceding -I directories for #include <...>. */
1790 first_bracket_include = 0;
1792 else {
1793 dirtmp = (struct file_name_list *)
1794 xmalloc (sizeof (struct file_name_list));
1795 dirtmp->next = 0; /* New one goes on the end */
1796 dirtmp->control_macro = 0;
1797 dirtmp->c_system_include_path = 0;
1798 if (argv[i][2] != 0)
1799 dirtmp->fname = argv[i] + 2;
1800 else if (i + 1 == argc)
1801 fatal ("Directory name missing after -I option");
1802 else
1803 dirtmp->fname = argv[++i];
1804 dirtmp->got_name_map = 0;
1805 append_include_chain (dirtmp, dirtmp);
1808 break;
1810 case 'n':
1811 if (!strcmp (argv[i], "-nostdinc"))
1812 /* -nostdinc causes no default include directories.
1813 You must specify all include-file directories with -I. */
1814 no_standard_includes = 1;
1815 else if (!strcmp (argv[i], "-nostdinc++"))
1816 /* -nostdinc++ causes no default C++-specific include directories. */
1817 no_standard_cplusplus_includes = 1;
1818 else if (!strcmp (argv[i], "-noprecomp"))
1819 no_precomp = 1;
1820 break;
1822 case 'u':
1823 /* Sun compiler passes undocumented switch "-undef".
1824 Let's assume it means to inhibit the predefined symbols. */
1825 inhibit_predefs = 1;
1826 break;
1828 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1829 if (in_fname == NULL) {
1830 in_fname = "";
1831 break;
1832 } else if (out_fname == NULL) {
1833 out_fname = "";
1834 break;
1835 } /* else fall through into error */
1837 default:
1838 fatal ("Invalid option `%s'", argv[i]);
1843 /* Add dirs from CPATH after dirs from -I. */
1844 /* There seems to be confusion about what CPATH should do,
1845 so for the moment it is not documented. */
1846 /* Some people say that CPATH should replace the standard include dirs,
1847 but that seems pointless: it comes before them, so it overrides them
1848 anyway. */
1849 cp = getenv ("CPATH");
1850 if (cp && ! no_standard_includes)
1851 path_include (cp);
1853 /* Now that dollars_in_ident is known, initialize is_idchar. */
1854 initialize_char_syntax ();
1856 /* Initialize output buffer */
1858 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1859 outbuf.bufp = outbuf.buf;
1860 outbuf.length = OUTBUF_SIZE;
1862 /* Do partial setup of input buffer for the sake of generating
1863 early #line directives (when -g is in effect). */
1865 fp = &instack[++indepth];
1866 if (in_fname == NULL)
1867 in_fname = "";
1868 fp->nominal_fname = fp->fname = in_fname;
1869 fp->lineno = 0;
1871 /* In C++, wchar_t is a distinct basic type, and we can expect
1872 __wchar_t to be defined by cc1plus. */
1873 if (cplusplus)
1874 wchar_type = "__wchar_t";
1876 /* Install __LINE__, etc. Must follow initialize_char_syntax
1877 and option processing. */
1878 initialize_builtins (fp, &outbuf);
1880 /* Do standard #defines and assertions
1881 that identify system and machine type. */
1883 if (!inhibit_predefs) {
1884 char *p = (char *) alloca (strlen (predefs) + 1);
1885 strcpy (p, predefs);
1886 while (*p) {
1887 char *q;
1888 while (*p == ' ' || *p == '\t')
1889 p++;
1890 /* Handle -D options. */
1891 if (p[0] == '-' && p[1] == 'D') {
1892 q = &p[2];
1893 while (*p && *p != ' ' && *p != '\t')
1894 p++;
1895 if (*p != 0)
1896 *p++= 0;
1897 if (debug_output)
1898 output_line_directive (fp, &outbuf, 0, same_file);
1899 make_definition (q, &outbuf);
1900 while (*p == ' ' || *p == '\t')
1901 p++;
1902 } else if (p[0] == '-' && p[1] == 'A') {
1903 /* Handle -A options (assertions). */
1904 char *assertion;
1905 char *past_name;
1906 char *value;
1907 char *past_value;
1908 char *termination;
1909 int save_char;
1911 assertion = &p[2];
1912 past_name = assertion;
1913 /* Locate end of name. */
1914 while (*past_name && *past_name != ' '
1915 && *past_name != '\t' && *past_name != '(')
1916 past_name++;
1917 /* Locate `(' at start of value. */
1918 value = past_name;
1919 while (*value && (*value == ' ' || *value == '\t'))
1920 value++;
1921 if (*value++ != '(')
1922 abort ();
1923 while (*value && (*value == ' ' || *value == '\t'))
1924 value++;
1925 past_value = value;
1926 /* Locate end of value. */
1927 while (*past_value && *past_value != ' '
1928 && *past_value != '\t' && *past_value != ')')
1929 past_value++;
1930 termination = past_value;
1931 while (*termination && (*termination == ' ' || *termination == '\t'))
1932 termination++;
1933 if (*termination++ != ')')
1934 abort ();
1935 if (*termination && *termination != ' ' && *termination != '\t')
1936 abort ();
1937 /* Temporarily null-terminate the value. */
1938 save_char = *termination;
1939 *termination = '\0';
1940 /* Install the assertion. */
1941 make_assertion ("-A", assertion);
1942 *termination = (char) save_char;
1943 p = termination;
1944 while (*p == ' ' || *p == '\t')
1945 p++;
1946 } else {
1947 abort ();
1952 /* Now handle the command line options. */
1954 /* Do -U's, -D's and -A's in the order they were seen. */
1955 for (i = 1; i < argc; i++) {
1956 if (pend_undefs[i]) {
1957 if (debug_output)
1958 output_line_directive (fp, &outbuf, 0, same_file);
1959 make_undef (pend_undefs[i], &outbuf);
1961 if (pend_defs[i]) {
1962 if (debug_output)
1963 output_line_directive (fp, &outbuf, 0, same_file);
1964 make_definition (pend_defs[i], &outbuf);
1966 if (pend_assertions[i])
1967 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1970 done_initializing = 1;
1972 { /* read the appropriate environment variable and if it exists
1973 replace include_defaults with the listed path. */
1974 char *epath = 0;
1975 switch ((objc << 1) + cplusplus)
1977 case 0:
1978 epath = getenv ("C_INCLUDE_PATH");
1979 break;
1980 case 1:
1981 epath = getenv ("CPLUS_INCLUDE_PATH");
1982 break;
1983 case 2:
1984 epath = getenv ("OBJC_INCLUDE_PATH");
1985 break;
1986 case 3:
1987 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1988 break;
1990 /* If the environment var for this language is set,
1991 add to the default list of include directories. */
1992 if (epath) {
1993 char *nstore = (char *) alloca (strlen (epath) + 2);
1994 int num_dirs;
1995 char *startp, *endp;
1997 for (num_dirs = 1, startp = epath; *startp; startp++)
1998 if (*startp == PATH_SEPARATOR)
1999 num_dirs++;
2000 include_defaults
2001 = (struct default_include *) xmalloc ((num_dirs
2002 * sizeof (struct default_include))
2003 + sizeof (include_defaults_array));
2004 startp = endp = epath;
2005 num_dirs = 0;
2006 while (1) {
2007 /* Handle cases like c:/usr/lib:d:/gcc/lib */
2008 if ((*endp == PATH_SEPARATOR
2009 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
2010 #ifdef __MSDOS__
2011 && (endp-startp != 1 || !isalpha (*startp))
2012 #endif
2013 #endif
2015 || *endp == 0) {
2016 strncpy (nstore, startp, endp-startp);
2017 if (endp == startp)
2018 strcpy (nstore, ".");
2019 else
2020 nstore[endp-startp] = '\0';
2022 include_defaults[num_dirs].fname = savestring (nstore);
2023 include_defaults[num_dirs].cplusplus = cplusplus;
2024 include_defaults[num_dirs].cxx_aware = 1;
2025 num_dirs++;
2026 if (*endp == '\0')
2027 break;
2028 endp = startp = endp + 1;
2029 } else
2030 endp++;
2032 /* Put the usual defaults back in at the end. */
2033 bcopy ((char *) include_defaults_array,
2034 (char *) &include_defaults[num_dirs],
2035 sizeof (include_defaults_array));
2039 append_include_chain (before_system, last_before_system);
2040 first_system_include = before_system;
2042 /* Unless -fnostdinc,
2043 tack on the standard include file dirs to the specified list */
2044 if (!no_standard_includes) {
2045 struct default_include *p = include_defaults;
2046 char *specd_prefix = include_prefix;
2047 char *default_prefix = savestring (GCC_INCLUDE_DIR);
2048 int default_len = 0;
2049 /* Remove the `include' from /usr/local/lib/gcc.../include. */
2050 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
2051 default_len = strlen (default_prefix) - 7;
2052 default_prefix[default_len] = 0;
2054 /* Search "translated" versions of GNU directories.
2055 These have /usr/local/lib/gcc... replaced by specd_prefix. */
2056 if (specd_prefix != 0 && default_len != 0)
2057 for (p = include_defaults; p->fname; p++) {
2058 /* Some standard dirs are only for C++. */
2059 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2060 /* Does this dir start with the prefix? */
2061 if (!strncmp (p->fname, default_prefix, default_len)) {
2062 /* Yes; change prefix and add to search list. */
2063 struct file_name_list *new
2064 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2065 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
2066 char *str = xmalloc (this_len + 1);
2067 strcpy (str, specd_prefix);
2068 strcat (str, p->fname + default_len);
2069 new->fname = str;
2070 new->control_macro = 0;
2071 new->c_system_include_path = !p->cxx_aware;
2072 new->got_name_map = 0;
2073 append_include_chain (new, new);
2074 if (first_system_include == 0)
2075 first_system_include = new;
2079 /* Search ordinary names for GNU include directories. */
2080 for (p = include_defaults; p->fname; p++) {
2081 /* Some standard dirs are only for C++. */
2082 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2083 struct file_name_list *new
2084 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2085 new->control_macro = 0;
2086 new->c_system_include_path = !p->cxx_aware;
2087 new->fname = p->fname;
2088 new->got_name_map = 0;
2089 append_include_chain (new, new);
2090 if (first_system_include == 0)
2091 first_system_include = new;
2096 /* Tack the after_include chain at the end of the include chain. */
2097 append_include_chain (after_include, last_after_include);
2098 if (first_system_include == 0)
2099 first_system_include = after_include;
2101 /* With -v, print the list of dirs to search. */
2102 if (verbose) {
2103 struct file_name_list *p;
2104 fprintf (stderr, "#include \"...\" search starts here:\n");
2105 for (p = include; p; p = p->next) {
2106 if (p == first_bracket_include)
2107 fprintf (stderr, "#include <...> search starts here:\n");
2108 fprintf (stderr, " %s\n", p->fname);
2110 fprintf (stderr, "End of search list.\n");
2113 /* Scan the -imacros files before the main input.
2114 Much like #including them, but with no_output set
2115 so that only their macro definitions matter. */
2117 no_output++; no_record_file++;
2118 for (i = 1; i < argc; i++)
2119 if (pend_files[i]) {
2120 int fd = open (pend_files[i], O_RDONLY, 0666);
2121 if (fd < 0) {
2122 perror_with_name (pend_files[i]);
2123 return FATAL_EXIT_CODE;
2125 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
2127 no_output--; no_record_file--;
2129 /* Copy the entire contents of the main input file into
2130 the stacked input buffer previously allocated for it. */
2132 /* JF check for stdin */
2133 if (in_fname == NULL || *in_fname == 0) {
2134 in_fname = "";
2135 f = 0;
2136 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2137 goto perror;
2139 /* -MG doesn't select the form of output and must be specified with one of
2140 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2141 inhibit compilation. */
2142 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2143 fatal ("-MG must be specified with one of -M or -MM");
2145 /* Either of two environment variables can specify output of deps.
2146 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2147 where OUTPUT_FILE is the file to write deps info to
2148 and DEPS_TARGET is the target to mention in the deps. */
2150 if (print_deps == 0
2151 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2152 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2153 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2154 char *s;
2155 char *output_file;
2157 if (spec == 0) {
2158 spec = getenv ("SUNPRO_DEPENDENCIES");
2159 print_deps = 2;
2161 else
2162 print_deps = 1;
2164 s = spec;
2165 /* Find the space before the DEPS_TARGET, if there is one. */
2166 /* This should use index. (mrs) */
2167 while (*s != 0 && *s != ' ') s++;
2168 if (*s != 0) {
2169 deps_target = s + 1;
2170 output_file = xmalloc (s - spec + 1);
2171 bcopy (spec, output_file, s - spec);
2172 output_file[s - spec] = 0;
2174 else {
2175 deps_target = 0;
2176 output_file = spec;
2179 deps_file = output_file;
2180 deps_mode = "a";
2183 /* For -M, print the expected object file name
2184 as the target of this Make-rule. */
2185 if (print_deps) {
2186 deps_allocated_size = 200;
2187 deps_buffer = xmalloc (deps_allocated_size);
2188 deps_buffer[0] = 0;
2189 deps_size = 0;
2190 deps_column = 0;
2192 if (deps_target) {
2193 deps_output (deps_target, ':');
2194 } else if (*in_fname == 0) {
2195 deps_output ("-", ':');
2196 } else {
2197 char *p, *q;
2198 int len;
2200 /* Discard all directory prefixes from filename. */
2201 if ((q = rindex (in_fname, '/')) != NULL
2202 #ifdef DIR_SEPARATOR
2203 && (q = rindex (in_fname, DIR_SEPARATOR)) != NULL
2204 #endif
2206 ++q;
2207 else
2208 q = in_fname;
2210 /* Copy remainder to mungable area. */
2211 p = (char *) alloca (strlen(q) + 8);
2212 strcpy (p, q);
2214 /* Output P, but remove known suffixes. */
2215 len = strlen (p);
2216 q = p + len;
2217 if (len >= 2
2218 && p[len - 2] == '.'
2219 && index("cCsSm", p[len - 1]))
2220 q = p + (len - 2);
2221 else if (len >= 3
2222 && p[len - 3] == '.'
2223 && p[len - 2] == 'c'
2224 && p[len - 1] == 'c')
2225 q = p + (len - 3);
2226 else if (len >= 4
2227 && p[len - 4] == '.'
2228 && p[len - 3] == 'c'
2229 && p[len - 2] == 'x'
2230 && p[len - 1] == 'x')
2231 q = p + (len - 4);
2232 else if (len >= 4
2233 && p[len - 4] == '.'
2234 && p[len - 3] == 'c'
2235 && p[len - 2] == 'p'
2236 && p[len - 1] == 'p')
2237 q = p + (len - 4);
2239 /* Supply our own suffix. */
2240 #ifndef VMS
2241 strcpy (q, ".o");
2242 #else
2243 strcpy (q, ".obj");
2244 #endif
2246 deps_output (p, ':');
2247 deps_output (in_fname, ' ');
2251 file_size_and_mode (f, &st_mode, &st_size);
2252 fp->nominal_fname = fp->fname = in_fname;
2253 fp->lineno = 1;
2254 fp->system_header_p = 0;
2255 /* JF all this is mine about reading pipes and ttys */
2256 if (! S_ISREG (st_mode)) {
2257 /* Read input from a file that is not a normal disk file.
2258 We cannot preallocate a buffer with the correct size,
2259 so we must read in the file a piece at the time and make it bigger. */
2260 int size;
2261 int bsize;
2262 int cnt;
2264 bsize = 2000;
2265 size = 0;
2266 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2267 for (;;) {
2268 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2269 if (cnt < 0) goto perror; /* error! */
2270 size += cnt;
2271 if (size != bsize) break; /* End of file */
2272 bsize *= 2;
2273 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2275 fp->length = size;
2276 } else {
2277 /* Read a file whose size we can determine in advance.
2278 For the sake of VMS, st_size is just an upper bound. */
2279 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2280 fp->length = safe_read (f, (char *) fp->buf, st_size);
2281 if (fp->length < 0) goto perror;
2283 fp->bufp = fp->buf;
2284 fp->if_stack = if_stack;
2286 /* Make sure data ends with a newline. And put a null after it. */
2288 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2289 /* Backslash-newline at end is not good enough. */
2290 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2291 fp->buf[fp->length++] = '\n';
2292 missing_newline = 1;
2294 fp->buf[fp->length] = '\0';
2296 /* Unless inhibited, convert trigraphs in the input. */
2298 if (!no_trigraphs)
2299 trigraph_pcp (fp);
2301 /* Now that we know the input file is valid, open the output. */
2303 if (!out_fname || !strcmp (out_fname, ""))
2304 out_fname = "stdout";
2305 else if (! freopen (out_fname, "w", stdout))
2306 pfatal_with_name (out_fname);
2308 output_line_directive (fp, &outbuf, 0, same_file);
2310 /* Scan the -include files before the main input. */
2312 no_record_file++;
2313 for (i = 1; i < argc; i++)
2314 if (pend_includes[i]) {
2315 int fd = open (pend_includes[i], O_RDONLY, 0666);
2316 if (fd < 0) {
2317 perror_with_name (pend_includes[i]);
2318 return FATAL_EXIT_CODE;
2320 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
2322 no_record_file--;
2324 /* Scan the input, processing macros and directives. */
2326 rescan (&outbuf, 0);
2328 if (missing_newline)
2329 fp->lineno--;
2331 if (pedantic && missing_newline)
2332 pedwarn ("file does not end in newline");
2334 /* Now we have processed the entire input
2335 Write whichever kind of output has been requested. */
2337 if (dump_macros == dump_only)
2338 dump_all_macros ();
2339 else if (! inhibit_output) {
2340 write_output ();
2343 if (print_deps) {
2344 /* Don't actually write the deps file if compilation has failed. */
2345 if (errors == 0) {
2346 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2347 pfatal_with_name (deps_file);
2348 fputs (deps_buffer, deps_stream);
2349 putc ('\n', deps_stream);
2350 if (deps_file) {
2351 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2352 fatal ("I/O error on output");
2357 if (pcp_outfile && pcp_outfile != stdout
2358 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2359 fatal ("I/O error on `-pcp' output");
2361 if (ferror (stdout) || fclose (stdout) != 0)
2362 fatal ("I/O error on output");
2364 if (errors)
2365 exit (FATAL_EXIT_CODE);
2366 exit (SUCCESS_EXIT_CODE);
2368 perror:
2369 pfatal_with_name (in_fname);
2370 return 0;
2373 /* Given a colon-separated list of file names PATH,
2374 add all the names to the search path for include files. */
2376 static void
2377 path_include (path)
2378 char *path;
2380 char *p;
2382 p = path;
2384 if (*p)
2385 while (1) {
2386 char *q = p;
2387 char *name;
2388 struct file_name_list *dirtmp;
2390 /* Find the end of this name. */
2391 while (*q != 0 && *q != PATH_SEPARATOR) q++;
2392 if (p == q) {
2393 /* An empty name in the path stands for the current directory. */
2394 name = xmalloc (2);
2395 name[0] = '.';
2396 name[1] = 0;
2397 } else {
2398 /* Otherwise use the directory that is named. */
2399 name = xmalloc (q - p + 1);
2400 bcopy (p, name, q - p);
2401 name[q - p] = 0;
2404 dirtmp = (struct file_name_list *)
2405 xmalloc (sizeof (struct file_name_list));
2406 dirtmp->next = 0; /* New one goes on the end */
2407 dirtmp->control_macro = 0;
2408 dirtmp->c_system_include_path = 0;
2409 dirtmp->fname = name;
2410 dirtmp->got_name_map = 0;
2411 append_include_chain (dirtmp, dirtmp);
2413 /* Advance past this name. */
2414 p = q;
2415 if (*p == 0)
2416 break;
2417 /* Skip the colon. */
2418 p++;
2422 /* Return the address of the first character in S that equals C.
2423 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2424 Return 0 if there is no such character. Assume that C itself is not '\0'.
2425 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2426 but unfortunately memchr isn't autoconfigured yet. */
2428 static U_CHAR *
2429 index0 (s, c, n)
2430 U_CHAR *s;
2431 int c;
2432 size_t n;
2434 char *p = (char *) s;
2435 for (;;) {
2436 char *q = index (p, c);
2437 if (q)
2438 return (U_CHAR *) q;
2439 else {
2440 size_t l = strlen (p);
2441 if (l == n)
2442 return 0;
2443 l++;
2444 p += l;
2445 n -= l;
2450 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2451 before main CCCP processing. Name `pcp' is also in honor of the
2452 drugs the trigraph designers must have been on.
2454 Using an extra pass through the buffer takes a little extra time,
2455 but is infinitely less hairy than trying to handle trigraphs inside
2456 strings, etc. everywhere, and also makes sure that trigraphs are
2457 only translated in the top level of processing. */
2459 static void
2460 trigraph_pcp (buf)
2461 FILE_BUF *buf;
2463 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2464 int len;
2466 fptr = bptr = sptr = buf->buf;
2467 lptr = fptr + buf->length;
2468 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2469 if (*++sptr != '?')
2470 continue;
2471 switch (*++sptr) {
2472 case '=':
2473 c = '#';
2474 break;
2475 case '(':
2476 c = '[';
2477 break;
2478 case '/':
2479 c = '\\';
2480 break;
2481 case ')':
2482 c = ']';
2483 break;
2484 case '\'':
2485 c = '^';
2486 break;
2487 case '<':
2488 c = '{';
2489 break;
2490 case '!':
2491 c = '|';
2492 break;
2493 case '>':
2494 c = '}';
2495 break;
2496 case '-':
2497 c = '~';
2498 break;
2499 case '?':
2500 sptr--;
2501 continue;
2502 default:
2503 continue;
2505 len = sptr - fptr - 2;
2507 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2508 C, this will be memmove (). */
2509 if (bptr != fptr && len > 0)
2510 bcopy ((char *) fptr, (char *) bptr, len);
2512 bptr += len;
2513 *bptr++ = c;
2514 fptr = ++sptr;
2516 len = buf->length - (fptr - buf->buf);
2517 if (bptr != fptr && len > 0)
2518 bcopy ((char *) fptr, (char *) bptr, len);
2519 buf->length -= fptr - bptr;
2520 buf->buf[buf->length] = '\0';
2521 if (warn_trigraphs && fptr != bptr)
2522 warning_with_line (0, "%d trigraph(s) encountered", (fptr - bptr) / 2);
2525 /* Move all backslash-newline pairs out of embarrassing places.
2526 Exchange all such pairs following BP
2527 with any potentially-embarrassing characters that follow them.
2528 Potentially-embarrassing characters are / and *
2529 (because a backslash-newline inside a comment delimiter
2530 would cause it not to be recognized). */
2532 static void
2533 newline_fix (bp)
2534 U_CHAR *bp;
2536 register U_CHAR *p = bp;
2538 /* First count the backslash-newline pairs here. */
2540 while (p[0] == '\\' && p[1] == '\n')
2541 p += 2;
2543 /* What follows the backslash-newlines is not embarrassing. */
2545 if (*p != '/' && *p != '*')
2546 return;
2548 /* Copy all potentially embarrassing characters
2549 that follow the backslash-newline pairs
2550 down to where the pairs originally started. */
2552 while (*p == '*' || *p == '/')
2553 *bp++ = *p++;
2555 /* Now write the same number of pairs after the embarrassing chars. */
2556 while (bp < p) {
2557 *bp++ = '\\';
2558 *bp++ = '\n';
2562 /* Like newline_fix but for use within a directive-name.
2563 Move any backslash-newlines up past any following symbol constituents. */
2565 static void
2566 name_newline_fix (bp)
2567 U_CHAR *bp;
2569 register U_CHAR *p = bp;
2571 /* First count the backslash-newline pairs here. */
2572 while (p[0] == '\\' && p[1] == '\n')
2573 p += 2;
2575 /* What follows the backslash-newlines is not embarrassing. */
2577 if (!is_idchar[*p])
2578 return;
2580 /* Copy all potentially embarrassing characters
2581 that follow the backslash-newline pairs
2582 down to where the pairs originally started. */
2584 while (is_idchar[*p])
2585 *bp++ = *p++;
2587 /* Now write the same number of pairs after the embarrassing chars. */
2588 while (bp < p) {
2589 *bp++ = '\\';
2590 *bp++ = '\n';
2594 /* Look for lint commands in comments.
2596 When we come in here, ibp points into a comment. Limit is as one expects.
2597 scan within the comment -- it should start, after lwsp, with a lint command.
2598 If so that command is returned as a (constant) string.
2600 Upon return, any arg will be pointed to with argstart and will be
2601 arglen long. Note that we don't parse that arg since it will just
2602 be printed out again.
2605 static char *
2606 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2607 register U_CHAR *ibp;
2608 register U_CHAR *limit;
2609 U_CHAR **argstart; /* point to command arg */
2610 int *arglen, *cmdlen; /* how long they are */
2612 long linsize;
2613 register U_CHAR *numptr; /* temp for arg parsing */
2615 *arglen = 0;
2617 SKIP_WHITE_SPACE (ibp);
2619 if (ibp >= limit) return NULL;
2621 linsize = limit - ibp;
2623 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2624 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2625 *cmdlen = 10;
2626 return "NOTREACHED";
2628 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2629 *cmdlen = 8;
2630 return "ARGSUSED";
2632 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2633 *cmdlen = 11;
2634 return "LINTLIBRARY";
2636 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2637 *cmdlen = 7;
2638 ibp += 7; linsize -= 7;
2639 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2641 /* OK, read a number */
2642 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2643 numptr++);
2644 *arglen = numptr - *argstart;
2645 return "VARARGS";
2647 return NULL;
2651 * The main loop of the program.
2653 * Read characters from the input stack, transferring them to the
2654 * output buffer OP.
2656 * Macros are expanded and push levels on the input stack.
2657 * At the end of such a level it is popped off and we keep reading.
2658 * At the end of any other kind of level, we return.
2659 * #-directives are handled, except within macros.
2661 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2662 * and insert them when appropriate. This is set while scanning macro
2663 * arguments before substitution. It is zero when scanning for final output.
2664 * There are three types of Newline markers:
2665 * * Newline - follows a macro name that was not expanded
2666 * because it appeared inside an expansion of the same macro.
2667 * This marker prevents future expansion of that identifier.
2668 * When the input is rescanned into the final output, these are deleted.
2669 * These are also deleted by ## concatenation.
2670 * * Newline Space (or Newline and any other whitespace character)
2671 * stands for a place that tokens must be separated or whitespace
2672 * is otherwise desirable, but where the ANSI standard specifies there
2673 * is no whitespace. This marker turns into a Space (or whichever other
2674 * whitespace char appears in the marker) in the final output,
2675 * but it turns into nothing in an argument that is stringified with #.
2676 * Such stringified arguments are the only place where the ANSI standard
2677 * specifies with precision that whitespace may not appear.
2679 * During this function, IP->bufp is kept cached in IBP for speed of access.
2680 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2681 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2682 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2683 * explicitly, and before RECACHE, since RECACHE uses OBP.
2686 static void
2687 rescan (op, output_marks)
2688 FILE_BUF *op;
2689 int output_marks;
2691 /* Character being scanned in main loop. */
2692 register U_CHAR c;
2694 /* Length of pending accumulated identifier. */
2695 register int ident_length = 0;
2697 /* Hash code of pending accumulated identifier. */
2698 register int hash = 0;
2700 /* Current input level (&instack[indepth]). */
2701 FILE_BUF *ip;
2703 /* Pointer for scanning input. */
2704 register U_CHAR *ibp;
2706 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2707 register U_CHAR *limit;
2709 /* Pointer for storing output. */
2710 register U_CHAR *obp;
2712 /* REDO_CHAR is nonzero if we are processing an identifier
2713 after backing up over the terminating character.
2714 Sometimes we process an identifier without backing up over
2715 the terminating character, if the terminating character
2716 is not special. Backing up is done so that the terminating character
2717 will be dispatched on again once the identifier is dealt with. */
2718 int redo_char = 0;
2720 /* 1 if within an identifier inside of which a concatenation
2721 marker (Newline -) has been seen. */
2722 int concatenated = 0;
2724 /* While scanning a comment or a string constant,
2725 this records the line it started on, for error messages. */
2726 int start_line;
2728 /* Record position of last `real' newline. */
2729 U_CHAR *beg_of_line;
2731 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2733 #define POPMACRO \
2734 do { ip->macro->type = T_MACRO; \
2735 if (ip->free_ptr) free (ip->free_ptr); \
2736 --indepth; } while (0)
2738 /* Reload `rescan's local variables that describe the current
2739 level of the input stack. */
2741 #define RECACHE \
2742 do { ip = &instack[indepth]; \
2743 ibp = ip->bufp; \
2744 limit = ip->buf + ip->length; \
2745 op->bufp = obp; \
2746 check_expand (op, limit - ibp); \
2747 beg_of_line = 0; \
2748 obp = op->bufp; } while (0)
2750 if (no_output && instack[indepth].fname != 0)
2751 skip_if_group (&instack[indepth], 1, NULL);
2753 obp = op->bufp;
2754 RECACHE;
2756 beg_of_line = ibp;
2758 /* Our caller must always put a null after the end of
2759 the input at each input stack level. */
2760 if (*limit != 0)
2761 abort ();
2763 while (1) {
2764 c = *ibp++;
2765 *obp++ = c;
2767 switch (c) {
2768 case '\\':
2769 if (*ibp == '\n' && !ip->macro) {
2770 /* At the top level, always merge lines ending with backslash-newline,
2771 even in middle of identifier. But do not merge lines in a macro,
2772 since backslash might be followed by a newline-space marker. */
2773 ++ibp;
2774 ++ip->lineno;
2775 --obp; /* remove backslash from obuf */
2776 break;
2778 /* If ANSI, backslash is just another character outside a string. */
2779 if (!traditional)
2780 goto randomchar;
2781 /* Otherwise, backslash suppresses specialness of following char,
2782 so copy it here to prevent the switch from seeing it.
2783 But first get any pending identifier processed. */
2784 if (ident_length > 0)
2785 goto specialchar;
2786 if (ibp < limit)
2787 *obp++ = *ibp++;
2788 break;
2790 case '%':
2791 if (ident_length || ip->macro || traditional)
2792 goto randomchar;
2793 while (*ibp == '\\' && ibp[1] == '\n') {
2794 ibp += 2;
2795 ++ip->lineno;
2797 if (*ibp != ':')
2798 break;
2799 /* Treat this %: digraph as if it were #. */
2800 /* Fall through. */
2802 case '#':
2803 if (assertions_flag) {
2804 if (ident_length)
2805 goto specialchar;
2806 /* Copy #foo (bar lose) without macro expansion. */
2807 obp[-1] = '#'; /* In case it was '%'. */
2808 SKIP_WHITE_SPACE (ibp);
2809 while (is_idchar[*ibp])
2810 *obp++ = *ibp++;
2811 SKIP_WHITE_SPACE (ibp);
2812 if (*ibp == '(') {
2813 ip->bufp = ibp;
2814 skip_paren_group (ip);
2815 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2816 obp += ip->bufp - ibp;
2817 ibp = ip->bufp;
2819 break;
2822 /* If this is expanding a macro definition, don't recognize
2823 preprocessing directives. */
2824 if (ip->macro != 0)
2825 goto randomchar;
2826 /* If this is expand_into_temp_buffer,
2827 don't recognize them either. Warn about them
2828 only after an actual newline at this level,
2829 not at the beginning of the input level. */
2830 if (! ip->fname) {
2831 if (ip->buf != beg_of_line)
2832 warning ("preprocessing directive not recognized within macro arg");
2833 goto randomchar;
2835 if (ident_length)
2836 goto specialchar;
2839 /* # keyword: a # must be first nonblank char on the line */
2840 if (beg_of_line == 0)
2841 goto randomchar;
2843 U_CHAR *bp;
2845 /* Scan from start of line, skipping whitespace, comments
2846 and backslash-newlines, and see if we reach this #.
2847 If not, this # is not special. */
2848 bp = beg_of_line;
2849 /* If -traditional, require # to be at beginning of line. */
2850 if (!traditional) {
2851 while (1) {
2852 if (is_hor_space[*bp])
2853 bp++;
2854 else if (*bp == '\\' && bp[1] == '\n')
2855 bp += 2;
2856 else if (*bp == '/' && bp[1] == '*') {
2857 bp += 2;
2858 while (!(*bp == '*' && bp[1] == '/'))
2859 bp++;
2860 bp += 2;
2862 /* There is no point in trying to deal with C++ // comments here,
2863 because if there is one, then this # must be part of the
2864 comment and we would never reach here. */
2865 else break;
2867 if (c == '%') {
2868 if (bp[0] != '%')
2869 break;
2870 while (bp[1] == '\\' && bp[2] == '\n')
2871 bp += 2;
2872 if (bp + 1 != ibp)
2873 break;
2874 /* %: appears at start of line; skip past the ':' too. */
2875 bp++;
2876 ibp++;
2879 if (bp + 1 != ibp)
2880 goto randomchar;
2883 /* This # can start a directive. */
2885 --obp; /* Don't copy the '#' */
2887 ip->bufp = ibp;
2888 op->bufp = obp;
2889 if (! handle_directive (ip, op)) {
2890 #ifdef USE_C_ALLOCA
2891 alloca (0);
2892 #endif
2893 /* Not a known directive: treat it as ordinary text.
2894 IP, OP, IBP, etc. have not been changed. */
2895 if (no_output && instack[indepth].fname) {
2896 /* If not generating expanded output,
2897 what we do with ordinary text is skip it.
2898 Discard everything until next # directive. */
2899 skip_if_group (&instack[indepth], 1, 0);
2900 RECACHE;
2901 beg_of_line = ibp;
2902 break;
2904 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2905 /* Don't expand an identifier that could be a macro directive.
2906 (Section 3.8.3 of the ANSI C standard) */
2907 SKIP_WHITE_SPACE (ibp);
2908 if (is_idstart[*ibp])
2910 *obp++ = *ibp++;
2911 while (is_idchar[*ibp])
2912 *obp++ = *ibp++;
2914 goto randomchar;
2916 #ifdef USE_C_ALLOCA
2917 alloca (0);
2918 #endif
2919 /* A # directive has been successfully processed. */
2920 /* If not generating expanded output, ignore everything until
2921 next # directive. */
2922 if (no_output && instack[indepth].fname)
2923 skip_if_group (&instack[indepth], 1, 0);
2924 obp = op->bufp;
2925 RECACHE;
2926 beg_of_line = ibp;
2927 break;
2929 case '\"': /* skip quoted string */
2930 case '\'':
2931 /* A single quoted string is treated like a double -- some
2932 programs (e.g., troff) are perverse this way */
2934 if (ident_length)
2935 goto specialchar;
2937 start_line = ip->lineno;
2939 /* Skip ahead to a matching quote. */
2941 while (1) {
2942 if (ibp >= limit) {
2943 if (ip->macro != 0) {
2944 /* try harder: this string crosses a macro expansion boundary.
2945 This can happen naturally if -traditional.
2946 Otherwise, only -D can make a macro with an unmatched quote. */
2947 POPMACRO;
2948 RECACHE;
2949 continue;
2951 if (!traditional) {
2952 error_with_line (line_for_error (start_line),
2953 "unterminated string or character constant");
2954 error_with_line (multiline_string_line,
2955 "possible real start of unterminated constant");
2956 multiline_string_line = 0;
2958 break;
2960 *obp++ = *ibp;
2961 switch (*ibp++) {
2962 case '\n':
2963 ++ip->lineno;
2964 ++op->lineno;
2965 /* Traditionally, end of line ends a string constant with no error.
2966 So exit the loop and record the new line. */
2967 if (traditional) {
2968 beg_of_line = ibp;
2969 goto while2end;
2971 if (c == '\'') {
2972 error_with_line (line_for_error (start_line),
2973 "unterminated character constant");
2974 goto while2end;
2976 if (pedantic && multiline_string_line == 0) {
2977 pedwarn_with_line (line_for_error (start_line),
2978 "string constant runs past end of line");
2980 if (multiline_string_line == 0)
2981 multiline_string_line = ip->lineno - 1;
2982 break;
2984 case '\\':
2985 if (ibp >= limit)
2986 break;
2987 if (*ibp == '\n') {
2988 /* Backslash newline is replaced by nothing at all,
2989 but keep the line counts correct. */
2990 --obp;
2991 ++ibp;
2992 ++ip->lineno;
2993 } else {
2994 /* ANSI stupidly requires that in \\ the second \
2995 is *not* prevented from combining with a newline. */
2996 while (*ibp == '\\' && ibp[1] == '\n') {
2997 ibp += 2;
2998 ++ip->lineno;
3000 *obp++ = *ibp++;
3002 break;
3004 case '\"':
3005 case '\'':
3006 if (ibp[-1] == c)
3007 goto while2end;
3008 break;
3011 while2end:
3012 break;
3014 case '/':
3015 if (*ibp == '\\' && ibp[1] == '\n')
3016 newline_fix (ibp);
3018 if (*ibp != '*'
3019 && !(cplusplus_comments && *ibp == '/'))
3020 goto randomchar;
3021 if (ip->macro != 0)
3022 goto randomchar;
3023 if (ident_length)
3024 goto specialchar;
3026 if (*ibp == '/') {
3027 /* C++ style comment... */
3028 start_line = ip->lineno;
3030 /* Comments are equivalent to spaces. */
3031 if (! put_out_comments)
3032 obp[-1] = ' ';
3035 U_CHAR *before_bp = ibp;
3037 while (++ibp < limit) {
3038 if (*ibp == '\n') {
3039 if (ibp[-1] != '\\') {
3040 if (put_out_comments) {
3041 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3042 obp += ibp - before_bp;
3044 break;
3046 ++ip->lineno;
3047 /* Copy the newline into the output buffer, in order to
3048 avoid the pain of a #line every time a multiline comment
3049 is seen. */
3050 if (!put_out_comments)
3051 *obp++ = '\n';
3052 ++op->lineno;
3055 break;
3059 /* Ordinary C comment. Skip it, optionally copying it to output. */
3061 start_line = ip->lineno;
3063 ++ibp; /* Skip the star. */
3065 /* If this cpp is for lint, we peek inside the comments: */
3066 if (for_lint) {
3067 U_CHAR *argbp;
3068 int cmdlen, arglen;
3069 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
3071 if (lintcmd != NULL) {
3072 op->bufp = obp;
3073 check_expand (op, cmdlen + arglen + 14);
3074 obp = op->bufp;
3075 /* I believe it is always safe to emit this newline: */
3076 obp[-1] = '\n';
3077 bcopy ("#pragma lint ", (char *) obp, 13);
3078 obp += 13;
3079 bcopy (lintcmd, (char *) obp, cmdlen);
3080 obp += cmdlen;
3082 if (arglen != 0) {
3083 *(obp++) = ' ';
3084 bcopy (argbp, (char *) obp, arglen);
3085 obp += arglen;
3088 /* OK, now bring us back to the state we were in before we entered
3089 this branch. We need #line because the #pragma's newline always
3090 messes up the line count. */
3091 op->bufp = obp;
3092 output_line_directive (ip, op, 0, same_file);
3093 check_expand (op, limit - ibp + 2);
3094 obp = op->bufp;
3095 *(obp++) = '/';
3099 /* Comments are equivalent to spaces.
3100 Note that we already output the slash; we might not want it.
3101 For -traditional, a comment is equivalent to nothing. */
3102 if (! put_out_comments) {
3103 if (traditional)
3104 obp--;
3105 else
3106 obp[-1] = ' ';
3108 else
3109 *obp++ = '*';
3112 U_CHAR *before_bp = ibp;
3114 while (ibp < limit) {
3115 switch (*ibp++) {
3116 case '/':
3117 if (warn_comments && *ibp == '*')
3118 warning ("`/*' within comment");
3119 break;
3120 case '*':
3121 if (*ibp == '\\' && ibp[1] == '\n')
3122 newline_fix (ibp);
3123 if (ibp >= limit || *ibp == '/')
3124 goto comment_end;
3125 break;
3126 case '\n':
3127 ++ip->lineno;
3128 /* Copy the newline into the output buffer, in order to
3129 avoid the pain of a #line every time a multiline comment
3130 is seen. */
3131 if (!put_out_comments)
3132 *obp++ = '\n';
3133 ++op->lineno;
3136 comment_end:
3138 if (ibp >= limit)
3139 error_with_line (line_for_error (start_line),
3140 "unterminated comment");
3141 else {
3142 ibp++;
3143 if (put_out_comments) {
3144 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3145 obp += ibp - before_bp;
3149 break;
3151 case '$':
3152 if (!dollars_in_ident)
3153 goto randomchar;
3154 goto letter;
3156 case '0': case '1': case '2': case '3': case '4':
3157 case '5': case '6': case '7': case '8': case '9':
3158 /* If digit is not part of identifier, it starts a number,
3159 which means that following letters are not an identifier.
3160 "0x5" does not refer to an identifier "x5".
3161 So copy all alphanumerics that follow without accumulating
3162 as an identifier. Periods also, for sake of "3.e7". */
3164 if (ident_length == 0) {
3165 for (;;) {
3166 while (ibp[0] == '\\' && ibp[1] == '\n') {
3167 ++ip->lineno;
3168 ibp += 2;
3170 c = *ibp++;
3171 if (!is_idchar[c] && c != '.') {
3172 --ibp;
3173 break;
3175 *obp++ = c;
3176 /* A sign can be part of a preprocessing number
3177 if it follows an e. */
3178 if (c == 'e' || c == 'E') {
3179 while (ibp[0] == '\\' && ibp[1] == '\n') {
3180 ++ip->lineno;
3181 ibp += 2;
3183 if (*ibp == '+' || *ibp == '-') {
3184 *obp++ = *ibp++;
3185 /* But traditional C does not let the token go past the sign. */
3186 if (traditional)
3187 break;
3191 break;
3193 /* fall through */
3195 case '_':
3196 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3197 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3198 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3199 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3200 case 'y': case 'z':
3201 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3202 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3203 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3204 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3205 case 'Y': case 'Z':
3206 letter:
3207 ident_length++;
3208 /* Compute step of hash function, to avoid a proc call on every token */
3209 hash = HASHSTEP (hash, c);
3210 break;
3212 case '\n':
3213 if (ip->fname == 0 && *ibp == '-') {
3214 /* Newline - inhibits expansion of preceding token.
3215 If expanding a macro arg, we keep the newline -.
3216 In final output, it is deleted.
3217 We recognize Newline - in macro bodies and macro args. */
3218 if (! concatenated) {
3219 ident_length = 0;
3220 hash = 0;
3222 ibp++;
3223 if (!output_marks) {
3224 obp--;
3225 } else {
3226 /* If expanding a macro arg, keep the newline -. */
3227 *obp++ = '-';
3229 break;
3232 /* If reprocessing a macro expansion, newline is a special marker. */
3233 else if (ip->macro != 0) {
3234 /* Newline White is a "funny space" to separate tokens that are
3235 supposed to be separate but without space between.
3236 Here White means any whitespace character.
3237 Newline - marks a recursive macro use that is not
3238 supposed to be expandable. */
3240 if (is_space[*ibp]) {
3241 /* Newline Space does not prevent expansion of preceding token
3242 so expand the preceding token and then come back. */
3243 if (ident_length > 0)
3244 goto specialchar;
3246 /* If generating final output, newline space makes a space. */
3247 if (!output_marks) {
3248 obp[-1] = *ibp++;
3249 /* And Newline Newline makes a newline, so count it. */
3250 if (obp[-1] == '\n')
3251 op->lineno++;
3252 } else {
3253 /* If expanding a macro arg, keep the newline space.
3254 If the arg gets stringified, newline space makes nothing. */
3255 *obp++ = *ibp++;
3257 } else abort (); /* Newline followed by something random? */
3258 break;
3261 /* If there is a pending identifier, handle it and come back here. */
3262 if (ident_length > 0)
3263 goto specialchar;
3265 beg_of_line = ibp;
3267 /* Update the line counts and output a #line if necessary. */
3268 ++ip->lineno;
3269 ++op->lineno;
3270 if (ip->lineno != op->lineno) {
3271 op->bufp = obp;
3272 output_line_directive (ip, op, 1, same_file);
3273 check_expand (op, limit - ibp);
3274 obp = op->bufp;
3276 break;
3278 /* Come here either after (1) a null character that is part of the input
3279 or (2) at the end of the input, because there is a null there. */
3280 case 0:
3281 if (ibp <= limit)
3282 /* Our input really contains a null character. */
3283 goto randomchar;
3285 /* At end of a macro-expansion level, pop it and read next level. */
3286 if (ip->macro != 0) {
3287 obp--;
3288 ibp--;
3289 /* If traditional, and we have an identifier that ends here,
3290 process it now, so we get the right error for recursion. */
3291 if (traditional && ident_length
3292 && ! is_idchar[*instack[indepth - 1].bufp]) {
3293 redo_char = 1;
3294 goto randomchar;
3296 POPMACRO;
3297 RECACHE;
3298 break;
3301 /* If we don't have a pending identifier,
3302 return at end of input. */
3303 if (ident_length == 0) {
3304 obp--;
3305 ibp--;
3306 op->bufp = obp;
3307 ip->bufp = ibp;
3308 goto ending;
3311 /* If we do have a pending identifier, just consider this null
3312 a special character and arrange to dispatch on it again.
3313 The second time, IDENT_LENGTH will be zero so we will return. */
3315 /* Fall through */
3317 specialchar:
3319 /* Handle the case of a character such as /, ', " or null
3320 seen following an identifier. Back over it so that
3321 after the identifier is processed the special char
3322 will be dispatched on again. */
3324 ibp--;
3325 obp--;
3326 redo_char = 1;
3328 default:
3330 randomchar:
3332 if (ident_length > 0) {
3333 register HASHNODE *hp;
3335 /* We have just seen an identifier end. If it's a macro, expand it.
3337 IDENT_LENGTH is the length of the identifier
3338 and HASH is its hash code.
3340 The identifier has already been copied to the output,
3341 so if it is a macro we must remove it.
3343 If REDO_CHAR is 0, the char that terminated the identifier
3344 has been skipped in the output and the input.
3345 OBP-IDENT_LENGTH-1 points to the identifier.
3346 If the identifier is a macro, we must back over the terminator.
3348 If REDO_CHAR is 1, the terminating char has already been
3349 backed over. OBP-IDENT_LENGTH points to the identifier. */
3351 if (!pcp_outfile || pcp_inside_if) {
3352 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3353 hp = hp->next) {
3355 if (hp->length == ident_length) {
3356 int obufp_before_macroname;
3357 int op_lineno_before_macroname;
3358 register int i = ident_length;
3359 register U_CHAR *p = hp->name;
3360 register U_CHAR *q = obp - i;
3361 int disabled;
3363 if (! redo_char)
3364 q--;
3366 do { /* All this to avoid a strncmp () */
3367 if (*p++ != *q++)
3368 goto hashcollision;
3369 } while (--i);
3371 /* We found a use of a macro name.
3372 see if the context shows it is a macro call. */
3374 /* Back up over terminating character if not already done. */
3375 if (! redo_char) {
3376 ibp--;
3377 obp--;
3380 /* Save this as a displacement from the beginning of the output
3381 buffer. We can not save this as a position in the output
3382 buffer, because it may get realloc'ed by RECACHE. */
3383 obufp_before_macroname = (obp - op->buf) - ident_length;
3384 op_lineno_before_macroname = op->lineno;
3386 if (hp->type == T_PCSTRING) {
3387 pcstring_used (hp); /* Mark the definition of this key
3388 as needed, ensuring that it
3389 will be output. */
3390 break; /* Exit loop, since the key cannot have a
3391 definition any longer. */
3394 /* Record whether the macro is disabled. */
3395 disabled = hp->type == T_DISABLED;
3397 /* This looks like a macro ref, but if the macro was disabled,
3398 just copy its name and put in a marker if requested. */
3400 if (disabled) {
3401 #if 0
3402 /* This error check caught useful cases such as
3403 #define foo(x,y) bar (x (y,0), y)
3404 foo (foo, baz) */
3405 if (traditional)
3406 error ("recursive use of macro `%s'", hp->name);
3407 #endif
3409 if (output_marks) {
3410 check_expand (op, limit - ibp + 2);
3411 *obp++ = '\n';
3412 *obp++ = '-';
3414 break;
3417 /* If macro wants an arglist, verify that a '(' follows.
3418 first skip all whitespace, copying it to the output
3419 after the macro name. Then, if there is no '(',
3420 decide this is not a macro call and leave things that way. */
3421 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3422 && hp->value.defn->nargs >= 0)
3424 U_CHAR *old_ibp = ibp;
3425 U_CHAR *old_obp = obp;
3426 int old_iln = ip->lineno;
3427 int old_oln = op->lineno;
3429 while (1) {
3430 /* Scan forward over whitespace, copying it to the output. */
3431 if (ibp == limit && ip->macro != 0) {
3432 POPMACRO;
3433 RECACHE;
3434 old_ibp = ibp;
3435 old_obp = obp;
3436 old_iln = ip->lineno;
3437 old_oln = op->lineno;
3439 /* A comment: copy it unchanged or discard it. */
3440 else if (*ibp == '/' && ibp[1] == '*') {
3441 if (put_out_comments) {
3442 *obp++ = '/';
3443 *obp++ = '*';
3444 } else if (! traditional) {
3445 *obp++ = ' ';
3447 ibp += 2;
3448 while (ibp + 1 != limit
3449 && !(ibp[0] == '*' && ibp[1] == '/')) {
3450 /* We need not worry about newline-marks,
3451 since they are never found in comments. */
3452 if (*ibp == '\n') {
3453 /* Newline in a file. Count it. */
3454 ++ip->lineno;
3455 ++op->lineno;
3457 if (put_out_comments)
3458 *obp++ = *ibp++;
3459 else
3460 ibp++;
3462 ibp += 2;
3463 if (put_out_comments) {
3464 *obp++ = '*';
3465 *obp++ = '/';
3468 else if (is_space[*ibp]) {
3469 *obp++ = *ibp++;
3470 if (ibp[-1] == '\n') {
3471 if (ip->macro == 0) {
3472 /* Newline in a file. Count it. */
3473 ++ip->lineno;
3474 ++op->lineno;
3475 } else if (!output_marks) {
3476 /* A newline mark, and we don't want marks
3477 in the output. If it is newline-hyphen,
3478 discard it entirely. Otherwise, it is
3479 newline-whitechar, so keep the whitechar. */
3480 obp--;
3481 if (*ibp == '-')
3482 ibp++;
3483 else {
3484 if (*ibp == '\n')
3485 ++op->lineno;
3486 *obp++ = *ibp++;
3488 } else {
3489 /* A newline mark; copy both chars to the output. */
3490 *obp++ = *ibp++;
3494 else break;
3496 if (*ibp != '(') {
3497 /* It isn't a macro call.
3498 Put back the space that we just skipped. */
3499 ibp = old_ibp;
3500 obp = old_obp;
3501 ip->lineno = old_iln;
3502 op->lineno = old_oln;
3503 /* Exit the for loop. */
3504 break;
3508 /* This is now known to be a macro call.
3509 Discard the macro name from the output,
3510 along with any following whitespace just copied,
3511 but preserve newlines if not outputting marks since this
3512 is more likely to do the right thing with line numbers. */
3513 obp = op->buf + obufp_before_macroname;
3514 if (output_marks)
3515 op->lineno = op_lineno_before_macroname;
3516 else {
3517 int newlines = op->lineno - op_lineno_before_macroname;
3518 while (0 < newlines--)
3519 *obp++ = '\n';
3522 /* Prevent accidental token-pasting with a character
3523 before the macro call. */
3524 if (!traditional && obp != op->buf) {
3525 switch (obp[-1]) {
3526 case '!': case '%': case '&': case '*':
3527 case '+': case '-': case '/': case ':':
3528 case '<': case '=': case '>': case '^':
3529 case '|':
3530 /* If we are expanding a macro arg, make a newline marker
3531 to separate the tokens. If we are making real output,
3532 a plain space will do. */
3533 if (output_marks)
3534 *obp++ = '\n';
3535 *obp++ = ' ';
3539 /* Expand the macro, reading arguments as needed,
3540 and push the expansion on the input stack. */
3541 ip->bufp = ibp;
3542 op->bufp = obp;
3543 macroexpand (hp, op);
3545 /* Reexamine input stack, since macroexpand has pushed
3546 a new level on it. */
3547 obp = op->bufp;
3548 RECACHE;
3549 break;
3551 hashcollision:
3553 } /* End hash-table-search loop */
3555 ident_length = hash = 0; /* Stop collecting identifier */
3556 redo_char = 0;
3557 concatenated = 0;
3558 } /* End if (ident_length > 0) */
3559 } /* End switch */
3560 } /* End per-char loop */
3562 /* Come here to return -- but first give an error message
3563 if there was an unterminated successful conditional. */
3564 ending:
3565 if (if_stack != ip->if_stack)
3567 char *str;
3569 switch (if_stack->type)
3571 case T_IF:
3572 str = "if";
3573 break;
3574 case T_IFDEF:
3575 str = "ifdef";
3576 break;
3577 case T_IFNDEF:
3578 str = "ifndef";
3579 break;
3580 case T_ELSE:
3581 str = "else";
3582 break;
3583 case T_ELIF:
3584 str = "elif";
3585 break;
3586 default:
3587 abort ();
3590 error_with_line (line_for_error (if_stack->lineno),
3591 "unterminated `#%s' conditional", str);
3593 if_stack = ip->if_stack;
3597 * Rescan a string into a temporary buffer and return the result
3598 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3600 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3601 * and insert such markers when appropriate. See `rescan' for details.
3602 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3603 * before substitution; it is 0 for other uses.
3605 static FILE_BUF
3606 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3607 U_CHAR *buf, *limit;
3608 int output_marks, assertions;
3610 register FILE_BUF *ip;
3611 FILE_BUF obuf;
3612 int length = limit - buf;
3613 U_CHAR *buf1;
3614 int odepth = indepth;
3615 int save_assertions_flag = assertions_flag;
3617 assertions_flag = assertions;
3619 if (length < 0)
3620 abort ();
3622 /* Set up the input on the input stack. */
3624 buf1 = (U_CHAR *) alloca (length + 1);
3626 register U_CHAR *p1 = buf;
3627 register U_CHAR *p2 = buf1;
3629 while (p1 != limit)
3630 *p2++ = *p1++;
3632 buf1[length] = 0;
3634 /* Set up to receive the output. */
3636 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3637 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3638 obuf.fname = 0;
3639 obuf.macro = 0;
3640 obuf.free_ptr = 0;
3642 CHECK_DEPTH ({return obuf;});
3644 ++indepth;
3646 ip = &instack[indepth];
3647 ip->fname = 0;
3648 ip->nominal_fname = 0;
3649 ip->system_header_p = 0;
3650 ip->macro = 0;
3651 ip->free_ptr = 0;
3652 ip->length = length;
3653 ip->buf = ip->bufp = buf1;
3654 ip->if_stack = if_stack;
3656 ip->lineno = obuf.lineno = 1;
3658 /* Scan the input, create the output. */
3659 rescan (&obuf, output_marks);
3661 /* Pop input stack to original state. */
3662 --indepth;
3664 if (indepth != odepth)
3665 abort ();
3667 /* Record the output. */
3668 obuf.length = obuf.bufp - obuf.buf;
3670 assertions_flag = save_assertions_flag;
3671 return obuf;
3675 * Process a # directive. Expects IP->bufp to point after the '#', as in
3676 * `#define foo bar'. Passes to the directive handler
3677 * (do_define, do_include, etc.): the addresses of the 1st and
3678 * last chars of the directive (starting immediately after the #
3679 * keyword), plus op and the keyword table pointer. If the directive
3680 * contains comments it is copied into a temporary buffer sans comments
3681 * and the temporary buffer is passed to the directive handler instead.
3682 * Likewise for backslash-newlines.
3684 * Returns nonzero if this was a known # directive.
3685 * Otherwise, returns zero, without advancing the input pointer.
3688 static int
3689 handle_directive (ip, op)
3690 FILE_BUF *ip, *op;
3692 register U_CHAR *bp, *cp;
3693 register struct directive *kt;
3694 register int ident_length;
3695 U_CHAR *resume_p;
3697 /* Nonzero means we must copy the entire directive
3698 to get rid of comments or backslash-newlines. */
3699 int copy_directive = 0;
3701 U_CHAR *ident, *after_ident;
3703 bp = ip->bufp;
3705 /* Record where the directive started. do_xifdef needs this. */
3706 directive_start = bp - 1;
3708 /* Skip whitespace and \-newline. */
3709 while (1) {
3710 if (is_hor_space[*bp]) {
3711 if (*bp != ' ' && *bp != '\t' && pedantic)
3712 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3713 bp++;
3714 } else if (*bp == '/' && (bp[1] == '*'
3715 || (cplusplus_comments && bp[1] == '/'))) {
3716 ip->bufp = bp + 2;
3717 skip_to_end_of_comment (ip, &ip->lineno, 0);
3718 bp = ip->bufp;
3719 } else if (*bp == '\\' && bp[1] == '\n') {
3720 bp += 2; ip->lineno++;
3721 } else break;
3724 /* Now find end of directive name.
3725 If we encounter a backslash-newline, exchange it with any following
3726 symbol-constituents so that we end up with a contiguous name. */
3728 cp = bp;
3729 while (1) {
3730 if (is_idchar[*cp])
3731 cp++;
3732 else {
3733 if (*cp == '\\' && cp[1] == '\n')
3734 name_newline_fix (cp);
3735 if (is_idchar[*cp])
3736 cp++;
3737 else break;
3740 ident_length = cp - bp;
3741 ident = bp;
3742 after_ident = cp;
3744 /* A line of just `#' becomes blank. */
3746 if (ident_length == 0 && *after_ident == '\n') {
3747 ip->bufp = after_ident;
3748 return 1;
3751 if (ident_length == 0 || !is_idstart[*ident]) {
3752 U_CHAR *p = ident;
3753 while (is_idchar[*p]) {
3754 if (*p < '0' || *p > '9')
3755 break;
3756 p++;
3758 /* Handle # followed by a line number. */
3759 if (p != ident && !is_idchar[*p]) {
3760 static struct directive line_directive_table[] = {
3761 { 4, do_line, "line", T_LINE},
3763 if (pedantic)
3764 pedwarn ("`#' followed by integer");
3765 after_ident = ident;
3766 kt = line_directive_table;
3767 goto old_linenum;
3770 /* Avoid error for `###' and similar cases unless -pedantic. */
3771 if (p == ident) {
3772 while (*p == '#' || is_hor_space[*p]) p++;
3773 if (*p == '\n') {
3774 if (pedantic && !lang_asm)
3775 warning ("invalid preprocessing directive");
3776 return 0;
3780 if (!lang_asm)
3781 error ("invalid preprocessing directive name");
3783 return 0;
3787 * Decode the keyword and call the appropriate expansion
3788 * routine, after moving the input pointer up to the next line.
3790 for (kt = directive_table; kt->length > 0; kt++) {
3791 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3792 register U_CHAR *buf;
3793 register U_CHAR *limit;
3794 int unterminated;
3795 int junk;
3796 int *already_output;
3798 /* Nonzero means do not delete comments within the directive.
3799 #define needs this when -traditional. */
3800 int keep_comments;
3802 old_linenum:
3804 limit = ip->buf + ip->length;
3805 unterminated = 0;
3806 already_output = 0;
3807 keep_comments = traditional && kt->traditional_comments;
3808 /* #import is defined only in Objective C, or when on the NeXT. */
3809 if (kt->type == T_IMPORT
3810 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3811 break;
3813 /* Find the end of this directive (first newline not backslashed
3814 and not in a string or comment).
3815 Set COPY_DIRECTIVE if the directive must be copied
3816 (it contains a backslash-newline or a comment). */
3818 buf = bp = after_ident;
3819 while (bp < limit) {
3820 register U_CHAR c = *bp++;
3821 switch (c) {
3822 case '\\':
3823 if (bp < limit) {
3824 if (*bp == '\n') {
3825 ip->lineno++;
3826 copy_directive = 1;
3827 bp++;
3828 } else if (traditional)
3829 bp++;
3831 break;
3833 case '\'':
3834 case '\"':
3835 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3836 /* Don't bother calling the directive if we already got an error
3837 message due to unterminated string. Skip everything and pretend
3838 we called the directive. */
3839 if (unterminated) {
3840 if (traditional) {
3841 /* Traditional preprocessing permits unterminated strings. */
3842 ip->bufp = bp;
3843 goto endloop1;
3845 ip->bufp = bp;
3846 return 1;
3848 break;
3850 /* <...> is special for #include. */
3851 case '<':
3852 if (!kt->angle_brackets)
3853 break;
3854 while (bp < limit && *bp != '>' && *bp != '\n') {
3855 if (*bp == '\\' && bp[1] == '\n') {
3856 ip->lineno++;
3857 copy_directive = 1;
3858 bp++;
3860 bp++;
3862 break;
3864 case '/':
3865 if (*bp == '\\' && bp[1] == '\n')
3866 newline_fix (bp);
3867 if (*bp == '*'
3868 || (cplusplus_comments && *bp == '/')) {
3869 U_CHAR *obp = bp - 1;
3870 ip->bufp = bp + 1;
3871 skip_to_end_of_comment (ip, &ip->lineno, 0);
3872 bp = ip->bufp;
3873 /* No need to copy the directive because of a comment at the end;
3874 just don't include the comment in the directive. */
3875 /* Start of code from future cccp.c added by AMB */
3876 if (!put_out_comments) {
3877 U_CHAR *p;
3878 for (p = bp; *p == ' ' || *p == '\t'; p++)
3879 continue;
3880 if (*p == '\n') {
3881 bp = obp;
3882 goto endloop1;
3885 /* End of code from future cccp.c added by AMB */
3886 /* Don't remove the comments if -traditional. */
3887 if (! keep_comments)
3888 copy_directive++;
3890 break;
3892 case '\f':
3893 case '\r':
3894 case '\v':
3895 if (pedantic)
3896 pedwarn ("%s in preprocessing directive", char_name[c]);
3897 break;
3899 case '\n':
3900 --bp; /* Point to the newline */
3901 ip->bufp = bp;
3902 goto endloop1;
3905 ip->bufp = bp;
3907 endloop1:
3908 resume_p = ip->bufp;
3909 /* BP is the end of the directive.
3910 RESUME_P is the next interesting data after the directive.
3911 A comment may come between. */
3913 /* If a directive should be copied through, and -E was given,
3914 pass it through before removing comments. */
3915 if (!no_output && put_out_comments &&
3916 /* Start new option added by AMB */
3917 (kt->pass_thru || (kt->type == T_INCLUDE && dump_includes))) {
3918 /* End new option added by AMB */
3919 int len;
3921 /* Output directive name. */
3922 check_expand (op, kt->length + 2);
3923 /* Make sure # is at the start of a line */
3924 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3925 op->lineno++;
3926 *op->bufp++ = '\n';
3928 *op->bufp++ = '#';
3929 bcopy (kt->name, op->bufp, kt->length);
3930 op->bufp += kt->length;
3932 /* Output arguments. */
3933 len = (bp - buf);
3934 check_expand (op, len);
3935 bcopy (buf, (char *) op->bufp, len);
3936 op->bufp += len;
3937 /* Take account of any (escaped) newlines just output. */
3938 while (--len >= 0)
3939 if (buf[len] == '\n')
3940 op->lineno++;
3942 already_output = &junk;
3943 } /* Don't we need a newline or #line? */
3945 if (copy_directive) {
3946 register U_CHAR *xp = buf;
3947 /* Need to copy entire directive into temp buffer before dispatching */
3949 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3950 some slop */
3951 buf = cp;
3953 /* Copy to the new buffer, deleting comments
3954 and backslash-newlines (and whitespace surrounding the latter). */
3956 while (xp < bp) {
3957 register U_CHAR c = *xp++;
3958 *cp++ = c;
3960 switch (c) {
3961 case '\n':
3962 abort (); /* A bare newline should never part of the line. */
3963 break;
3965 /* <...> is special for #include. */
3966 case '<':
3967 if (!kt->angle_brackets)
3968 break;
3969 while (xp < bp && c != '>') {
3970 c = *xp++;
3971 if (c == '\\' && xp < bp && *xp == '\n')
3972 xp++;
3973 else
3974 *cp++ = c;
3976 break;
3978 case '\\':
3979 if (*xp == '\n') {
3980 xp++;
3981 cp--;
3982 if (cp != buf && is_hor_space[cp[-1]]) {
3983 while (cp - 1 != buf && is_hor_space[cp[-2]])
3984 cp--;
3985 SKIP_WHITE_SPACE (xp);
3986 } else if (is_hor_space[*xp]) {
3987 *cp++ = *xp++;
3988 SKIP_WHITE_SPACE (xp);
3990 } else if (traditional && xp < bp) {
3991 *cp++ = *xp++;
3993 break;
3995 case '\'':
3996 case '\"':
3998 register U_CHAR *bp1
3999 = skip_quoted_string (xp - 1, bp, ip->lineno,
4000 NULL_PTR, NULL_PTR, NULL_PTR);
4001 while (xp != bp1)
4002 if (*xp == '\\') {
4003 if (*++xp != '\n')
4004 *cp++ = '\\';
4005 else
4006 xp++;
4007 } else
4008 *cp++ = *xp++;
4010 break;
4012 case '/':
4013 if (*xp == '*'
4014 || (cplusplus_comments && *xp == '/')) {
4015 ip->bufp = xp + 1;
4016 /* If we already copied the directive through,
4017 already_output != 0 prevents outputting comment now. */
4018 skip_to_end_of_comment (ip, already_output, 0);
4019 if (keep_comments)
4020 while (xp != ip->bufp)
4021 *cp++ = *xp++;
4022 /* Delete or replace the slash. */
4023 else if (traditional)
4024 cp--;
4025 else
4026 cp[-1] = ' ';
4027 xp = ip->bufp;
4032 /* Null-terminate the copy. */
4034 *cp = 0;
4035 } else
4036 cp = bp;
4038 ip->bufp = resume_p;
4040 /* Some directives should be written out for cc1 to process,
4041 just as if they were not defined. And sometimes we're copying
4042 definitions through. */
4044 if (!no_output && already_output == 0
4045 && (kt->pass_thru
4046 /* Start new option added by AMB */
4047 || (kt->type == T_INCLUDE
4048 && dump_includes)
4049 /* End new option added by AMB */
4050 || (kt->type == T_DEFINE
4051 && (dump_macros == dump_names
4052 || dump_macros == dump_definitions)))) {
4053 int len;
4055 /* Output directive name. */
4056 check_expand (op, kt->length + 1);
4057 *op->bufp++ = '#';
4058 bcopy (kt->name, (char *) op->bufp, kt->length);
4059 op->bufp += kt->length;
4061 if (kt->pass_thru || dump_macros == dump_definitions
4062 /* Start new option added by AMB */
4063 || dump_includes
4064 /* End new option added by AMB */
4066 /* Output arguments. */
4067 len = (cp - buf);
4068 check_expand (op, len);
4069 bcopy (buf, (char *) op->bufp, len);
4070 op->bufp += len;
4071 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
4072 U_CHAR *xp = buf;
4073 U_CHAR *yp;
4074 SKIP_WHITE_SPACE (xp);
4075 yp = xp;
4076 while (is_idchar[*xp]) xp++;
4077 len = (xp - yp);
4078 check_expand (op, len + 1);
4079 *op->bufp++ = ' ';
4080 bcopy (yp, op->bufp, len);
4081 op->bufp += len;
4083 } /* Don't we need a newline or #line? */
4085 /* Call the appropriate directive handler. buf now points to
4086 either the appropriate place in the input buffer, or to
4087 the temp buffer if it was necessary to make one. cp
4088 points to the first char after the contents of the (possibly
4089 copied) directive, in either case. */
4090 (*kt->func) (buf, cp, op, kt);
4091 check_expand (op, ip->length - (ip->bufp - ip->buf));
4093 return 1;
4097 /* It is deliberate that we don't warn about undefined directives.
4098 That is the responsibility of cc1. */
4099 return 0;
4102 static struct tm *
4103 timestamp ()
4105 static struct tm *timebuf;
4106 if (!timebuf) {
4107 time_t t = time ((time_t *)0);
4108 timebuf = localtime (&t);
4110 return timebuf;
4113 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4114 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4118 * expand things like __FILE__. Place the expansion into the output
4119 * buffer *without* rescanning.
4122 static void
4123 special_symbol (hp, op)
4124 HASHNODE *hp;
4125 FILE_BUF *op;
4127 char *buf;
4128 int i, len;
4129 int true_indepth;
4130 FILE_BUF *ip = NULL;
4131 struct tm *timebuf;
4133 int paren = 0; /* For special `defined' keyword */
4135 if (pcp_outfile && pcp_inside_if
4136 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4137 error ("Predefined macro `%s' used inside `#if' during precompilation",
4138 hp->name);
4140 for (i = indepth; i >= 0; i--)
4141 if (instack[i].fname != NULL) {
4142 ip = &instack[i];
4143 break;
4145 if (ip == NULL) {
4146 error ("cccp error: not in any file?!");
4147 return; /* the show must go on */
4150 switch (hp->type) {
4151 case T_FILE:
4152 case T_BASE_FILE:
4154 char *string;
4155 if (hp->type == T_FILE)
4156 string = ip->nominal_fname;
4157 else
4158 string = instack[0].nominal_fname;
4160 if (string)
4162 buf = (char *) alloca (3 + 4 * strlen (string));
4163 quote_string (buf, string);
4165 else
4166 buf = "\"\"";
4168 break;
4171 case T_INCLUDE_LEVEL:
4172 true_indepth = 0;
4173 for (i = indepth; i >= 0; i--)
4174 if (instack[i].fname != NULL)
4175 true_indepth++;
4177 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4178 sprintf (buf, "%d", true_indepth - 1);
4179 break;
4181 case T_VERSION:
4182 buf = (char *) alloca (3 + strlen (version_string));
4183 sprintf (buf, "\"%s\"", version_string);
4184 break;
4186 #ifndef NO_BUILTIN_SIZE_TYPE
4187 case T_SIZE_TYPE:
4188 buf = SIZE_TYPE;
4189 break;
4190 #endif
4192 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4193 case T_PTRDIFF_TYPE:
4194 buf = PTRDIFF_TYPE;
4195 break;
4196 #endif
4198 case T_WCHAR_TYPE:
4199 buf = wchar_type;
4200 break;
4202 case T_USER_LABEL_PREFIX_TYPE:
4203 buf = USER_LABEL_PREFIX;
4204 break;
4206 case T_REGISTER_PREFIX_TYPE:
4207 buf = REGISTER_PREFIX;
4208 break;
4210 case T_IMMEDIATE_PREFIX_TYPE:
4211 buf = IMMEDIATE_PREFIX;
4212 break;
4214 case T_CONST:
4215 buf = hp->value.cpval;
4216 if (pcp_inside_if && pcp_outfile)
4217 /* Output a precondition for this macro use */
4218 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4219 break;
4221 case T_SPECLINE:
4222 buf = (char *) alloca (10);
4223 sprintf (buf, "%d", ip->lineno);
4224 break;
4226 case T_DATE:
4227 case T_TIME:
4228 buf = (char *) alloca (20);
4229 timebuf = timestamp ();
4230 if (hp->type == T_DATE)
4231 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4232 timebuf->tm_mday, timebuf->tm_year + 1900);
4233 else
4234 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4235 timebuf->tm_sec);
4236 break;
4238 case T_SPEC_DEFINED:
4239 buf = " 0 "; /* Assume symbol is not defined */
4240 ip = &instack[indepth];
4241 SKIP_WHITE_SPACE (ip->bufp);
4242 if (*ip->bufp == '(') {
4243 paren++;
4244 ip->bufp++; /* Skip over the paren */
4245 SKIP_WHITE_SPACE (ip->bufp);
4248 if (!is_idstart[*ip->bufp])
4249 goto oops;
4250 if ((hp = lookup (ip->bufp, -1, -1))) {
4251 if (pcp_outfile && pcp_inside_if
4252 && (hp->type == T_CONST
4253 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4254 /* Output a precondition for this macro use. */
4255 fprintf (pcp_outfile, "#define %s\n", hp->name);
4256 buf = " 1 ";
4258 else
4259 if (pcp_outfile && pcp_inside_if) {
4260 /* Output a precondition for this macro use */
4261 U_CHAR *cp = ip->bufp;
4262 fprintf (pcp_outfile, "#undef ");
4263 while (is_idchar[*cp]) /* Ick! */
4264 fputc (*cp++, pcp_outfile);
4265 putc ('\n', pcp_outfile);
4267 while (is_idchar[*ip->bufp])
4268 ++ip->bufp;
4269 SKIP_WHITE_SPACE (ip->bufp);
4270 if (paren) {
4271 if (*ip->bufp != ')')
4272 goto oops;
4273 ++ip->bufp;
4275 break;
4277 oops:
4279 error ("`defined' without an identifier");
4280 break;
4282 default:
4283 error ("cccp error: invalid special hash type"); /* time for gdb */
4284 abort ();
4286 len = strlen (buf);
4287 check_expand (op, len);
4288 bcopy (buf, (char *) op->bufp, len);
4289 op->bufp += len;
4291 return;
4295 /* Routines to handle #directives */
4297 /* Handle #include and #import.
4298 This function expects to see "fname" or <fname> on the input. */
4300 static int
4301 do_include (buf, limit, op, keyword)
4302 U_CHAR *buf, *limit;
4303 FILE_BUF *op;
4304 struct directive *keyword;
4306 int importing = (keyword->type == T_IMPORT);
4307 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4308 static int import_warning = 0;
4309 char *fname; /* Dynamically allocated fname buffer */
4310 char *pcftry;
4311 char *pcfname;
4312 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
4314 struct file_name_list *search_start = include; /* Chain of dirs to search */
4315 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4316 struct file_name_list *searchptr = 0;
4317 size_t flen;
4319 int f; /* file number */
4321 int retried = 0; /* Have already tried macro
4322 expanding the include line*/
4323 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4324 int pcf = -1;
4325 char *pcfbuf;
4326 char *pcfbuflimit;
4327 int pcfnum;
4328 f= -1; /* JF we iz paranoid! */
4330 if (importing && warn_import && !inhibit_warnings
4331 && !instack[indepth].system_header_p && !import_warning) {
4332 import_warning = 1;
4333 warning ("using `#import' is not recommended");
4334 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4335 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4336 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4337 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4338 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4339 fprintf (stderr, " ... <real contents of file> ...\n");
4340 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4341 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4342 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4343 fprintf (stderr, "when it is equipped with such a conditional.\n");
4346 get_filename:
4348 fbeg = buf;
4349 SKIP_WHITE_SPACE (fbeg);
4350 /* Discard trailing whitespace so we can easily see
4351 if we have parsed all the significant chars we were given. */
4352 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
4354 switch (*fbeg++) {
4355 case '\"':
4357 FILE_BUF *fp;
4358 /* Copy the operand text, concatenating the strings. */
4360 U_CHAR *fin = fbeg;
4361 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
4362 fend = fbeg;
4363 while (fin != limit) {
4364 while (fin != limit && *fin != '\"')
4365 *fend++ = *fin++;
4366 fin++;
4367 if (fin == limit)
4368 break;
4369 /* If not at the end, there had better be another string. */
4370 /* Skip just horiz space, and don't go past limit. */
4371 while (fin != limit && is_hor_space[*fin]) fin++;
4372 if (fin != limit && *fin == '\"')
4373 fin++;
4374 else
4375 goto fail;
4378 *fend = 0;
4380 /* We have "filename". Figure out directory this source
4381 file is coming from and put it on the front of the list. */
4383 /* If -I- was specified, don't search current dir, only spec'd ones. */
4384 if (ignore_srcdir) break;
4386 for (fp = &instack[indepth]; fp >= instack; fp--)
4388 int n;
4389 char *ep,*nam;
4391 if ((nam = fp->nominal_fname) != NULL) {
4392 /* Found a named file. Figure out dir of the file,
4393 and put it in front of the search list. */
4394 dsp[0].next = search_start;
4395 search_start = dsp;
4396 #ifndef VMS
4397 ep = rindex (nam, '/');
4398 #ifdef DIR_SEPARATOR
4399 if (ep == NULL) ep = rindex (nam, DIR_SEPARATOR);
4400 else {
4401 char *tmp = rindex (nam, DIR_SEPARATOR);
4402 if (tmp != NULL && tmp > ep) ep = tmp;
4404 #endif
4405 #else /* VMS */
4406 ep = rindex (nam, ']');
4407 if (ep == NULL) ep = rindex (nam, '>');
4408 if (ep == NULL) ep = rindex (nam, ':');
4409 if (ep != NULL) ep++;
4410 #endif /* VMS */
4411 if (ep != NULL) {
4412 n = ep - nam;
4413 dsp[0].fname = (char *) alloca (n + 1);
4414 strncpy (dsp[0].fname, nam, n);
4415 dsp[0].fname[n] = '\0';
4416 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4417 max_include_len = n + INCLUDE_LEN_FUDGE;
4418 } else {
4419 dsp[0].fname = 0; /* Current directory */
4421 dsp[0].got_name_map = 0;
4422 break;
4425 break;
4428 case '<':
4429 fend = fbeg;
4430 while (fend != limit && *fend != '>') fend++;
4431 if (*fend == '>' && fend + 1 == limit) {
4432 angle_brackets = 1;
4433 /* If -I-, start with the first -I dir after the -I-. */
4434 if (first_bracket_include)
4435 search_start = first_bracket_include;
4436 break;
4438 goto fail;
4440 default:
4441 #ifdef VMS
4443 * Support '#include xyz' like VAX-C to allow for easy use of all the
4444 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4445 * code from case '<' is repeated here) and generates a warning.
4446 * (Note: macro expansion of `xyz' takes precedence.)
4448 if (retried && isalpha(*(--fbeg))) {
4449 fend = fbeg;
4450 while (fend != limit && (!isspace(*fend))) fend++;
4451 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4452 if (fend == limit) {
4453 angle_brackets = 1;
4454 /* If -I-, start with the first -I dir after the -I-. */
4455 if (first_bracket_include)
4456 search_start = first_bracket_include;
4457 break;
4460 #endif
4462 fail:
4463 if (retried) {
4464 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4465 return 0;
4466 } else {
4467 /* Expand buffer and then remove any newline markers.
4468 We can't just tell expand_to_temp_buffer to omit the markers,
4469 since it would put extra spaces in include file names. */
4470 FILE_BUF trybuf;
4471 U_CHAR *src;
4472 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4473 src = trybuf.buf;
4474 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4475 limit = buf;
4476 while (src != trybuf.bufp) {
4477 switch ((*limit++ = *src++)) {
4478 case '\n':
4479 limit--;
4480 src++;
4481 break;
4483 case '\'':
4484 case '\"':
4486 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4487 NULL_PTR, NULL_PTR, NULL_PTR);
4488 while (src != src1)
4489 *limit++ = *src++;
4491 break;
4494 *limit = 0;
4495 free (trybuf.buf);
4496 retried++;
4497 goto get_filename;
4501 /* For #include_next, skip in the search path
4502 past the dir in which the containing file was found. */
4503 if (skip_dirs) {
4504 FILE_BUF *fp;
4505 for (fp = &instack[indepth]; fp >= instack; fp--)
4506 if (fp->fname != NULL) {
4507 /* fp->dir is null if the containing file was specified
4508 with an absolute file name. In that case, don't skip anything. */
4509 if (fp->dir)
4510 search_start = fp->dir->next;
4511 break;
4515 flen = fend - fbeg;
4517 if (flen == 0)
4519 error ("empty file name in `#%s'", keyword->name);
4520 return 0;
4523 /* Allocate this permanently, because it gets stored in the definitions
4524 of macros. */
4525 fname = xmalloc (max_include_len + flen + 4);
4526 /* + 2 above for slash and terminating null. */
4527 /* + 2 added for '.h' on VMS (to support '#include filename') */
4529 /* If specified file name is absolute, just open it. */
4531 if (*fbeg == '/'
4532 #ifdef DIR_SEPARATOR
4533 || *fbeg == DIR_SEPARATOR
4534 #endif
4536 strncpy (fname, (char *) fbeg, flen);
4537 fname[flen] = 0;
4538 if (redundant_include_p (fname))
4539 return 0;
4540 if (importing)
4541 f = lookup_import (fname, NULL_PTR);
4542 else
4543 f = open_include_file (fname, NULL_PTR);
4544 if (f == -2)
4545 return 0; /* Already included this file */
4546 } else {
4547 /* Search directory path, trying to open the file.
4548 Copy each filename tried into FNAME. */
4550 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4551 if (searchptr->fname) {
4552 /* The empty string in a search path is ignored.
4553 This makes it possible to turn off entirely
4554 a standard piece of the list. */
4555 if (searchptr->fname[0] == 0)
4556 continue;
4557 strcpy (fname, skip_redundant_dir_prefix (searchptr->fname));
4558 if (fname[0] && fname[strlen (fname) - 1] != '/')
4559 strcat (fname, "/");
4560 } else {
4561 fname[0] = 0;
4563 strncat (fname, (char *) fbeg, flen);
4564 #ifdef VMS
4565 /* Change this 1/2 Unix 1/2 VMS file specification into a
4566 full VMS file specification */
4567 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4568 /* Fix up the filename */
4569 hack_vms_include_specification (fname);
4570 } else {
4571 /* This is a normal VMS filespec, so use it unchanged. */
4572 strncpy (fname, fbeg, flen);
4573 fname[flen] = 0;
4574 /* if it's '#include filename', add the missing .h */
4575 if (index(fname,'.')==NULL) {
4576 strcat (fname, ".h");
4579 #endif /* VMS */
4580 /* ??? There are currently 3 separate mechanisms for avoiding processing
4581 of redundant include files: #import, #pragma once, and
4582 redundant_include_p. It would be nice if they were unified. */
4583 if (redundant_include_p (fname))
4584 return 0;
4585 if (importing)
4586 f = lookup_import (fname, searchptr);
4587 else
4588 f = open_include_file (fname, searchptr);
4589 if (f == -2)
4590 return 0; /* Already included this file */
4591 #ifdef EACCES
4592 else if (f == -1 && errno == EACCES)
4593 warning ("Header file %s exists, but is not readable", fname);
4594 #endif
4595 if (f >= 0)
4596 break;
4600 if (f < 0) {
4601 /* A file that was not found. */
4603 strncpy (fname, (char *) fbeg, flen);
4604 fname[flen] = 0;
4605 /* If generating dependencies and -MG was specified, we assume missing
4606 files are leaf files, living in the same directory as the source file
4607 or other similar place; these missing files may be generated from
4608 other files and may not exist yet (eg: y.tab.h). */
4609 if (print_deps_missing_files
4610 && print_deps > (angle_brackets || (system_include_depth > 0)))
4612 /* If it was requested as a system header file,
4613 then assume it belongs in the first place to look for such. */
4614 if (angle_brackets)
4616 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
4618 if (searchptr->fname)
4620 char *p;
4622 if (searchptr->fname[0] == 0)
4623 continue;
4624 p = (char *) alloca (strlen (searchptr->fname)
4625 + strlen (fname) + 2);
4626 strcpy (p, skip_redundant_dir_prefix (searchptr->fname));
4627 if (p[0] && p[strlen (p) - 1] != '/')
4628 strcat (p, "/");
4629 strcat (p, fname);
4630 deps_output (p, ' ');
4631 break;
4635 else
4637 /* Otherwise, omit the directory, as if the file existed
4638 in the directory with the source. */
4639 deps_output (fname, ' ');
4642 /* If -M was specified, and this header file won't be added to the
4643 dependency list, then don't count this as an error, because we can
4644 still produce correct output. Otherwise, we can't produce correct
4645 output, because there may be dependencies we need inside the missing
4646 file, and we don't know what directory this missing file exists in. */
4647 else if (print_deps
4648 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4649 warning ("No include path in which to find %s", fname);
4650 else if (search_start)
4651 error_from_errno (fname);
4652 else
4653 error ("No include path in which to find %s", fname);
4654 } else {
4655 /* Check to see if this include file is a once-only include file.
4656 If so, give up. */
4658 struct file_name_list* ptr;
4660 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4661 if (!strcmp (ptr->fname, fname)) {
4662 close (f);
4663 return 0; /* This file was once'd. */
4667 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4668 if (!strcmp (ptr->fname, fname))
4669 break; /* This file was included before. */
4672 if (ptr == 0) {
4673 /* This is the first time for this file. */
4674 /* Add it to list of files included. */
4676 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4677 ptr->control_macro = 0;
4678 ptr->c_system_include_path = 0;
4679 ptr->next = all_include_files;
4680 all_include_files = ptr;
4681 ptr->fname = savestring (fname);
4682 ptr->got_name_map = 0;
4684 /* For -M, add this file to the dependencies. */
4685 if (print_deps > (angle_brackets || (system_include_depth > 0)))
4686 deps_output (fname, ' ');
4689 /* Handle -H option. */
4690 if (print_include_names)
4691 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4693 if (angle_brackets)
4694 system_include_depth++;
4696 /* Actually process the file. */
4697 add_import (f, fname); /* Record file on "seen" list for #import. */
4699 pcftry = (char *) alloca (strlen (fname) + 30);
4700 pcfbuf = 0;
4701 pcfnum = 0;
4703 if (!no_precomp)
4705 struct stat stat_f;
4707 fstat (f, &stat_f);
4709 do {
4710 sprintf (pcftry, "%s%d", fname, pcfnum++);
4712 pcf = open (pcftry, O_RDONLY, 0666);
4713 if (pcf != -1)
4715 struct stat s;
4717 fstat (pcf, &s);
4718 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
4719 sizeof (s.st_ino))
4720 || stat_f.st_dev != s.st_dev)
4722 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4723 /* Don't need it any more. */
4724 close (pcf);
4726 else
4728 /* Don't need it at all. */
4729 close (pcf);
4730 break;
4733 } while (pcf != -1 && !pcfbuf);
4736 /* Actually process the file */
4737 if (pcfbuf) {
4738 pcfname = xmalloc (strlen (pcftry) + 1);
4739 strcpy (pcfname, pcftry);
4740 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4741 (U_CHAR *) fname, op);
4743 else
4744 finclude (f, fname, op, is_system_include (fname), searchptr);
4746 if (angle_brackets)
4747 system_include_depth--;
4749 return 0;
4752 /* Return nonzero if there is no need to include file NAME
4753 because it has already been included and it contains a conditional
4754 to make a repeated include do nothing. */
4756 static int
4757 redundant_include_p (name)
4758 char *name;
4760 struct file_name_list *l = all_include_files;
4761 for (; l; l = l->next)
4762 if (! strcmp (name, l->fname)
4763 && l->control_macro
4764 && lookup (l->control_macro, -1, -1))
4765 return 1;
4766 return 0;
4769 /* Return nonzero if the given FILENAME is an absolute pathname which
4770 designates a file within one of the known "system" include file
4771 directories. We assume here that if the given FILENAME looks like
4772 it is the name of a file which resides either directly in a "system"
4773 include file directory, or within any subdirectory thereof, then the
4774 given file must be a "system" include file. This function tells us
4775 if we should suppress pedantic errors/warnings for the given FILENAME.
4777 The value is 2 if the file is a C-language system header file
4778 for which C++ should (on most systems) assume `extern "C"'. */
4780 static int
4781 is_system_include (filename)
4782 register char *filename;
4784 struct file_name_list *searchptr;
4786 for (searchptr = first_system_include; searchptr;
4787 searchptr = searchptr->next)
4788 if (searchptr->fname) {
4789 register char *sys_dir = skip_redundant_dir_prefix (searchptr->fname);
4790 register unsigned length = strlen (sys_dir);
4792 if (! strncmp (sys_dir, filename, length)
4793 && (filename[length] == '/'
4794 #ifdef DIR_SEPARATOR
4795 || filename[length] == DIR_SEPARATOR
4796 #endif
4797 )) {
4798 if (searchptr->c_system_include_path)
4799 return 2;
4800 else
4801 return 1;
4804 return 0;
4807 /* Skip leading "./" from a directory name.
4808 This may yield the empty string, which represents the current directory. */
4810 static char *
4811 skip_redundant_dir_prefix (dir)
4812 char *dir;
4814 while (dir[0] == '.' && dir[1] == '/')
4815 for (dir += 2; *dir == '/'; dir++)
4816 continue;
4817 if (dir[0] == '.' && !dir[1])
4818 dir++;
4819 return dir;
4822 /* The file_name_map structure holds a mapping of file names for a
4823 particular directory. This mapping is read from the file named
4824 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4825 map filenames on a file system with severe filename restrictions,
4826 such as DOS. The format of the file name map file is just a series
4827 of lines with two tokens on each line. The first token is the name
4828 to map, and the second token is the actual name to use. */
4830 struct file_name_map
4832 struct file_name_map *map_next;
4833 char *map_from;
4834 char *map_to;
4837 #define FILE_NAME_MAP_FILE "header.gcc"
4839 /* Read a space delimited string of unlimited length from a stdio
4840 file. */
4842 static char *
4843 read_filename_string (ch, f)
4844 int ch;
4845 FILE *f;
4847 char *alloc, *set;
4848 int len;
4850 len = 20;
4851 set = alloc = xmalloc (len + 1);
4852 if (! is_space[ch])
4854 *set++ = ch;
4855 while ((ch = getc (f)) != EOF && ! is_space[ch])
4857 if (set - alloc == len)
4859 len *= 2;
4860 alloc = xrealloc (alloc, len + 1);
4861 set = alloc + len / 2;
4863 *set++ = ch;
4866 *set = '\0';
4867 ungetc (ch, f);
4868 return alloc;
4871 /* Read the file name map file for DIRNAME. */
4873 static struct file_name_map *
4874 read_name_map (dirname)
4875 char *dirname;
4877 /* This structure holds a linked list of file name maps, one per
4878 directory. */
4879 struct file_name_map_list
4881 struct file_name_map_list *map_list_next;
4882 char *map_list_name;
4883 struct file_name_map *map_list_map;
4885 static struct file_name_map_list *map_list;
4886 register struct file_name_map_list *map_list_ptr;
4887 char *name;
4888 FILE *f;
4889 size_t dirlen;
4890 int separator_needed;
4892 dirname = skip_redundant_dir_prefix (dirname);
4894 for (map_list_ptr = map_list; map_list_ptr;
4895 map_list_ptr = map_list_ptr->map_list_next)
4896 if (! strcmp (map_list_ptr->map_list_name, dirname))
4897 return map_list_ptr->map_list_map;
4899 map_list_ptr = ((struct file_name_map_list *)
4900 xmalloc (sizeof (struct file_name_map_list)));
4901 map_list_ptr->map_list_name = savestring (dirname);
4902 map_list_ptr->map_list_map = NULL;
4904 dirlen = strlen (dirname);
4905 separator_needed = dirlen != 0 && dirname[dirlen - 1] != '/';
4906 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 2);
4907 strcpy (name, dirname);
4908 name[dirlen] = '/';
4909 strcpy (name + dirlen + separator_needed, FILE_NAME_MAP_FILE);
4910 f = fopen (name, "r");
4911 if (!f)
4912 map_list_ptr->map_list_map = NULL;
4913 else
4915 int ch;
4917 while ((ch = getc (f)) != EOF)
4919 char *from, *to;
4920 struct file_name_map *ptr;
4922 if (is_space[ch])
4923 continue;
4924 from = read_filename_string (ch, f);
4925 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4927 to = read_filename_string (ch, f);
4929 ptr = ((struct file_name_map *)
4930 xmalloc (sizeof (struct file_name_map)));
4931 ptr->map_from = from;
4933 /* Make the real filename absolute. */
4934 if (*to == '/')
4935 ptr->map_to = to;
4936 else
4938 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
4939 strcpy (ptr->map_to, dirname);
4940 ptr->map_to[dirlen] = '/';
4941 strcpy (ptr->map_to + dirlen + separator_needed, to);
4942 free (to);
4945 ptr->map_next = map_list_ptr->map_list_map;
4946 map_list_ptr->map_list_map = ptr;
4948 while ((ch = getc (f)) != '\n')
4949 if (ch == EOF)
4950 break;
4952 fclose (f);
4955 map_list_ptr->map_list_next = map_list;
4956 map_list = map_list_ptr;
4958 return map_list_ptr->map_list_map;
4961 /* Try to open include file FILENAME. SEARCHPTR is the directory
4962 being tried from the include file search path. This function maps
4963 filenames on file systems based on information read by
4964 read_name_map. */
4966 static int
4967 open_include_file (filename, searchptr)
4968 char *filename;
4969 struct file_name_list *searchptr;
4971 register struct file_name_map *map;
4972 register char *from;
4973 char *p, *dir;
4975 if (searchptr && ! searchptr->got_name_map)
4977 searchptr->name_map = read_name_map (searchptr->fname
4978 ? searchptr->fname : ".");
4979 searchptr->got_name_map = 1;
4982 /* First check the mapping for the directory we are using. */
4983 if (searchptr && searchptr->name_map)
4985 from = filename;
4986 if (searchptr->fname)
4987 from += strlen (searchptr->fname) + 1;
4988 for (map = searchptr->name_map; map; map = map->map_next)
4990 if (! strcmp (map->map_from, from))
4992 /* Found a match. */
4993 return open (map->map_to, O_RDONLY, 0666);
4998 /* Try to find a mapping file for the particular directory we are
4999 looking in. Thus #include <sys/types.h> will look up sys/types.h
5000 in /usr/include/header.gcc and look up types.h in
5001 /usr/include/sys/header.gcc. */
5002 p = rindex (filename, '/');
5003 #ifdef DIR_SEPARATOR
5004 if (! p) p = rindex (filename, DIR_SEPARATOR);
5005 else {
5006 char *tmp = rindex (filename, DIR_SEPARATOR);
5007 if (tmp != NULL && tmp > p) p = tmp;
5009 #endif
5010 if (! p)
5011 p = filename;
5012 if (searchptr
5013 && searchptr->fname
5014 && strlen (searchptr->fname) == p - filename
5015 && ! strncmp (searchptr->fname, filename, p - filename))
5017 /* FILENAME is in SEARCHPTR, which we've already checked. */
5018 return open (filename, O_RDONLY, 0666);
5021 if (p == filename)
5023 dir = ".";
5024 from = filename;
5026 else
5028 dir = (char *) alloca (p - filename + 1);
5029 bcopy (filename, dir, p - filename);
5030 dir[p - filename] = '\0';
5031 from = p + 1;
5033 for (map = read_name_map (dir); map; map = map->map_next)
5034 if (! strcmp (map->map_from, from))
5035 return open (map->map_to, O_RDONLY, 0666);
5037 return open (filename, O_RDONLY, 0666);
5040 /* Process the contents of include file FNAME, already open on descriptor F,
5041 with output to OP.
5042 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5043 "system" include directories (as decided by the `is_system_include'
5044 function above).
5045 DIRPTR is the link in the dir path through which this file was found,
5046 or 0 if the file name was absolute. */
5048 static void
5049 finclude (f, fname, op, system_header_p, dirptr)
5050 int f;
5051 char *fname;
5052 FILE_BUF *op;
5053 int system_header_p;
5054 struct file_name_list *dirptr;
5056 int st_mode;
5057 long st_size;
5058 long i;
5059 FILE_BUF *fp; /* For input stack frame */
5060 int missing_newline = 0;
5062 CHECK_DEPTH (return;);
5064 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
5066 perror_with_name (fname);
5067 close (f);
5068 return;
5071 fp = &instack[indepth + 1];
5072 bzero ((char *) fp, sizeof (FILE_BUF));
5073 fp->nominal_fname = fp->fname = fname;
5074 fp->length = 0;
5075 fp->lineno = 1;
5076 fp->if_stack = if_stack;
5077 fp->system_header_p = system_header_p;
5078 fp->dir = dirptr;
5080 if (S_ISREG (st_mode)) {
5081 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
5082 fp->bufp = fp->buf;
5084 /* Read the file contents, knowing that st_size is an upper bound
5085 on the number of bytes we can read. */
5086 fp->length = safe_read (f, (char *) fp->buf, st_size);
5087 if (fp->length < 0) goto nope;
5089 else if (S_ISDIR (st_mode)) {
5090 error ("directory `%s' specified in #include", fname);
5091 close (f);
5092 return;
5093 } else {
5094 /* Cannot count its file size before reading.
5095 First read the entire file into heap and
5096 copy them into buffer on stack. */
5098 int bsize = 2000;
5100 st_size = 0;
5101 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5103 for (;;) {
5104 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5105 if (i < 0)
5106 goto nope; /* error! */
5107 st_size += i;
5108 if (st_size != bsize)
5109 break; /* End of file */
5110 bsize *= 2;
5111 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5113 fp->bufp = fp->buf;
5114 fp->length = st_size;
5117 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5118 /* Backslash-newline at end is not good enough. */
5119 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5120 fp->buf[fp->length++] = '\n';
5121 missing_newline = 1;
5123 fp->buf[fp->length] = '\0';
5125 /* Close descriptor now, so nesting does not use lots of descriptors. */
5126 close (f);
5128 /* Must do this before calling trigraph_pcp, so that the correct file name
5129 will be printed in warning messages. */
5131 indepth++;
5132 input_file_stack_tick++;
5134 if (!no_trigraphs)
5135 trigraph_pcp (fp);
5137 output_line_directive (fp, op, 0, enter_file);
5138 rescan (op, 0);
5140 if (missing_newline)
5141 fp->lineno--;
5143 if (pedantic && missing_newline)
5144 pedwarn ("file does not end in newline");
5146 indepth--;
5147 input_file_stack_tick++;
5148 output_line_directive (&instack[indepth], op, 0, leave_file);
5149 free (fp->buf);
5150 return;
5152 nope:
5154 perror_with_name (fname);
5155 close (f);
5156 free (fp->buf);
5159 /* Record that inclusion of the file named FILE
5160 should be controlled by the macro named MACRO_NAME.
5161 This means that trying to include the file again
5162 will do something if that macro is defined. */
5164 static void
5165 record_control_macro (file, macro_name)
5166 char *file;
5167 U_CHAR *macro_name;
5169 struct file_name_list *new;
5171 for (new = all_include_files; new; new = new->next) {
5172 if (!strcmp (new->fname, file)) {
5173 new->control_macro = macro_name;
5174 return;
5178 /* If the file is not in all_include_files, something's wrong. */
5179 abort ();
5182 /* Maintain and search list of included files, for #import. */
5184 #define IMPORT_HASH_SIZE 31
5186 struct import_file {
5187 char *name;
5188 ino_t inode;
5189 dev_t dev;
5190 struct import_file *next;
5193 /* Hash table of files already included with #include or #import. */
5195 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
5197 /* Hash a file name for import_hash_table. */
5199 static int
5200 import_hash (f)
5201 char *f;
5203 int val = 0;
5205 while (*f) val += *f++;
5206 return (val%IMPORT_HASH_SIZE);
5209 /* Search for file FILENAME in import_hash_table.
5210 Return -2 if found, either a matching name or a matching inode.
5211 Otherwise, open the file and return a file descriptor if successful
5212 or -1 if unsuccessful. */
5214 static int
5215 lookup_import (filename, searchptr)
5216 char *filename;
5217 struct file_name_list *searchptr;
5219 struct import_file *i;
5220 int h;
5221 int hashval;
5222 struct stat sb;
5223 int fd;
5225 hashval = import_hash (filename);
5227 /* Attempt to find file in list of already included files */
5228 i = import_hash_table[hashval];
5230 while (i) {
5231 if (!strcmp (filename, i->name))
5232 return -2; /* return found */
5233 i = i->next;
5235 /* Open it and try a match on inode/dev */
5236 fd = open_include_file (filename, searchptr);
5237 if (fd < 0)
5238 return fd;
5239 fstat (fd, &sb);
5240 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
5241 i = import_hash_table[h];
5242 while (i) {
5243 /* Compare the inode and the device.
5244 Supposedly on some systems the inode is not a scalar. */
5245 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
5246 && i->dev == sb.st_dev) {
5247 close (fd);
5248 return -2; /* return found */
5250 i = i->next;
5253 return fd; /* Not found, return open file */
5256 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
5258 static void
5259 add_import (fd, fname)
5260 int fd;
5261 char *fname;
5263 struct import_file *i;
5264 int hashval;
5265 struct stat sb;
5267 hashval = import_hash (fname);
5268 fstat (fd, &sb);
5269 i = (struct import_file *)xmalloc (sizeof (struct import_file));
5270 i->name = xmalloc (strlen (fname)+1);
5271 strcpy (i->name, fname);
5272 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5273 i->dev = sb.st_dev;
5274 i->next = import_hash_table[hashval];
5275 import_hash_table[hashval] = i;
5278 /* Load the specified precompiled header into core, and verify its
5279 preconditions. PCF indicates the file descriptor to read, which must
5280 be a regular file. FNAME indicates the file name of the original
5281 header. *LIMIT will be set to an address one past the end of the file.
5282 If the preconditions of the file are not satisfied, the buffer is
5283 freed and we return 0. If the preconditions are satisfied, return
5284 the address of the buffer following the preconditions. The buffer, in
5285 this case, should never be freed because various pieces of it will
5286 be referred to until all precompiled strings are output at the end of
5287 the run.
5289 static char *
5290 check_precompiled (pcf, fname, limit)
5291 int pcf;
5292 char *fname;
5293 char **limit;
5295 int st_mode;
5296 long st_size;
5297 int length = 0;
5298 char *buf;
5299 char *cp;
5301 if (pcp_outfile)
5302 return 0;
5304 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
5305 return 0;
5307 if (S_ISREG (st_mode))
5309 buf = xmalloc (st_size + 2);
5310 length = safe_read (pcf, buf, st_size);
5311 if (length < 0)
5312 goto nope;
5314 else
5315 abort ();
5317 if (length > 0 && buf[length-1] != '\n')
5318 buf[length++] = '\n';
5319 buf[length] = '\0';
5321 *limit = buf + length;
5323 /* File is in core. Check the preconditions. */
5324 if (!check_preconditions (buf))
5325 goto nope;
5326 for (cp = buf; *cp; cp++)
5328 #ifdef DEBUG_PCP
5329 fprintf (stderr, "Using preinclude %s\n", fname);
5330 #endif
5331 return cp + 1;
5333 nope:
5334 #ifdef DEBUG_PCP
5335 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5336 #endif
5337 free (buf);
5338 return 0;
5341 /* PREC (null terminated) points to the preconditions of a
5342 precompiled header. These are a series of #define and #undef
5343 lines which must match the current contents of the hash
5344 table. */
5345 static int
5346 check_preconditions (prec)
5347 char *prec;
5349 MACRODEF mdef;
5350 char *lineend;
5352 while (*prec) {
5353 lineend = index (prec, '\n');
5355 if (*prec++ != '#') {
5356 error ("Bad format encountered while reading precompiled file");
5357 return 0;
5359 if (!strncmp (prec, "define", 6)) {
5360 HASHNODE *hp;
5362 prec += 6;
5363 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5365 if (mdef.defn == 0)
5366 abort ();
5368 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5369 || (hp->type != T_MACRO && hp->type != T_CONST)
5370 || (hp->type == T_MACRO
5371 && !compare_defs (mdef.defn, hp->value.defn)
5372 && (mdef.defn->length != 2
5373 || mdef.defn->expansion[0] != '\n'
5374 || mdef.defn->expansion[1] != ' ')))
5375 return 0;
5376 } else if (!strncmp (prec, "undef", 5)) {
5377 char *name;
5378 int len;
5380 prec += 5;
5381 while (is_hor_space[(U_CHAR) *prec])
5382 prec++;
5383 name = prec;
5384 while (is_idchar[(U_CHAR) *prec])
5385 prec++;
5386 len = prec - name;
5388 if (lookup ((U_CHAR *) name, len, -1))
5389 return 0;
5390 } else {
5391 error ("Bad format encountered while reading precompiled file");
5392 return 0;
5394 prec = lineend + 1;
5396 /* They all passed successfully */
5397 return 1;
5400 /* Process the main body of a precompiled file. BUF points to the
5401 string section of the file, following the preconditions. LIMIT is one
5402 character past the end. NAME is the name of the file being read
5403 in. OP is the main output buffer */
5404 static void
5405 pcfinclude (buf, limit, name, op)
5406 U_CHAR *buf, *limit, *name;
5407 FILE_BUF *op;
5409 FILE_BUF tmpbuf;
5410 int nstrings;
5411 U_CHAR *cp = buf;
5413 /* First in the file comes 4 bytes indicating the number of strings, */
5414 /* in network byte order. (MSB first). */
5415 nstrings = *cp++;
5416 nstrings = (nstrings << 8) | *cp++;
5417 nstrings = (nstrings << 8) | *cp++;
5418 nstrings = (nstrings << 8) | *cp++;
5420 /* Looping over each string... */
5421 while (nstrings--) {
5422 U_CHAR *string_start;
5423 U_CHAR *endofthiskey;
5424 STRINGDEF *str;
5425 int nkeys;
5427 /* Each string starts with a STRINGDEF structure (str), followed */
5428 /* by the text of the string (string_start) */
5430 /* First skip to a longword boundary */
5431 /* ??? Why a 4-byte boundary? On all machines? */
5432 /* NOTE: This works correctly even if HOST_WIDE_INT
5433 is narrower than a pointer.
5434 Do not try risky measures here to get another type to use!
5435 Do not include stddef.h--it will fail! */
5436 if ((HOST_WIDE_INT) cp & 3)
5437 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5439 /* Now get the string. */
5440 str = (STRINGDEF *) (GENERIC_PTR) cp;
5441 string_start = cp += sizeof (STRINGDEF);
5443 for (; *cp; cp++) /* skip the string */
5446 /* We need to macro expand the string here to ensure that the
5447 proper definition environment is in place. If it were only
5448 expanded when we find out it is needed, macros necessary for
5449 its proper expansion might have had their definitions changed. */
5450 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5451 /* Lineno is already set in the precompiled file */
5452 str->contents = tmpbuf.buf;
5453 str->len = tmpbuf.length;
5454 str->writeflag = 0;
5455 str->filename = name;
5456 str->output_mark = outbuf.bufp - outbuf.buf;
5458 str->chain = 0;
5459 *stringlist_tailp = str;
5460 stringlist_tailp = &str->chain;
5462 /* Next comes a fourbyte number indicating the number of keys */
5463 /* for this string. */
5464 nkeys = *cp++;
5465 nkeys = (nkeys << 8) | *cp++;
5466 nkeys = (nkeys << 8) | *cp++;
5467 nkeys = (nkeys << 8) | *cp++;
5469 /* If this number is -1, then the string is mandatory. */
5470 if (nkeys == -1)
5471 str->writeflag = 1;
5472 else
5473 /* Otherwise, for each key, */
5474 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5475 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5476 HASHNODE *hp;
5478 /* It starts with a KEYDEF structure */
5479 cp += sizeof (KEYDEF);
5481 /* Find the end of the key. At the end of this for loop we
5482 advance CP to the start of the next key using this variable. */
5483 endofthiskey = cp + strlen ((char *) cp);
5484 kp->str = str;
5486 /* Expand the key, and enter it into the hash table. */
5487 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5488 tmpbuf.bufp = tmpbuf.buf;
5490 while (is_hor_space[*tmpbuf.bufp])
5491 tmpbuf.bufp++;
5492 if (!is_idstart[*tmpbuf.bufp]
5493 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5494 str->writeflag = 1;
5495 continue;
5498 hp = lookup (tmpbuf.bufp, -1, -1);
5499 if (hp == NULL) {
5500 kp->chain = 0;
5501 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5503 else if (hp->type == T_PCSTRING) {
5504 kp->chain = hp->value.keydef;
5505 hp->value.keydef = kp;
5507 else
5508 str->writeflag = 1;
5511 /* This output_line_directive serves to switch us back to the current
5512 input file in case some of these strings get output (which will
5513 result in line directives for the header file being output). */
5514 output_line_directive (&instack[indepth], op, 0, enter_file);
5517 /* Called from rescan when it hits a key for strings. Mark them all */
5518 /* used and clean up. */
5519 static void
5520 pcstring_used (hp)
5521 HASHNODE *hp;
5523 KEYDEF *kp;
5525 for (kp = hp->value.keydef; kp; kp = kp->chain)
5526 kp->str->writeflag = 1;
5527 delete_macro (hp);
5530 /* Write the output, interspersing precompiled strings in their */
5531 /* appropriate places. */
5532 static void
5533 write_output ()
5535 STRINGDEF *next_string;
5536 U_CHAR *cur_buf_loc;
5537 int line_directive_len = 80;
5538 char *line_directive = xmalloc (line_directive_len);
5539 int len;
5541 /* In each run through the loop, either cur_buf_loc == */
5542 /* next_string_loc, in which case we print a series of strings, or */
5543 /* it is less than next_string_loc, in which case we write some of */
5544 /* the buffer. */
5545 cur_buf_loc = outbuf.buf;
5546 next_string = stringlist;
5548 while (cur_buf_loc < outbuf.bufp || next_string) {
5549 if (next_string
5550 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5551 if (next_string->writeflag) {
5552 len = 4 * strlen ((char *) next_string->filename) + 32;
5553 while (len > line_directive_len)
5554 line_directive = xrealloc (line_directive,
5555 line_directive_len *= 2);
5556 sprintf (line_directive, "\n# %d ", next_string->lineno);
5557 strcpy (quote_string (line_directive + strlen (line_directive),
5558 (char *) next_string->filename),
5559 "\n");
5560 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5561 safe_write (fileno (stdout),
5562 (char *) next_string->contents, next_string->len);
5564 next_string = next_string->chain;
5566 else {
5567 len = (next_string
5568 ? (next_string->output_mark
5569 - (cur_buf_loc - outbuf.buf))
5570 : outbuf.bufp - cur_buf_loc);
5572 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5573 cur_buf_loc += len;
5576 free (line_directive);
5579 /* Pass a directive through to the output file.
5580 BUF points to the contents of the directive, as a contiguous string.
5581 LIMIT points to the first character past the end of the directive.
5582 KEYWORD is the keyword-table entry for the directive. */
5584 static void
5585 pass_thru_directive (buf, limit, op, keyword)
5586 U_CHAR *buf, *limit;
5587 FILE_BUF *op;
5588 struct directive *keyword;
5590 register unsigned keyword_length = keyword->length;
5592 check_expand (op, 1 + keyword_length + (limit - buf));
5593 *op->bufp++ = '#';
5594 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5595 op->bufp += keyword_length;
5596 if (limit != buf && buf[0] != ' ')
5597 *op->bufp++ = ' ';
5598 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5599 op->bufp += (limit - buf);
5600 #if 0
5601 *op->bufp++ = '\n';
5602 /* Count the line we have just made in the output,
5603 to get in sync properly. */
5604 op->lineno++;
5605 #endif
5608 /* The arglist structure is built by do_define to tell
5609 collect_definition where the argument names begin. That
5610 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5611 would contain pointers to the strings x, y, and z.
5612 Collect_definition would then build a DEFINITION node,
5613 with reflist nodes pointing to the places x, y, and z had
5614 appeared. So the arglist is just convenience data passed
5615 between these two routines. It is not kept around after
5616 the current #define has been processed and entered into the
5617 hash table. */
5619 struct arglist {
5620 struct arglist *next;
5621 U_CHAR *name;
5622 int length;
5623 int argno;
5624 char rest_args;
5627 /* Create a DEFINITION node from a #define directive. Arguments are
5628 as for do_define. */
5629 static MACRODEF
5630 create_definition (buf, limit, op)
5631 U_CHAR *buf, *limit;
5632 FILE_BUF *op;
5634 U_CHAR *bp; /* temp ptr into input buffer */
5635 U_CHAR *symname; /* remember where symbol name starts */
5636 int sym_length; /* and how long it is */
5637 int line = instack[indepth].lineno;
5638 char *file = instack[indepth].nominal_fname;
5639 int rest_args = 0;
5641 DEFINITION *defn;
5642 int arglengths = 0; /* Accumulate lengths of arg names
5643 plus number of args. */
5644 MACRODEF mdef;
5646 bp = buf;
5648 while (is_hor_space[*bp])
5649 bp++;
5651 symname = bp; /* remember where it starts */
5652 sym_length = check_macro_name (bp, "macro");
5653 bp += sym_length;
5655 /* Lossage will occur if identifiers or control keywords are broken
5656 across lines using backslash. This is not the right place to take
5657 care of that. */
5659 if (*bp == '(') {
5660 struct arglist *arg_ptrs = NULL;
5661 int argno = 0;
5663 bp++; /* skip '(' */
5664 SKIP_WHITE_SPACE (bp);
5666 /* Loop over macro argument names. */
5667 while (*bp != ')') {
5668 struct arglist *temp;
5670 temp = (struct arglist *) alloca (sizeof (struct arglist));
5671 temp->name = bp;
5672 temp->next = arg_ptrs;
5673 temp->argno = argno++;
5674 temp->rest_args = 0;
5675 arg_ptrs = temp;
5677 if (rest_args)
5678 pedwarn ("another parameter follows `%s'",
5679 rest_extension);
5681 if (!is_idstart[*bp])
5682 pedwarn ("invalid character in macro parameter name");
5684 /* Find the end of the arg name. */
5685 while (is_idchar[*bp]) {
5686 bp++;
5687 /* do we have a "special" rest-args extension here? */
5688 if (limit - bp > REST_EXTENSION_LENGTH &&
5689 bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5690 rest_args = 1;
5691 temp->rest_args = 1;
5692 break;
5695 temp->length = bp - temp->name;
5696 if (rest_args == 1)
5697 bp += REST_EXTENSION_LENGTH;
5698 arglengths += temp->length + 2;
5699 SKIP_WHITE_SPACE (bp);
5700 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5701 error ("badly punctuated parameter list in `#define'");
5702 goto nope;
5704 if (*bp == ',') {
5705 bp++;
5706 SKIP_WHITE_SPACE (bp);
5707 /* A comma at this point can only be followed by an identifier. */
5708 if (!is_idstart[*bp]) {
5709 error ("badly punctuated parameter list in `#define'");
5710 goto nope;
5713 if (bp >= limit) {
5714 error ("unterminated parameter list in `#define'");
5715 goto nope;
5718 struct arglist *otemp;
5720 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5721 if (temp->length == otemp->length &&
5722 bcmp (temp->name, otemp->name, temp->length) == 0) {
5723 error ("duplicate argument name `%.*s' in `#define'",
5724 temp->length, temp->name);
5725 goto nope;
5730 ++bp; /* skip paren */
5731 SKIP_WHITE_SPACE (bp);
5732 /* now everything from bp before limit is the definition. */
5733 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5734 defn->rest_args = rest_args;
5736 /* Now set defn->args.argnames to the result of concatenating
5737 the argument names in reverse order
5738 with comma-space between them. */
5739 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5741 struct arglist *temp;
5742 int i = 0;
5743 for (temp = arg_ptrs; temp; temp = temp->next) {
5744 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5745 i += temp->length;
5746 if (temp->next != 0) {
5747 defn->args.argnames[i++] = ',';
5748 defn->args.argnames[i++] = ' ';
5751 defn->args.argnames[i] = 0;
5753 } else {
5754 /* Simple expansion or empty definition. */
5756 if (bp < limit)
5758 if (is_hor_space[*bp]) {
5759 bp++;
5760 SKIP_WHITE_SPACE (bp);
5761 } else {
5762 switch (*bp) {
5763 case '!': case '"': case '#': case '%': case '&': case '\'':
5764 case ')': case '*': case '+': case ',': case '-': case '.':
5765 case '/': case ':': case ';': case '<': case '=': case '>':
5766 case '?': case '[': case '\\': case ']': case '^': case '{':
5767 case '|': case '}': case '~':
5768 warning ("missing white space after `#define %.*s'",
5769 sym_length, symname);
5770 break;
5772 default:
5773 pedwarn ("missing white space after `#define %.*s'",
5774 sym_length, symname);
5775 break;
5779 /* Now everything from bp before limit is the definition. */
5780 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5781 defn->args.argnames = (U_CHAR *) "";
5784 defn->line = line;
5785 defn->file = file;
5787 /* OP is null if this is a predefinition */
5788 defn->predefined = !op;
5789 mdef.defn = defn;
5790 mdef.symnam = symname;
5791 mdef.symlen = sym_length;
5793 return mdef;
5795 nope:
5796 mdef.defn = 0;
5797 return mdef;
5800 /* Process a #define directive.
5801 BUF points to the contents of the #define directive, as a contiguous string.
5802 LIMIT points to the first character past the end of the definition.
5803 KEYWORD is the keyword-table entry for #define. */
5805 static int
5806 do_define (buf, limit, op, keyword)
5807 U_CHAR *buf, *limit;
5808 FILE_BUF *op;
5809 struct directive *keyword;
5811 int hashcode;
5812 MACRODEF mdef;
5814 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5815 if (pcp_outfile && op)
5816 pass_thru_directive (buf, limit, op, keyword);
5818 mdef = create_definition (buf, limit, op);
5819 if (mdef.defn == 0)
5820 goto nope;
5822 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5825 HASHNODE *hp;
5826 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5827 int ok = 0;
5828 /* Redefining a precompiled key is ok. */
5829 if (hp->type == T_PCSTRING)
5830 ok = 1;
5831 /* Redefining a macro is ok if the definitions are the same. */
5832 else if (hp->type == T_MACRO)
5833 ok = ! compare_defs (mdef.defn, hp->value.defn);
5834 /* Redefining a constant is ok with -D. */
5835 else if (hp->type == T_CONST)
5836 ok = ! done_initializing;
5837 /* Print the warning if it's not ok. */
5838 if (!ok) {
5839 /* If we are passing through #define and #undef directives, do
5840 that for this re-definition now. */
5841 if (debug_output && op)
5842 pass_thru_directive (buf, limit, op, keyword);
5844 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5845 if (hp->type == T_MACRO)
5846 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5847 "this is the location of the previous definition");
5849 /* Replace the old definition. */
5850 hp->type = T_MACRO;
5851 hp->value.defn = mdef.defn;
5852 } else {
5853 /* If we are passing through #define and #undef directives, do
5854 that for this new definition now. */
5855 if (debug_output && op)
5856 pass_thru_directive (buf, limit, op, keyword);
5857 install (mdef.symnam, mdef.symlen, T_MACRO,
5858 (char *) mdef.defn, hashcode);
5862 return 0;
5864 nope:
5866 return 1;
5869 /* Check a purported macro name SYMNAME, and yield its length.
5870 USAGE is the kind of name this is intended for. */
5872 static int
5873 check_macro_name (symname, usage)
5874 U_CHAR *symname;
5875 char *usage;
5877 U_CHAR *p;
5878 int sym_length;
5880 for (p = symname; is_idchar[*p]; p++)
5882 sym_length = p - symname;
5883 if (sym_length == 0)
5884 error ("invalid %s name", usage);
5885 else if (!is_idstart[*symname]
5886 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5887 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5888 return sym_length;
5892 * return zero if two DEFINITIONs are isomorphic
5894 static int
5895 compare_defs (d1, d2)
5896 DEFINITION *d1, *d2;
5898 register struct reflist *a1, *a2;
5899 register U_CHAR *p1 = d1->expansion;
5900 register U_CHAR *p2 = d2->expansion;
5901 int first = 1;
5903 if (d1->nargs != d2->nargs)
5904 return 1;
5905 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5906 return 1;
5907 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5908 a1 = a1->next, a2 = a2->next) {
5909 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5910 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5911 || a1->argno != a2->argno
5912 || a1->stringify != a2->stringify
5913 || a1->raw_before != a2->raw_before
5914 || a1->raw_after != a2->raw_after)
5915 return 1;
5916 first = 0;
5917 p1 += a1->nchars;
5918 p2 += a2->nchars;
5920 if (a1 != a2)
5921 return 1;
5922 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5923 p2, d2->length - (p2 - d2->expansion), 1))
5924 return 1;
5925 return 0;
5928 /* Return 1 if two parts of two macro definitions are effectively different.
5929 One of the parts starts at BEG1 and has LEN1 chars;
5930 the other has LEN2 chars at BEG2.
5931 Any sequence of whitespace matches any other sequence of whitespace.
5932 FIRST means these parts are the first of a macro definition;
5933 so ignore leading whitespace entirely.
5934 LAST means these parts are the last of a macro definition;
5935 so ignore trailing whitespace entirely. */
5937 static int
5938 comp_def_part (first, beg1, len1, beg2, len2, last)
5939 int first;
5940 U_CHAR *beg1, *beg2;
5941 int len1, len2;
5942 int last;
5944 register U_CHAR *end1 = beg1 + len1;
5945 register U_CHAR *end2 = beg2 + len2;
5946 if (first) {
5947 while (beg1 != end1 && is_space[*beg1]) beg1++;
5948 while (beg2 != end2 && is_space[*beg2]) beg2++;
5950 if (last) {
5951 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5952 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5954 while (beg1 != end1 && beg2 != end2) {
5955 if (is_space[*beg1] && is_space[*beg2]) {
5956 while (beg1 != end1 && is_space[*beg1]) beg1++;
5957 while (beg2 != end2 && is_space[*beg2]) beg2++;
5958 } else if (*beg1 == *beg2) {
5959 beg1++; beg2++;
5960 } else break;
5962 return (beg1 != end1) || (beg2 != end2);
5965 /* Read a replacement list for a macro with parameters.
5966 Build the DEFINITION structure.
5967 Reads characters of text starting at BUF until END.
5968 ARGLIST specifies the formal parameters to look for
5969 in the text of the definition; NARGS is the number of args
5970 in that list, or -1 for a macro name that wants no argument list.
5971 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5972 and NAMELEN is its length in characters.
5974 Note that comments, backslash-newlines, and leading white space
5975 have already been deleted from the argument. */
5977 /* If there is no trailing whitespace, a Newline Space is added at the end
5978 to prevent concatenation that would be contrary to the standard. */
5980 static DEFINITION *
5981 collect_expansion (buf, end, nargs, arglist)
5982 U_CHAR *buf, *end;
5983 int nargs;
5984 struct arglist *arglist;
5986 DEFINITION *defn;
5987 register U_CHAR *p, *limit, *lastp, *exp_p;
5988 struct reflist *endpat = NULL;
5989 /* Pointer to first nonspace after last ## seen. */
5990 U_CHAR *concat = 0;
5991 /* Pointer to first nonspace after last single-# seen. */
5992 U_CHAR *stringify = 0;
5993 /* How those tokens were spelled. */
5994 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5995 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5996 int maxsize;
5997 int expected_delimiter = '\0';
5999 /* Scan thru the replacement list, ignoring comments and quoted
6000 strings, picking up on the macro calls. It does a linear search
6001 thru the arg list on every potential symbol. Profiling might say
6002 that something smarter should happen. */
6004 if (end < buf)
6005 abort ();
6007 /* Find the beginning of the trailing whitespace. */
6008 limit = end;
6009 p = buf;
6010 while (p < limit && is_space[limit[-1]]) limit--;
6012 /* Allocate space for the text in the macro definition.
6013 Each input char may or may not need 1 byte,
6014 so this is an upper bound.
6015 The extra 3 are for invented trailing newline-marker and final null. */
6016 maxsize = (sizeof (DEFINITION)
6017 + (limit - p) + 3);
6018 defn = (DEFINITION *) xcalloc (1, maxsize);
6020 defn->nargs = nargs;
6021 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6022 lastp = exp_p;
6024 if (p[0] == '#'
6025 ? p[1] == '#'
6026 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6027 error ("`##' at start of macro definition");
6028 p += p[0] == '#' ? 2 : 4;
6031 /* Process the main body of the definition. */
6032 while (p < limit) {
6033 int skipped_arg = 0;
6034 register U_CHAR c = *p++;
6036 *exp_p++ = c;
6038 if (!traditional) {
6039 switch (c) {
6040 case '\'':
6041 case '\"':
6042 if (expected_delimiter != '\0') {
6043 if (c == expected_delimiter)
6044 expected_delimiter = '\0';
6045 } else
6046 expected_delimiter = c;
6047 break;
6049 case '\\':
6050 if (p < limit && expected_delimiter) {
6051 /* In a string, backslash goes through
6052 and makes next char ordinary. */
6053 *exp_p++ = *p++;
6055 break;
6057 case '%':
6058 if (!expected_delimiter && *p == ':') {
6059 /* %: is not a digraph if preceded by an odd number of '<'s. */
6060 U_CHAR *p0 = p - 1;
6061 while (buf < p0 && p0[-1] == '<')
6062 p0--;
6063 if ((p - p0) & 1) {
6064 /* Treat %:%: as ## and %: as #. */
6065 if (p[1] == '%' && p[2] == ':') {
6066 p += 2;
6067 goto sharp_sharp_token;
6069 if (nargs >= 0) {
6070 p++;
6071 goto sharp_token;
6075 break;
6077 case '#':
6078 /* # is ordinary inside a string. */
6079 if (expected_delimiter)
6080 break;
6081 if (*p == '#') {
6082 sharp_sharp_token:
6083 /* ##: concatenate preceding and following tokens. */
6084 /* Take out the first #, discard preceding whitespace. */
6085 exp_p--;
6086 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6087 --exp_p;
6088 /* Skip the second #. */
6089 p++;
6090 concat_sharp_token_type = c;
6091 if (is_hor_space[*p]) {
6092 concat_sharp_token_type = c + 1;
6093 p++;
6094 SKIP_WHITE_SPACE (p);
6096 concat = p;
6097 if (p == limit)
6098 error ("`##' at end of macro definition");
6099 } else if (nargs >= 0) {
6100 /* Single #: stringify following argument ref.
6101 Don't leave the # in the expansion. */
6102 sharp_token:
6103 exp_p--;
6104 stringify_sharp_token_type = c;
6105 if (is_hor_space[*p]) {
6106 stringify_sharp_token_type = c + 1;
6107 p++;
6108 SKIP_WHITE_SPACE (p);
6110 if (! is_idstart[*p] || nargs == 0)
6111 error ("`#' operator is not followed by a macro argument name");
6112 else
6113 stringify = p;
6115 break;
6117 } else {
6118 /* In -traditional mode, recognize arguments inside strings and
6119 and character constants, and ignore special properties of #.
6120 Arguments inside strings are considered "stringified", but no
6121 extra quote marks are supplied. */
6122 switch (c) {
6123 case '\'':
6124 case '\"':
6125 if (expected_delimiter != '\0') {
6126 if (c == expected_delimiter)
6127 expected_delimiter = '\0';
6128 } else
6129 expected_delimiter = c;
6130 break;
6132 case '\\':
6133 /* Backslash quotes delimiters and itself, but not macro args. */
6134 if (expected_delimiter != 0 && p < limit
6135 && (*p == expected_delimiter || *p == '\\')) {
6136 *exp_p++ = *p++;
6137 continue;
6139 break;
6141 case '/':
6142 if (expected_delimiter != '\0') /* No comments inside strings. */
6143 break;
6144 if (*p == '*') {
6145 /* If we find a comment that wasn't removed by handle_directive,
6146 this must be -traditional. So replace the comment with
6147 nothing at all. */
6148 exp_p--;
6149 p += 1;
6150 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
6151 p++;
6152 #if 0
6153 /* Mark this as a concatenation-point, as if it had been ##. */
6154 concat = p;
6155 #endif
6157 break;
6161 /* Handle the start of a symbol. */
6162 if (is_idchar[c] && nargs > 0) {
6163 U_CHAR *id_beg = p - 1;
6164 int id_len;
6166 --exp_p;
6167 while (p != limit && is_idchar[*p]) p++;
6168 id_len = p - id_beg;
6170 if (is_idstart[c]) {
6171 register struct arglist *arg;
6173 for (arg = arglist; arg != NULL; arg = arg->next) {
6174 struct reflist *tpat;
6176 if (arg->name[0] == c
6177 && arg->length == id_len
6178 && bcmp (arg->name, id_beg, id_len) == 0) {
6179 enum sharp_token_type tpat_stringify;
6180 if (expected_delimiter) {
6181 if (warn_stringify) {
6182 if (traditional) {
6183 warning ("macro argument `%.*s' is stringified.",
6184 id_len, arg->name);
6185 } else {
6186 warning ("macro arg `%.*s' would be stringified with -traditional.",
6187 id_len, arg->name);
6190 /* If ANSI, don't actually substitute inside a string. */
6191 if (!traditional)
6192 break;
6193 tpat_stringify = SHARP_TOKEN;
6194 } else {
6195 tpat_stringify
6196 = (stringify == id_beg
6197 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6199 /* make a pat node for this arg and append it to the end of
6200 the pat list */
6201 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6202 tpat->next = NULL;
6203 tpat->raw_before
6204 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6205 tpat->raw_after = NO_SHARP_TOKEN;
6206 tpat->rest_args = arg->rest_args;
6207 tpat->stringify = tpat_stringify;
6209 if (endpat == NULL)
6210 defn->pattern = tpat;
6211 else
6212 endpat->next = tpat;
6213 endpat = tpat;
6215 tpat->argno = arg->argno;
6216 tpat->nchars = exp_p - lastp;
6218 register U_CHAR *p1 = p;
6219 SKIP_WHITE_SPACE (p1);
6220 if (p1[0]=='#'
6221 ? p1[1]=='#'
6222 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6223 tpat->raw_after = p1[0] + (p != p1);
6225 lastp = exp_p; /* place to start copying from next time */
6226 skipped_arg = 1;
6227 break;
6232 /* If this was not a macro arg, copy it into the expansion. */
6233 if (! skipped_arg) {
6234 register U_CHAR *lim1 = p;
6235 p = id_beg;
6236 while (p != lim1)
6237 *exp_p++ = *p++;
6238 if (stringify == id_beg)
6239 error ("`#' operator should be followed by a macro argument name");
6244 if (!traditional && expected_delimiter == 0) {
6245 /* If ANSI, put in a newline-space marker to prevent token pasting.
6246 But not if "inside a string" (which in ANSI mode happens only for
6247 -D option). */
6248 *exp_p++ = '\n';
6249 *exp_p++ = ' ';
6252 *exp_p = '\0';
6254 defn->length = exp_p - defn->expansion;
6256 /* Crash now if we overrun the allocated size. */
6257 if (defn->length + 1 > maxsize)
6258 abort ();
6260 #if 0
6261 /* This isn't worth the time it takes. */
6262 /* give back excess storage */
6263 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6264 #endif
6266 return defn;
6269 static int
6270 do_assert (buf, limit, op, keyword)
6271 U_CHAR *buf, *limit;
6272 FILE_BUF *op;
6273 struct directive *keyword;
6275 U_CHAR *bp; /* temp ptr into input buffer */
6276 U_CHAR *symname; /* remember where symbol name starts */
6277 int sym_length; /* and how long it is */
6278 struct arglist *tokens = NULL;
6280 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6281 pedwarn ("ANSI C does not allow `#assert'");
6283 bp = buf;
6285 while (is_hor_space[*bp])
6286 bp++;
6288 symname = bp; /* remember where it starts */
6289 sym_length = check_macro_name (bp, "assertion");
6290 bp += sym_length;
6291 /* #define doesn't do this, but we should. */
6292 SKIP_WHITE_SPACE (bp);
6294 /* Lossage will occur if identifiers or control tokens are broken
6295 across lines using backslash. This is not the right place to take
6296 care of that. */
6298 if (*bp != '(') {
6299 error ("missing token-sequence in `#assert'");
6300 return 1;
6304 int error_flag = 0;
6306 bp++; /* skip '(' */
6307 SKIP_WHITE_SPACE (bp);
6309 tokens = read_token_list (&bp, limit, &error_flag);
6310 if (error_flag)
6311 return 1;
6312 if (tokens == 0) {
6313 error ("empty token-sequence in `#assert'");
6314 return 1;
6317 ++bp; /* skip paren */
6318 SKIP_WHITE_SPACE (bp);
6321 /* If this name isn't already an assertion name, make it one.
6322 Error if it was already in use in some other way. */
6325 ASSERTION_HASHNODE *hp;
6326 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6327 struct tokenlist_list *value
6328 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6330 hp = assertion_lookup (symname, sym_length, hashcode);
6331 if (hp == NULL) {
6332 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6333 error ("`defined' redefined as assertion");
6334 hp = assertion_install (symname, sym_length, hashcode);
6337 /* Add the spec'd token-sequence to the list of such. */
6338 value->tokens = tokens;
6339 value->next = hp->value;
6340 hp->value = value;
6343 return 0;
6346 static int
6347 do_unassert (buf, limit, op, keyword)
6348 U_CHAR *buf, *limit;
6349 FILE_BUF *op;
6350 struct directive *keyword;
6352 U_CHAR *bp; /* temp ptr into input buffer */
6353 U_CHAR *symname; /* remember where symbol name starts */
6354 int sym_length; /* and how long it is */
6356 struct arglist *tokens = NULL;
6357 int tokens_specified = 0;
6359 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6360 pedwarn ("ANSI C does not allow `#unassert'");
6362 bp = buf;
6364 while (is_hor_space[*bp])
6365 bp++;
6367 symname = bp; /* remember where it starts */
6368 sym_length = check_macro_name (bp, "assertion");
6369 bp += sym_length;
6370 /* #define doesn't do this, but we should. */
6371 SKIP_WHITE_SPACE (bp);
6373 /* Lossage will occur if identifiers or control tokens are broken
6374 across lines using backslash. This is not the right place to take
6375 care of that. */
6377 if (*bp == '(') {
6378 int error_flag = 0;
6380 bp++; /* skip '(' */
6381 SKIP_WHITE_SPACE (bp);
6383 tokens = read_token_list (&bp, limit, &error_flag);
6384 if (error_flag)
6385 return 1;
6386 if (tokens == 0) {
6387 error ("empty token list in `#unassert'");
6388 return 1;
6391 tokens_specified = 1;
6393 ++bp; /* skip paren */
6394 SKIP_WHITE_SPACE (bp);
6398 ASSERTION_HASHNODE *hp;
6399 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6400 struct tokenlist_list *tail, *prev;
6402 hp = assertion_lookup (symname, sym_length, hashcode);
6403 if (hp == NULL)
6404 return 1;
6406 /* If no token list was specified, then eliminate this assertion
6407 entirely. */
6408 if (! tokens_specified) {
6409 struct tokenlist_list *next;
6410 for (tail = hp->value; tail; tail = next) {
6411 next = tail->next;
6412 free_token_list (tail->tokens);
6413 free (tail);
6415 delete_assertion (hp);
6416 } else {
6417 /* If a list of tokens was given, then delete any matching list. */
6419 tail = hp->value;
6420 prev = 0;
6421 while (tail) {
6422 struct tokenlist_list *next = tail->next;
6423 if (compare_token_lists (tail->tokens, tokens)) {
6424 if (prev)
6425 prev->next = next;
6426 else
6427 hp->value = tail->next;
6428 free_token_list (tail->tokens);
6429 free (tail);
6430 } else {
6431 prev = tail;
6433 tail = next;
6438 return 0;
6441 /* Test whether there is an assertion named NAME
6442 and optionally whether it has an asserted token list TOKENS.
6443 NAME is not null terminated; its length is SYM_LENGTH.
6444 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6447 check_assertion (name, sym_length, tokens_specified, tokens)
6448 U_CHAR *name;
6449 int sym_length;
6450 int tokens_specified;
6451 struct arglist *tokens;
6453 ASSERTION_HASHNODE *hp;
6454 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6456 if (pedantic && !instack[indepth].system_header_p)
6457 pedwarn ("ANSI C does not allow testing assertions");
6459 hp = assertion_lookup (name, sym_length, hashcode);
6460 if (hp == NULL)
6461 /* It is not an assertion; just return false. */
6462 return 0;
6464 /* If no token list was specified, then value is 1. */
6465 if (! tokens_specified)
6466 return 1;
6469 struct tokenlist_list *tail;
6471 tail = hp->value;
6473 /* If a list of tokens was given,
6474 then succeed if the assertion records a matching list. */
6476 while (tail) {
6477 if (compare_token_lists (tail->tokens, tokens))
6478 return 1;
6479 tail = tail->next;
6482 /* Fail if the assertion has no matching list. */
6483 return 0;
6487 /* Compare two lists of tokens for equality including order of tokens. */
6489 static int
6490 compare_token_lists (l1, l2)
6491 struct arglist *l1, *l2;
6493 while (l1 && l2) {
6494 if (l1->length != l2->length)
6495 return 0;
6496 if (bcmp (l1->name, l2->name, l1->length))
6497 return 0;
6498 l1 = l1->next;
6499 l2 = l2->next;
6502 /* Succeed if both lists end at the same time. */
6503 return l1 == l2;
6506 /* Read a space-separated list of tokens ending in a close parenthesis.
6507 Return a list of strings, in the order they were written.
6508 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6509 Parse the text starting at *BPP, and update *BPP.
6510 Don't parse beyond LIMIT. */
6512 static struct arglist *
6513 read_token_list (bpp, limit, error_flag)
6514 U_CHAR **bpp;
6515 U_CHAR *limit;
6516 int *error_flag;
6518 struct arglist *token_ptrs = 0;
6519 U_CHAR *bp = *bpp;
6520 int depth = 1;
6522 *error_flag = 0;
6524 /* Loop over the assertion value tokens. */
6525 while (depth > 0) {
6526 struct arglist *temp;
6527 int eofp = 0;
6528 U_CHAR *beg = bp;
6530 /* Find the end of the token. */
6531 if (*bp == '(') {
6532 bp++;
6533 depth++;
6534 } else if (*bp == ')') {
6535 depth--;
6536 if (depth == 0)
6537 break;
6538 bp++;
6539 } else if (*bp == '"' || *bp == '\'')
6540 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6541 else
6542 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6543 && *bp != '"' && *bp != '\'' && bp != limit)
6544 bp++;
6546 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6547 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6548 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6549 temp->name[bp - beg] = 0;
6550 temp->next = token_ptrs;
6551 token_ptrs = temp;
6552 temp->length = bp - beg;
6554 SKIP_WHITE_SPACE (bp);
6556 if (bp >= limit) {
6557 error ("unterminated token sequence in `#assert' or `#unassert'");
6558 *error_flag = -1;
6559 return 0;
6562 *bpp = bp;
6564 /* We accumulated the names in reverse order.
6565 Now reverse them to get the proper order. */
6567 register struct arglist *prev = 0, *this, *next;
6568 for (this = token_ptrs; this; this = next) {
6569 next = this->next;
6570 this->next = prev;
6571 prev = this;
6573 return prev;
6577 static void
6578 free_token_list (tokens)
6579 struct arglist *tokens;
6581 while (tokens) {
6582 struct arglist *next = tokens->next;
6583 free (tokens->name);
6584 free (tokens);
6585 tokens = next;
6590 * Install a name in the assertion hash table.
6592 * If LEN is >= 0, it is the length of the name.
6593 * Otherwise, compute the length by scanning the entire name.
6595 * If HASH is >= 0, it is the precomputed hash code.
6596 * Otherwise, compute the hash code.
6598 static ASSERTION_HASHNODE *
6599 assertion_install (name, len, hash)
6600 U_CHAR *name;
6601 int len;
6602 int hash;
6604 register ASSERTION_HASHNODE *hp;
6605 register int i, bucket;
6606 register U_CHAR *p, *q;
6608 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6609 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6610 bucket = hash;
6611 hp->bucket_hdr = &assertion_hashtab[bucket];
6612 hp->next = assertion_hashtab[bucket];
6613 assertion_hashtab[bucket] = hp;
6614 hp->prev = NULL;
6615 if (hp->next != NULL)
6616 hp->next->prev = hp;
6617 hp->length = len;
6618 hp->value = 0;
6619 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6620 p = hp->name;
6621 q = name;
6622 for (i = 0; i < len; i++)
6623 *p++ = *q++;
6624 hp->name[len] = 0;
6625 return hp;
6629 * find the most recent hash node for name name (ending with first
6630 * non-identifier char) installed by install
6632 * If LEN is >= 0, it is the length of the name.
6633 * Otherwise, compute the length by scanning the entire name.
6635 * If HASH is >= 0, it is the precomputed hash code.
6636 * Otherwise, compute the hash code.
6638 static ASSERTION_HASHNODE *
6639 assertion_lookup (name, len, hash)
6640 U_CHAR *name;
6641 int len;
6642 int hash;
6644 register ASSERTION_HASHNODE *bucket;
6646 bucket = assertion_hashtab[hash];
6647 while (bucket) {
6648 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6649 return bucket;
6650 bucket = bucket->next;
6652 return NULL;
6655 static void
6656 delete_assertion (hp)
6657 ASSERTION_HASHNODE *hp;
6660 if (hp->prev != NULL)
6661 hp->prev->next = hp->next;
6662 if (hp->next != NULL)
6663 hp->next->prev = hp->prev;
6665 /* make sure that the bucket chain header that
6666 the deleted guy was on points to the right thing afterwards. */
6667 if (hp == *hp->bucket_hdr)
6668 *hp->bucket_hdr = hp->next;
6670 free (hp);
6674 * interpret #line directive. Remembers previously seen fnames
6675 * in its very own hash table.
6677 #define FNAME_HASHSIZE 37
6679 static int
6680 do_line (buf, limit, op, keyword)
6681 U_CHAR *buf, *limit;
6682 FILE_BUF *op;
6683 struct directive *keyword;
6685 register U_CHAR *bp;
6686 FILE_BUF *ip = &instack[indepth];
6687 FILE_BUF tem;
6688 int new_lineno;
6689 enum file_change_code file_change = same_file;
6691 /* Expand any macros. */
6692 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6694 /* Point to macroexpanded line, which is null-terminated now. */
6695 bp = tem.buf;
6696 SKIP_WHITE_SPACE (bp);
6698 if (!isdigit (*bp)) {
6699 error ("invalid format `#line' directive");
6700 return 0;
6703 /* The Newline at the end of this line remains to be processed.
6704 To put the next line at the specified line number,
6705 we must store a line number now that is one less. */
6706 new_lineno = atoi ((char *) bp) - 1;
6708 /* NEW_LINENO is one less than the actual line number here. */
6709 if (pedantic && new_lineno < 0)
6710 pedwarn ("line number out of range in `#line' directive");
6712 /* skip over the line number. */
6713 while (isdigit (*bp))
6714 bp++;
6716 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6717 if (*bp && !is_space[*bp]) {
6718 error ("invalid format `#line' directive");
6719 return;
6721 #endif
6723 SKIP_WHITE_SPACE (bp);
6725 if (*bp == '\"') {
6726 static HASHNODE *fname_table[FNAME_HASHSIZE];
6727 HASHNODE *hp, **hash_bucket;
6728 U_CHAR *fname, *p;
6729 int fname_length;
6731 fname = ++bp;
6733 /* Turn the file name, which is a character string literal,
6734 into a null-terminated string. Do this in place. */
6735 p = bp;
6736 for (;;)
6737 switch ((*p++ = *bp++)) {
6738 case '\0':
6739 error ("invalid format `#line' directive");
6740 return 0;
6742 case '\\':
6744 char *bpc = (char *) bp;
6745 int c = parse_escape (&bpc);
6746 bp = (U_CHAR *) bpc;
6747 if (c < 0)
6748 p--;
6749 else
6750 p[-1] = c;
6752 break;
6754 case '\"':
6755 p[-1] = 0;
6756 goto fname_done;
6758 fname_done:
6759 fname_length = p - fname;
6761 SKIP_WHITE_SPACE (bp);
6762 if (*bp) {
6763 if (pedantic)
6764 pedwarn ("garbage at end of `#line' directive");
6765 if (*bp == '1')
6766 file_change = enter_file;
6767 else if (*bp == '2')
6768 file_change = leave_file;
6769 else if (*bp == '3')
6770 ip->system_header_p = 1;
6771 else if (*bp == '4')
6772 ip->system_header_p = 2;
6773 else {
6774 error ("invalid format `#line' directive");
6775 return 0;
6778 bp++;
6779 SKIP_WHITE_SPACE (bp);
6780 if (*bp == '3') {
6781 ip->system_header_p = 1;
6782 bp++;
6783 SKIP_WHITE_SPACE (bp);
6785 if (*bp == '4') {
6786 ip->system_header_p = 2;
6787 bp++;
6788 SKIP_WHITE_SPACE (bp);
6790 if (*bp) {
6791 error ("invalid format `#line' directive");
6792 return 0;
6796 hash_bucket =
6797 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6798 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6799 if (hp->length == fname_length &&
6800 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6801 ip->nominal_fname = hp->value.cpval;
6802 break;
6804 if (hp == 0) {
6805 /* Didn't find it; cons up a new one. */
6806 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6807 hp->next = *hash_bucket;
6808 *hash_bucket = hp;
6810 hp->length = fname_length;
6811 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6812 bcopy (fname, hp->value.cpval, fname_length);
6814 } else if (*bp) {
6815 error ("invalid format `#line' directive");
6816 return 0;
6819 ip->lineno = new_lineno;
6820 output_line_directive (ip, op, 0, file_change);
6821 check_expand (op, ip->length - (ip->bufp - ip->buf));
6822 return 0;
6826 * remove the definition of a symbol from the symbol table.
6827 * according to un*x /lib/cpp, it is not an error to undef
6828 * something that has no definitions, so it isn't one here either.
6831 static int
6832 do_undef (buf, limit, op, keyword)
6833 U_CHAR *buf, *limit;
6834 FILE_BUF *op;
6835 struct directive *keyword;
6837 int sym_length;
6838 HASHNODE *hp;
6839 U_CHAR *orig_buf = buf;
6841 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6842 if (pcp_outfile && op)
6843 pass_thru_directive (buf, limit, op, keyword);
6845 SKIP_WHITE_SPACE (buf);
6846 sym_length = check_macro_name (buf, "macro");
6848 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6849 /* If we are generating additional info for debugging (with -g) we
6850 need to pass through all effective #undef directives. */
6851 if (debug_output && op)
6852 pass_thru_directive (orig_buf, limit, op, keyword);
6853 if (hp->type != T_MACRO)
6854 warning ("undefining `%s'", hp->name);
6855 delete_macro (hp);
6858 if (pedantic) {
6859 buf += sym_length;
6860 SKIP_WHITE_SPACE (buf);
6861 if (buf != limit)
6862 pedwarn ("garbage after `#undef' directive");
6864 return 0;
6868 * Report an error detected by the program we are processing.
6869 * Use the text of the line in the error message.
6870 * (We use error because it prints the filename & line#.)
6873 static int
6874 do_error (buf, limit, op, keyword)
6875 U_CHAR *buf, *limit;
6876 FILE_BUF *op;
6877 struct directive *keyword;
6879 int length = limit - buf;
6880 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6881 bcopy ((char *) buf, (char *) copy, length);
6882 copy[length] = 0;
6883 SKIP_WHITE_SPACE (copy);
6884 error ("#error %s", copy);
6885 return 0;
6889 * Report a warning detected by the program we are processing.
6890 * Use the text of the line in the warning message, then continue.
6891 * (We use error because it prints the filename & line#.)
6894 static int
6895 do_warning (buf, limit, op, keyword)
6896 U_CHAR *buf, *limit;
6897 FILE_BUF *op;
6898 struct directive *keyword;
6900 int length = limit - buf;
6901 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6902 bcopy ((char *) buf, (char *) copy, length);
6903 copy[length] = 0;
6904 SKIP_WHITE_SPACE (copy);
6905 warning ("#warning %s", copy);
6906 return 0;
6909 /* Remember the name of the current file being read from so that we can
6910 avoid ever including it again. */
6912 static void
6913 do_once ()
6915 int i;
6916 FILE_BUF *ip = NULL;
6918 for (i = indepth; i >= 0; i--)
6919 if (instack[i].fname != NULL) {
6920 ip = &instack[i];
6921 break;
6924 if (ip != NULL) {
6925 struct file_name_list *new;
6927 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6928 new->next = dont_repeat_files;
6929 dont_repeat_files = new;
6930 new->fname = savestring (ip->fname);
6931 new->control_macro = 0;
6932 new->got_name_map = 0;
6933 new->c_system_include_path = 0;
6937 /* #ident has already been copied to the output file, so just ignore it. */
6939 static int
6940 do_ident (buf, limit, op, keyword)
6941 U_CHAR *buf, *limit;
6942 FILE_BUF *op;
6943 struct directive *keyword;
6945 FILE_BUF trybuf;
6946 int len;
6948 /* Allow #ident in system headers, since that's not user's fault. */
6949 if (pedantic && !instack[indepth].system_header_p)
6950 pedwarn ("ANSI C does not allow `#ident'");
6952 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6953 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6954 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6955 limit = buf + (trybuf.bufp - trybuf.buf);
6956 len = (limit - buf);
6957 free (trybuf.buf);
6959 /* Output directive name. */
6960 check_expand (op, 7);
6961 bcopy ("#ident ", (char *) op->bufp, 7);
6962 op->bufp += 7;
6964 /* Output the expanded argument line. */
6965 check_expand (op, len);
6966 bcopy ((char *) buf, (char *) op->bufp, len);
6967 op->bufp += len;
6969 return 0;
6972 /* #pragma and its argument line have already been copied to the output file.
6973 Just check for some recognized pragmas that need validation here. */
6975 static int
6976 do_pragma (buf, limit, op, keyword)
6977 U_CHAR *buf, *limit;
6978 FILE_BUF *op;
6979 struct directive *keyword;
6981 SKIP_WHITE_SPACE (buf);
6982 if (!strncmp ((char *) buf, "once", 4)) {
6983 /* Allow #pragma once in system headers, since that's not the user's
6984 fault. */
6985 if (!instack[indepth].system_header_p)
6986 warning ("`#pragma once' is obsolete");
6987 do_once ();
6990 if (!strncmp ((char *) buf, "implementation", 14)) {
6991 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6992 been included yet. */
6993 struct file_name_list *ptr;
6994 U_CHAR *p = buf + 14, *fname, *inc_fname;
6995 SKIP_WHITE_SPACE (p);
6996 if (*p == '\n' || *p != '\"')
6997 return 0;
6999 fname = p + 1;
7000 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
7001 *p = '\0';
7003 for (ptr = all_include_files; ptr; ptr = ptr->next) {
7004 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
7005 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
7006 if (inc_fname && !strcmp ((char *) inc_fname, (char *) fname))
7007 warning ("`#pragma implementation' for `%s' appears after file is included",
7008 fname);
7012 return 0;
7015 #if 0
7016 /* This was a fun hack, but #pragma seems to start to be useful.
7017 By failing to recognize it, we pass it through unchanged to cc1. */
7020 * the behavior of the #pragma directive is implementation defined.
7021 * this implementation defines it as follows.
7024 static int
7025 do_pragma ()
7027 close (0);
7028 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7029 goto nope;
7030 close (1);
7031 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7032 goto nope;
7033 execl ("/usr/games/hack", "#pragma", 0);
7034 execl ("/usr/games/rogue", "#pragma", 0);
7035 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7036 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7037 nope:
7038 fatal ("You are in a maze of twisty compiler features, all different");
7040 #endif
7042 #ifdef SCCS_DIRECTIVE
7044 /* Just ignore #sccs, on systems where we define it at all. */
7046 static int
7047 do_sccs (buf, limit, op, keyword)
7048 U_CHAR *buf, *limit;
7049 FILE_BUF *op;
7050 struct directive *keyword;
7052 if (pedantic)
7053 pedwarn ("ANSI C does not allow `#sccs'");
7054 return 0;
7057 #endif /* defined (SCCS_DIRECTIVE) */
7060 * handle #if directive by
7061 * 1) inserting special `defined' keyword into the hash table
7062 * that gets turned into 0 or 1 by special_symbol (thus,
7063 * if the luser has a symbol called `defined' already, it won't
7064 * work inside the #if directive)
7065 * 2) rescan the input into a temporary output buffer
7066 * 3) pass the output buffer to the yacc parser and collect a value
7067 * 4) clean up the mess left from steps 1 and 2.
7068 * 5) call conditional_skip to skip til the next #endif (etc.),
7069 * or not, depending on the value from step 3.
7072 static int
7073 do_if (buf, limit, op, keyword)
7074 U_CHAR *buf, *limit;
7075 FILE_BUF *op;
7076 struct directive *keyword;
7078 HOST_WIDE_INT value;
7079 FILE_BUF *ip = &instack[indepth];
7081 value = eval_if_expression (buf, limit - buf);
7082 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7083 return 0;
7087 * handle a #elif directive by not changing if_stack either.
7088 * see the comment above do_else.
7091 static int
7092 do_elif (buf, limit, op, keyword)
7093 U_CHAR *buf, *limit;
7094 FILE_BUF *op;
7095 struct directive *keyword;
7097 HOST_WIDE_INT value;
7098 FILE_BUF *ip = &instack[indepth];
7100 if (if_stack == instack[indepth].if_stack) {
7101 error ("`#elif' not within a conditional");
7102 return 0;
7103 } else {
7104 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7105 error ("`#elif' after `#else'");
7106 fprintf (stderr, " (matches line %d", if_stack->lineno);
7107 if (if_stack->fname != NULL && ip->fname != NULL &&
7108 strcmp (if_stack->fname, ip->nominal_fname) != 0)
7109 fprintf (stderr, ", file %s", if_stack->fname);
7110 fprintf (stderr, ")\n");
7112 if_stack->type = T_ELIF;
7115 if (if_stack->if_succeeded)
7116 skip_if_group (ip, 0, op);
7117 else {
7118 value = eval_if_expression (buf, limit - buf);
7119 if (value == 0)
7120 skip_if_group (ip, 0, op);
7121 else {
7122 ++if_stack->if_succeeded; /* continue processing input */
7123 output_line_directive (ip, op, 1, same_file);
7126 return 0;
7130 * evaluate a #if expression in BUF, of length LENGTH,
7131 * then parse the result as a C expression and return the value as an int.
7133 static HOST_WIDE_INT
7134 eval_if_expression (buf, length)
7135 U_CHAR *buf;
7136 int length;
7138 FILE_BUF temp_obuf;
7139 HASHNODE *save_defined;
7140 HOST_WIDE_INT value;
7142 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7143 NULL_PTR, -1);
7144 pcp_inside_if = 1;
7145 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7146 pcp_inside_if = 0;
7147 delete_macro (save_defined); /* clean up special symbol */
7149 value = parse_c_expression ((char *) temp_obuf.buf);
7151 free (temp_obuf.buf);
7153 return value;
7157 * routine to handle ifdef/ifndef. Try to look up the symbol,
7158 * then do or don't skip to the #endif/#else/#elif depending
7159 * on what directive is actually being processed.
7162 static int
7163 do_xifdef (buf, limit, op, keyword)
7164 U_CHAR *buf, *limit;
7165 FILE_BUF *op;
7166 struct directive *keyword;
7168 int skip;
7169 FILE_BUF *ip = &instack[indepth];
7170 U_CHAR *end;
7171 int start_of_file = 0;
7172 U_CHAR *control_macro = 0;
7174 /* Detect a #ifndef at start of file (not counting comments). */
7175 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7176 U_CHAR *p = ip->buf;
7177 while (p != directive_start) {
7178 U_CHAR c = *p++;
7179 if (is_space[c])
7181 /* Make no special provision for backslash-newline here; this is
7182 slower if backslash-newlines are present, but it's correct,
7183 and it's not worth it to tune for the rare backslash-newline. */
7184 else if (c == '/'
7185 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7186 /* Skip this comment. */
7187 int junk = 0;
7188 U_CHAR *save_bufp = ip->bufp;
7189 ip->bufp = p + 1;
7190 p = skip_to_end_of_comment (ip, &junk, 1);
7191 ip->bufp = save_bufp;
7192 } else {
7193 goto fail;
7196 /* If we get here, this conditional is the beginning of the file. */
7197 start_of_file = 1;
7198 fail: ;
7201 /* Discard leading and trailing whitespace. */
7202 SKIP_WHITE_SPACE (buf);
7203 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7205 /* Find the end of the identifier at the beginning. */
7206 for (end = buf; is_idchar[*end]; end++);
7208 if (end == buf) {
7209 skip = (keyword->type == T_IFDEF);
7210 if (! traditional)
7211 pedwarn (end == limit ? "`#%s' with no argument"
7212 : "`#%s' argument starts with punctuation",
7213 keyword->name);
7214 } else {
7215 HASHNODE *hp;
7217 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
7218 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7219 else if (end != limit && !traditional)
7220 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7222 hp = lookup (buf, end-buf, -1);
7224 if (pcp_outfile) {
7225 /* Output a precondition for this macro. */
7226 if (hp &&
7227 (hp->type == T_CONST
7228 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7229 fprintf (pcp_outfile, "#define %s\n", hp->name);
7230 else {
7231 U_CHAR *cp = buf;
7232 fprintf (pcp_outfile, "#undef ");
7233 while (is_idchar[*cp]) /* Ick! */
7234 fputc (*cp++, pcp_outfile);
7235 putc ('\n', pcp_outfile);
7239 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7240 if (start_of_file && !skip) {
7241 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7242 bcopy ((char *) buf, (char *) control_macro, end - buf);
7243 control_macro[end - buf] = 0;
7247 conditional_skip (ip, skip, T_IF, control_macro, op);
7248 return 0;
7251 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7252 If this is a #ifndef starting at the beginning of a file,
7253 CONTROL_MACRO is the macro name tested by the #ifndef.
7254 Otherwise, CONTROL_MACRO is 0. */
7256 static void
7257 conditional_skip (ip, skip, type, control_macro, op)
7258 FILE_BUF *ip;
7259 int skip;
7260 enum node_type type;
7261 U_CHAR *control_macro;
7262 FILE_BUF *op;
7264 IF_STACK_FRAME *temp;
7266 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7267 temp->fname = ip->nominal_fname;
7268 temp->lineno = ip->lineno;
7269 temp->next = if_stack;
7270 temp->control_macro = control_macro;
7271 if_stack = temp;
7273 if_stack->type = type;
7275 if (skip != 0) {
7276 skip_if_group (ip, 0, op);
7277 return;
7278 } else {
7279 ++if_stack->if_succeeded;
7280 output_line_directive (ip, &outbuf, 1, same_file);
7285 * skip to #endif, #else, or #elif. adjust line numbers, etc.
7286 * leaves input ptr at the sharp sign found.
7287 * If ANY is nonzero, return at next directive of any sort.
7289 static void
7290 skip_if_group (ip, any, op)
7291 FILE_BUF *ip;
7292 int any;
7293 FILE_BUF *op;
7295 register U_CHAR *bp = ip->bufp, *cp;
7296 register U_CHAR *endb = ip->buf + ip->length;
7297 struct directive *kt;
7298 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7299 U_CHAR *beg_of_line = bp;
7300 register int ident_length;
7301 U_CHAR *ident, *after_ident;
7302 /* Save info about where the group starts. */
7303 U_CHAR *beg_of_group = bp;
7304 int beg_lineno = ip->lineno;
7306 if (output_conditionals && op != 0) {
7307 char *ptr = "#failed\n";
7308 int len = strlen (ptr);
7310 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7312 *op->bufp++ = '\n';
7313 op->lineno++;
7315 check_expand (op, len);
7316 bcopy (ptr, (char *) op->bufp, len);
7317 op->bufp += len;
7318 op->lineno++;
7319 output_line_directive (ip, op, 1, 0);
7322 while (bp < endb) {
7323 switch (*bp++) {
7324 case '/': /* possible comment */
7325 if (*bp == '\\' && bp[1] == '\n')
7326 newline_fix (bp);
7327 if (*bp == '*'
7328 || (cplusplus_comments && *bp == '/')) {
7329 ip->bufp = ++bp;
7330 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7332 break;
7333 case '\"':
7334 case '\'':
7335 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7336 NULL_PTR, NULL_PTR);
7337 break;
7338 case '\\':
7339 /* Char after backslash loses its special meaning. */
7340 if (bp < endb) {
7341 if (*bp == '\n')
7342 ++ip->lineno; /* But do update the line-count. */
7343 bp++;
7345 break;
7346 case '\n':
7347 ++ip->lineno;
7348 beg_of_line = bp;
7349 break;
7350 case '%':
7351 if (beg_of_line == 0 || traditional)
7352 break;
7353 ip->bufp = bp - 1;
7354 while (bp[0] == '\\' && bp[1] == '\n')
7355 bp += 2;
7356 if (*bp == ':')
7357 goto sharp_token;
7358 break;
7359 case '#':
7360 /* # keyword: a # must be first nonblank char on the line */
7361 if (beg_of_line == 0)
7362 break;
7363 ip->bufp = bp - 1;
7364 sharp_token:
7365 /* Scan from start of line, skipping whitespace, comments
7366 and backslash-newlines, and see if we reach this #.
7367 If not, this # is not special. */
7368 bp = beg_of_line;
7369 /* If -traditional, require # to be at beginning of line. */
7370 if (!traditional) {
7371 while (1) {
7372 if (is_hor_space[*bp])
7373 bp++;
7374 else if (*bp == '\\' && bp[1] == '\n')
7375 bp += 2;
7376 else if (*bp == '/' && bp[1] == '*') {
7377 bp += 2;
7378 while (!(*bp == '*' && bp[1] == '/'))
7379 bp++;
7380 bp += 2;
7382 /* There is no point in trying to deal with C++ // comments here,
7383 because if there is one, then this # must be part of the
7384 comment and we would never reach here. */
7385 else break;
7388 if (bp != ip->bufp) {
7389 bp = ip->bufp + 1; /* Reset bp to after the #. */
7390 break;
7393 bp = ip->bufp + 1; /* Point after the '#' */
7394 if (ip->bufp[0] == '%') {
7395 /* Skip past the ':' again. */
7396 while (*bp == '\\') {
7397 ip->lineno++;
7398 bp += 2;
7400 bp++;
7403 /* Skip whitespace and \-newline. */
7404 while (1) {
7405 if (is_hor_space[*bp])
7406 bp++;
7407 else if (*bp == '\\' && bp[1] == '\n')
7408 bp += 2;
7409 else if (*bp == '/' && bp[1] == '*') {
7410 bp += 2;
7411 while (!(*bp == '*' && bp[1] == '/')) {
7412 if (*bp == '\n')
7413 ip->lineno++;
7414 bp++;
7416 bp += 2;
7417 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
7418 bp += 2;
7419 while (bp[-1] == '\\' || *bp != '\n') {
7420 if (*bp == '\n')
7421 ip->lineno++;
7422 bp++;
7425 else break;
7428 cp = bp;
7430 /* Now find end of directive name.
7431 If we encounter a backslash-newline, exchange it with any following
7432 symbol-constituents so that we end up with a contiguous name. */
7434 while (1) {
7435 if (is_idchar[*bp])
7436 bp++;
7437 else {
7438 if (*bp == '\\' && bp[1] == '\n')
7439 name_newline_fix (bp);
7440 if (is_idchar[*bp])
7441 bp++;
7442 else break;
7445 ident_length = bp - cp;
7446 ident = cp;
7447 after_ident = bp;
7449 /* A line of just `#' becomes blank. */
7451 if (ident_length == 0 && *after_ident == '\n') {
7452 continue;
7455 if (ident_length == 0 || !is_idstart[*ident]) {
7456 U_CHAR *p = ident;
7457 while (is_idchar[*p]) {
7458 if (*p < '0' || *p > '9')
7459 break;
7460 p++;
7462 /* Handle # followed by a line number. */
7463 if (p != ident && !is_idchar[*p]) {
7464 if (pedantic)
7465 pedwarn ("`#' followed by integer");
7466 continue;
7469 /* Avoid error for `###' and similar cases unless -pedantic. */
7470 if (p == ident) {
7471 while (*p == '#' || is_hor_space[*p]) p++;
7472 if (*p == '\n') {
7473 if (pedantic && !lang_asm)
7474 pedwarn ("invalid preprocessing directive");
7475 continue;
7479 if (!lang_asm && pedantic)
7480 pedwarn ("invalid preprocessing directive name");
7481 continue;
7484 for (kt = directive_table; kt->length >= 0; kt++) {
7485 IF_STACK_FRAME *temp;
7486 if (ident_length == kt->length
7487 && bcmp (cp, kt->name, kt->length) == 0) {
7488 /* If we are asked to return on next directive, do so now. */
7489 if (any)
7490 goto done;
7492 switch (kt->type) {
7493 case T_IF:
7494 case T_IFDEF:
7495 case T_IFNDEF:
7496 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7497 temp->next = if_stack;
7498 if_stack = temp;
7499 temp->lineno = ip->lineno;
7500 temp->fname = ip->nominal_fname;
7501 temp->type = kt->type;
7502 break;
7503 case T_ELSE:
7504 case T_ENDIF:
7505 if (pedantic && if_stack != save_if_stack)
7506 validate_else (bp);
7507 case T_ELIF:
7508 if (if_stack == instack[indepth].if_stack) {
7509 error ("`#%s' not within a conditional", kt->name);
7510 break;
7512 else if (if_stack == save_if_stack)
7513 goto done; /* found what we came for */
7515 if (kt->type != T_ENDIF) {
7516 if (if_stack->type == T_ELSE)
7517 error ("`#else' or `#elif' after `#else'");
7518 if_stack->type = kt->type;
7519 break;
7522 temp = if_stack;
7523 if_stack = if_stack->next;
7524 free (temp);
7525 break;
7527 default:
7528 break;
7530 break;
7533 /* Don't let erroneous code go by. */
7534 if (kt->length < 0 && !lang_asm && pedantic)
7535 pedwarn ("invalid preprocessing directive name");
7539 ip->bufp = bp;
7540 /* after this returns, rescan will exit because ip->bufp
7541 now points to the end of the buffer.
7542 rescan is responsible for the error message also. */
7544 done:
7545 if (output_conditionals && op != 0) {
7546 char *ptr = "#endfailed\n";
7547 int len = strlen (ptr);
7549 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7551 *op->bufp++ = '\n';
7552 op->lineno++;
7554 check_expand (op, beg_of_line - beg_of_group);
7555 bcopy ((char *) beg_of_group, (char *) op->bufp,
7556 beg_of_line - beg_of_group);
7557 op->bufp += beg_of_line - beg_of_group;
7558 op->lineno += ip->lineno - beg_lineno;
7559 check_expand (op, len);
7560 bcopy (ptr, (char *) op->bufp, len);
7561 op->bufp += len;
7562 op->lineno++;
7567 * handle a #else directive. Do this by just continuing processing
7568 * without changing if_stack ; this is so that the error message
7569 * for missing #endif's etc. will point to the original #if. It
7570 * is possible that something different would be better.
7573 static int
7574 do_else (buf, limit, op, keyword)
7575 U_CHAR *buf, *limit;
7576 FILE_BUF *op;
7577 struct directive *keyword;
7579 FILE_BUF *ip = &instack[indepth];
7581 if (pedantic) {
7582 SKIP_WHITE_SPACE (buf);
7583 if (buf != limit)
7584 pedwarn ("text following `#else' violates ANSI standard");
7587 if (if_stack == instack[indepth].if_stack) {
7588 error ("`#else' not within a conditional");
7589 return 0;
7590 } else {
7591 /* #ifndef can't have its special treatment for containing the whole file
7592 if it has a #else clause. */
7593 if_stack->control_macro = 0;
7595 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7596 error ("`#else' after `#else'");
7597 fprintf (stderr, " (matches line %d", if_stack->lineno);
7598 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7599 fprintf (stderr, ", file %s", if_stack->fname);
7600 fprintf (stderr, ")\n");
7602 if_stack->type = T_ELSE;
7605 if (if_stack->if_succeeded)
7606 skip_if_group (ip, 0, op);
7607 else {
7608 ++if_stack->if_succeeded; /* continue processing input */
7609 output_line_directive (ip, op, 1, same_file);
7611 return 0;
7615 * unstack after #endif directive
7618 static int
7619 do_endif (buf, limit, op, keyword)
7620 U_CHAR *buf, *limit;
7621 FILE_BUF *op;
7622 struct directive *keyword;
7624 if (pedantic) {
7625 SKIP_WHITE_SPACE (buf);
7626 if (buf != limit)
7627 pedwarn ("text following `#endif' violates ANSI standard");
7630 if (if_stack == instack[indepth].if_stack)
7631 error ("unbalanced `#endif'");
7632 else {
7633 IF_STACK_FRAME *temp = if_stack;
7634 if_stack = if_stack->next;
7635 if (temp->control_macro != 0) {
7636 /* This #endif matched a #ifndef at the start of the file.
7637 See if it is at the end of the file. */
7638 FILE_BUF *ip = &instack[indepth];
7639 U_CHAR *p = ip->bufp;
7640 U_CHAR *ep = ip->buf + ip->length;
7642 while (p != ep) {
7643 U_CHAR c = *p++;
7644 if (!is_space[c]) {
7645 if (c == '/'
7646 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7647 /* Skip this comment. */
7648 int junk = 0;
7649 U_CHAR *save_bufp = ip->bufp;
7650 ip->bufp = p + 1;
7651 p = skip_to_end_of_comment (ip, &junk, 1);
7652 ip->bufp = save_bufp;
7653 } else
7654 goto fail;
7657 /* If we get here, this #endif ends a #ifndef
7658 that contains all of the file (aside from whitespace).
7659 Arrange not to include the file again
7660 if the macro that was tested is defined.
7662 Do not do this for the top-level file in a -include or any
7663 file in a -imacros. */
7664 if (indepth != 0
7665 && ! (indepth == 1 && no_record_file)
7666 && ! (no_record_file && no_output))
7667 record_control_macro (ip->fname, temp->control_macro);
7668 fail: ;
7670 free (temp);
7671 output_line_directive (&instack[indepth], op, 1, same_file);
7673 return 0;
7676 /* When an #else or #endif is found while skipping failed conditional,
7677 if -pedantic was specified, this is called to warn about text after
7678 the directive name. P points to the first char after the directive name. */
7680 static void
7681 validate_else (p)
7682 register U_CHAR *p;
7684 /* Advance P over whitespace and comments. */
7685 while (1) {
7686 if (*p == '\\' && p[1] == '\n')
7687 p += 2;
7688 if (is_hor_space[*p])
7689 p++;
7690 else if (*p == '/') {
7691 if (p[1] == '\\' && p[2] == '\n')
7692 newline_fix (p + 1);
7693 if (p[1] == '*') {
7694 p += 2;
7695 /* Don't bother warning about unterminated comments
7696 since that will happen later. Just be sure to exit. */
7697 while (*p) {
7698 if (p[1] == '\\' && p[2] == '\n')
7699 newline_fix (p + 1);
7700 if (*p == '*' && p[1] == '/') {
7701 p += 2;
7702 break;
7704 p++;
7707 else if (cplusplus_comments && p[1] == '/') {
7708 p += 2;
7709 while (*p && (*p != '\n' || p[-1] == '\\'))
7710 p++;
7712 } else break;
7714 if (*p && *p != '\n')
7715 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7718 /* Skip a comment, assuming the input ptr immediately follows the
7719 initial slash-star. Bump *LINE_COUNTER for each newline.
7720 (The canonical line counter is &ip->lineno.)
7721 Don't use this routine (or the next one) if bumping the line
7722 counter is not sufficient to deal with newlines in the string.
7724 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7725 This feature is useful when processing a comment that is going to be
7726 processed or was processed at another point in the preprocessor,
7727 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7729 static U_CHAR *
7730 skip_to_end_of_comment (ip, line_counter, nowarn)
7731 register FILE_BUF *ip;
7732 int *line_counter; /* place to remember newlines, or NULL */
7733 int nowarn;
7735 register U_CHAR *limit = ip->buf + ip->length;
7736 register U_CHAR *bp = ip->bufp;
7737 FILE_BUF *op = &outbuf; /* JF */
7738 int output = put_out_comments && !line_counter;
7739 int start_line = line_counter ? *line_counter : 0;
7741 /* JF this line_counter stuff is a crock to make sure the
7742 comment is only put out once, no matter how many times
7743 the comment is skipped. It almost works */
7744 if (output) {
7745 *op->bufp++ = '/';
7746 *op->bufp++ = '*';
7748 if (cplusplus_comments && bp[-1] == '/') {
7749 if (output) {
7750 while (bp < limit) {
7751 *op->bufp++ = *bp;
7752 if (*bp == '\n' && bp[-1] != '\\')
7753 break;
7754 if (*bp == '\n') {
7755 ++*line_counter;
7756 ++op->lineno;
7758 bp++;
7760 op->bufp[-1] = '*';
7761 *op->bufp++ = '/';
7762 *op->bufp++ = '\n';
7763 } else {
7764 while (bp < limit) {
7765 if (bp[-1] != '\\' && *bp == '\n') {
7766 break;
7767 } else {
7768 if (*bp == '\n' && line_counter)
7769 ++*line_counter;
7770 bp++;
7774 ip->bufp = bp;
7775 return bp;
7777 while (bp < limit) {
7778 if (output)
7779 *op->bufp++ = *bp;
7780 switch (*bp++) {
7781 case '/':
7782 if (warn_comments && !nowarn && bp < limit && *bp == '*')
7783 warning ("`/*' within comment");
7784 break;
7785 case '\n':
7786 /* If this is the end of the file, we have an unterminated comment.
7787 Don't swallow the newline. We are guaranteed that there will be a
7788 trailing newline and various pieces assume it's there. */
7789 if (bp == limit)
7791 --bp;
7792 --limit;
7793 break;
7795 if (line_counter != NULL)
7796 ++*line_counter;
7797 if (output)
7798 ++op->lineno;
7799 break;
7800 case '*':
7801 if (*bp == '\\' && bp[1] == '\n')
7802 newline_fix (bp);
7803 if (*bp == '/') {
7804 if (output)
7805 *op->bufp++ = '/';
7806 ip->bufp = ++bp;
7807 return bp;
7809 break;
7813 if (!nowarn)
7814 error_with_line (line_for_error (start_line), "unterminated comment");
7815 ip->bufp = bp;
7816 return bp;
7820 * Skip over a quoted string. BP points to the opening quote.
7821 * Returns a pointer after the closing quote. Don't go past LIMIT.
7822 * START_LINE is the line number of the starting point (but it need
7823 * not be valid if the starting point is inside a macro expansion).
7825 * The input stack state is not changed.
7827 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7828 * for each newline passed.
7830 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7831 * if we pass a backslash-newline.
7833 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7835 static U_CHAR *
7836 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7837 register U_CHAR *bp;
7838 register U_CHAR *limit;
7839 int start_line;
7840 int *count_newlines;
7841 int *backslash_newlines_p;
7842 int *eofp;
7844 register U_CHAR c, match;
7846 match = *bp++;
7847 while (1) {
7848 if (bp >= limit) {
7849 error_with_line (line_for_error (start_line),
7850 "unterminated string or character constant");
7851 error_with_line (multiline_string_line,
7852 "possible real start of unterminated constant");
7853 multiline_string_line = 0;
7854 if (eofp)
7855 *eofp = 1;
7856 break;
7858 c = *bp++;
7859 if (c == '\\') {
7860 while (*bp == '\\' && bp[1] == '\n') {
7861 if (backslash_newlines_p)
7862 *backslash_newlines_p = 1;
7863 if (count_newlines)
7864 ++*count_newlines;
7865 bp += 2;
7867 if (*bp == '\n' && count_newlines) {
7868 if (backslash_newlines_p)
7869 *backslash_newlines_p = 1;
7870 ++*count_newlines;
7872 bp++;
7873 } else if (c == '\n') {
7874 if (traditional) {
7875 /* Unterminated strings and character constants are 'valid'. */
7876 bp--; /* Don't consume the newline. */
7877 if (eofp)
7878 *eofp = 1;
7879 break;
7881 if (pedantic || match == '\'') {
7882 error_with_line (line_for_error (start_line),
7883 "unterminated string or character constant");
7884 bp--;
7885 if (eofp)
7886 *eofp = 1;
7887 break;
7889 /* If not traditional, then allow newlines inside strings. */
7890 if (count_newlines)
7891 ++*count_newlines;
7892 if (multiline_string_line == 0)
7893 multiline_string_line = start_line;
7894 } else if (c == match)
7895 break;
7897 return bp;
7900 /* Place into DST a quoted string representing the string SRC.
7901 Return the address of DST's terminating null. */
7902 static char *
7903 quote_string (dst, src)
7904 char *dst, *src;
7906 U_CHAR c;
7908 *dst++ = '\"';
7909 for (;;)
7910 switch ((c = *src++))
7912 default:
7913 if (isprint (c))
7914 *dst++ = c;
7915 else
7917 sprintf (dst, "\\%03o", c);
7918 dst += 4;
7920 break;
7922 case '\"':
7923 case '\\':
7924 *dst++ = '\\';
7925 *dst++ = c;
7926 break;
7928 case '\0':
7929 *dst++ = '\"';
7930 *dst = '\0';
7931 return dst;
7935 /* Skip across a group of balanced parens, starting from IP->bufp.
7936 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7938 This does not handle newlines, because it's used for the arg of #if,
7939 where there aren't any newlines. Also, backslash-newline can't appear. */
7941 static U_CHAR *
7942 skip_paren_group (ip)
7943 register FILE_BUF *ip;
7945 U_CHAR *limit = ip->buf + ip->length;
7946 U_CHAR *p = ip->bufp;
7947 int depth = 0;
7948 int lines_dummy = 0;
7950 while (p != limit) {
7951 int c = *p++;
7952 switch (c) {
7953 case '(':
7954 depth++;
7955 break;
7957 case ')':
7958 depth--;
7959 if (depth == 0)
7960 return ip->bufp = p;
7961 break;
7963 case '/':
7964 if (*p == '*') {
7965 ip->bufp = p;
7966 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7967 p = ip->bufp;
7970 case '"':
7971 case '\'':
7973 int eofp = 0;
7974 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7975 if (eofp)
7976 return ip->bufp = p;
7978 break;
7982 ip->bufp = p;
7983 return p;
7987 * write out a #line directive, for instance, after an #include file.
7988 * If CONDITIONAL is nonzero, we can omit the #line if it would
7989 * appear to be a no-op, and we can output a few newlines instead
7990 * if we want to increase the line number by a small amount.
7991 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7994 static void
7995 output_line_directive (ip, op, conditional, file_change)
7996 FILE_BUF *ip, *op;
7997 int conditional;
7998 enum file_change_code file_change;
8000 int len;
8001 char *line_directive_buf, *line_end;
8003 if (no_line_directives
8004 || ip->fname == NULL
8005 || no_output) {
8006 op->lineno = ip->lineno;
8007 return;
8010 if (conditional) {
8011 if (ip->lineno == op->lineno)
8012 return;
8014 /* If the inherited line number is a little too small,
8015 output some newlines instead of a #line directive. */
8016 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8017 check_expand (op, 10);
8018 while (ip->lineno > op->lineno) {
8019 *op->bufp++ = '\n';
8020 op->lineno++;
8022 return;
8026 /* Don't output a line number of 0 if we can help it. */
8027 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
8028 && *ip->bufp == '\n') {
8029 ip->lineno++;
8030 ip->bufp++;
8033 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
8034 sprintf (line_directive_buf, "# %d ", ip->lineno);
8035 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8036 ip->nominal_fname);
8037 if (file_change != same_file) {
8038 *line_end++ = ' ';
8039 *line_end++ = file_change == enter_file ? '1' : '2';
8041 /* Tell cc1 if following text comes from a system header file. */
8042 if (ip->system_header_p) {
8043 *line_end++ = ' ';
8044 *line_end++ = '3';
8046 #ifndef NO_IMPLICIT_EXTERN_C
8047 /* Tell cc1plus if following text should be treated as C. */
8048 if (ip->system_header_p == 2 && cplusplus) {
8049 *line_end++ = ' ';
8050 *line_end++ = '4';
8052 #endif
8053 *line_end++ = '\n';
8054 len = line_end - line_directive_buf;
8055 check_expand (op, len + 1);
8056 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8057 *op->bufp++ = '\n';
8058 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8059 op->bufp += len;
8060 op->lineno = ip->lineno;
8063 /* This structure represents one parsed argument in a macro call.
8064 `raw' points to the argument text as written (`raw_length' is its length).
8065 `expanded' points to the argument's macro-expansion
8066 (its length is `expand_length').
8067 `stringified_length' is the length the argument would have
8068 if stringified.
8069 `use_count' is the number of times this macro arg is substituted
8070 into the macro. If the actual use count exceeds 10,
8071 the value stored is 10.
8072 `free1' and `free2', if nonzero, point to blocks to be freed
8073 when the macro argument data is no longer needed. */
8075 struct argdata {
8076 U_CHAR *raw, *expanded;
8077 int raw_length, expand_length;
8078 int stringified_length;
8079 U_CHAR *free1, *free2;
8080 char newlines;
8081 char use_count;
8084 /* Expand a macro call.
8085 HP points to the symbol that is the macro being called.
8086 Put the result of expansion onto the input stack
8087 so that subsequent input by our caller will use it.
8089 If macro wants arguments, caller has already verified that
8090 an argument list follows; arguments come from the input stack. */
8092 static void
8093 macroexpand (hp, op)
8094 HASHNODE *hp;
8095 FILE_BUF *op;
8097 int nargs;
8098 DEFINITION *defn = hp->value.defn;
8099 register U_CHAR *xbuf;
8100 int xbuf_len;
8101 int start_line = instack[indepth].lineno;
8102 int rest_args, rest_zero;
8104 CHECK_DEPTH (return;);
8106 /* it might not actually be a macro. */
8107 if (hp->type != T_MACRO) {
8108 special_symbol (hp, op);
8109 return;
8112 /* This macro is being used inside a #if, which means it must be */
8113 /* recorded as a precondition. */
8114 if (pcp_inside_if && pcp_outfile && defn->predefined)
8115 dump_single_macro (hp, pcp_outfile);
8117 nargs = defn->nargs;
8119 if (nargs >= 0) {
8120 register int i;
8121 struct argdata *args;
8122 char *parse_error = 0;
8124 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8126 for (i = 0; i < nargs; i++) {
8127 args[i].raw = (U_CHAR *) "";
8128 args[i].expanded = 0;
8129 args[i].raw_length = args[i].expand_length
8130 = args[i].stringified_length = 0;
8131 args[i].free1 = args[i].free2 = 0;
8132 args[i].use_count = 0;
8135 /* Parse all the macro args that are supplied. I counts them.
8136 The first NARGS args are stored in ARGS.
8137 The rest are discarded.
8138 If rest_args is set then we assume macarg absorbed the rest of the args.
8140 i = 0;
8141 rest_args = 0;
8142 do {
8143 /* Discard the open-parenthesis or comma before the next arg. */
8144 ++instack[indepth].bufp;
8145 if (rest_args)
8146 continue;
8147 if (i < nargs || (nargs == 0 && i == 0)) {
8148 /* if we are working on last arg which absorbs rest of args... */
8149 if (i == nargs - 1 && defn->rest_args)
8150 rest_args = 1;
8151 parse_error = macarg (&args[i], rest_args);
8153 else
8154 parse_error = macarg (NULL_PTR, 0);
8155 if (parse_error) {
8156 error_with_line (line_for_error (start_line), parse_error);
8157 break;
8159 i++;
8160 } while (*instack[indepth].bufp != ')');
8162 /* If we got one arg but it was just whitespace, call that 0 args. */
8163 if (i == 1) {
8164 register U_CHAR *bp = args[0].raw;
8165 register U_CHAR *lim = bp + args[0].raw_length;
8166 /* cpp.texi says for foo ( ) we provide one argument.
8167 However, if foo wants just 0 arguments, treat this as 0. */
8168 if (nargs == 0)
8169 while (bp != lim && is_space[*bp]) bp++;
8170 if (bp == lim)
8171 i = 0;
8174 /* Don't output an error message if we have already output one for
8175 a parse error above. */
8176 rest_zero = 0;
8177 if (nargs == 0 && i > 0) {
8178 if (! parse_error)
8179 error ("arguments given to macro `%s'", hp->name);
8180 } else if (i < nargs) {
8181 /* traditional C allows foo() if foo wants one argument. */
8182 if (nargs == 1 && i == 0 && traditional)
8184 /* the rest args token is allowed to absorb 0 tokens */
8185 else if (i == nargs - 1 && defn->rest_args)
8186 rest_zero = 1;
8187 else if (parse_error)
8189 else if (i == 0)
8190 error ("macro `%s' used without args", hp->name);
8191 else if (i == 1)
8192 error ("macro `%s' used with just one arg", hp->name);
8193 else
8194 error ("macro `%s' used with only %d args", hp->name, i);
8195 } else if (i > nargs) {
8196 if (! parse_error)
8197 error ("macro `%s' used with too many (%d) args", hp->name, i);
8200 /* Swallow the closeparen. */
8201 ++instack[indepth].bufp;
8203 /* If macro wants zero args, we parsed the arglist for checking only.
8204 Read directly from the macro definition. */
8205 if (nargs == 0) {
8206 xbuf = defn->expansion;
8207 xbuf_len = defn->length;
8208 } else {
8209 register U_CHAR *exp = defn->expansion;
8210 register int offset; /* offset in expansion,
8211 copied a piece at a time */
8212 register int totlen; /* total amount of exp buffer filled so far */
8214 register struct reflist *ap, *last_ap;
8216 /* Macro really takes args. Compute the expansion of this call. */
8218 /* Compute length in characters of the macro's expansion.
8219 Also count number of times each arg is used. */
8220 xbuf_len = defn->length;
8221 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8222 if (ap->stringify)
8223 xbuf_len += args[ap->argno].stringified_length;
8224 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8225 /* Add 4 for two newline-space markers to prevent
8226 token concatenation. */
8227 xbuf_len += args[ap->argno].raw_length + 4;
8228 else {
8229 /* We have an ordinary (expanded) occurrence of the arg.
8230 So compute its expansion, if we have not already. */
8231 if (args[ap->argno].expanded == 0) {
8232 FILE_BUF obuf;
8233 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8234 args[ap->argno].raw + args[ap->argno].raw_length,
8235 1, 0);
8237 args[ap->argno].expanded = obuf.buf;
8238 args[ap->argno].expand_length = obuf.length;
8239 args[ap->argno].free2 = obuf.buf;
8242 /* Add 4 for two newline-space markers to prevent
8243 token concatenation. */
8244 xbuf_len += args[ap->argno].expand_length + 4;
8246 if (args[ap->argno].use_count < 10)
8247 args[ap->argno].use_count++;
8250 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8252 /* Generate in XBUF the complete expansion
8253 with arguments substituted in.
8254 TOTLEN is the total size generated so far.
8255 OFFSET is the index in the definition
8256 of where we are copying from. */
8257 offset = totlen = 0;
8258 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8259 last_ap = ap, ap = ap->next) {
8260 register struct argdata *arg = &args[ap->argno];
8261 int count_before = totlen;
8263 /* Add chars to XBUF. */
8264 for (i = 0; i < ap->nchars; i++, offset++)
8265 xbuf[totlen++] = exp[offset];
8267 /* If followed by an empty rest arg with concatenation,
8268 delete the last run of nonwhite chars. */
8269 if (rest_zero && totlen > count_before
8270 && ((ap->rest_args && ap->raw_before != 0)
8271 || (last_ap != NULL && last_ap->rest_args
8272 && last_ap->raw_after != 0))) {
8273 /* Delete final whitespace. */
8274 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8275 totlen--;
8278 /* Delete the nonwhites before them. */
8279 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8280 totlen--;
8284 if (ap->stringify != 0) {
8285 int arglen = arg->raw_length;
8286 int escaped = 0;
8287 int in_string = 0;
8288 int c;
8289 i = 0;
8290 while (i < arglen
8291 && (c = arg->raw[i], is_space[c]))
8292 i++;
8293 while (i < arglen
8294 && (c = arg->raw[arglen - 1], is_space[c]))
8295 arglen--;
8296 if (!traditional)
8297 xbuf[totlen++] = '\"'; /* insert beginning quote */
8298 for (; i < arglen; i++) {
8299 c = arg->raw[i];
8301 /* Special markers Newline Space
8302 generate nothing for a stringified argument. */
8303 if (c == '\n' && arg->raw[i+1] != '\n') {
8304 i++;
8305 continue;
8308 /* Internal sequences of whitespace are replaced by one space
8309 except within an string or char token. */
8310 if (! in_string
8311 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8312 while (1) {
8313 /* Note that Newline Space does occur within whitespace
8314 sequences; consider it part of the sequence. */
8315 if (c == '\n' && is_space[arg->raw[i+1]])
8316 i += 2;
8317 else if (c != '\n' && is_space[c])
8318 i++;
8319 else break;
8320 c = arg->raw[i];
8322 i--;
8323 c = ' ';
8326 if (escaped)
8327 escaped = 0;
8328 else {
8329 if (c == '\\')
8330 escaped = 1;
8331 if (in_string) {
8332 if (c == in_string)
8333 in_string = 0;
8334 } else if (c == '\"' || c == '\'')
8335 in_string = c;
8338 /* Escape these chars */
8339 if (c == '\"' || (in_string && c == '\\'))
8340 xbuf[totlen++] = '\\';
8341 if (isprint (c))
8342 xbuf[totlen++] = c;
8343 else {
8344 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8345 totlen += 4;
8348 if (!traditional)
8349 xbuf[totlen++] = '\"'; /* insert ending quote */
8350 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8351 U_CHAR *p1 = arg->raw;
8352 U_CHAR *l1 = p1 + arg->raw_length;
8353 if (ap->raw_before != 0) {
8354 while (p1 != l1 && is_space[*p1]) p1++;
8355 while (p1 != l1 && is_idchar[*p1])
8356 xbuf[totlen++] = *p1++;
8357 /* Delete any no-reexpansion marker that follows
8358 an identifier at the beginning of the argument
8359 if the argument is concatenated with what precedes it. */
8360 if (p1[0] == '\n' && p1[1] == '-')
8361 p1 += 2;
8362 } else if (!traditional) {
8363 /* Ordinary expanded use of the argument.
8364 Put in newline-space markers to prevent token pasting. */
8365 xbuf[totlen++] = '\n';
8366 xbuf[totlen++] = ' ';
8368 if (ap->raw_after != 0) {
8369 /* Arg is concatenated after: delete trailing whitespace,
8370 whitespace markers, and no-reexpansion markers. */
8371 while (p1 != l1) {
8372 if (is_space[l1[-1]]) l1--;
8373 else if (l1[-1] == '-') {
8374 U_CHAR *p2 = l1 - 1;
8375 /* If a `-' is preceded by an odd number of newlines then it
8376 and the last newline are a no-reexpansion marker. */
8377 while (p2 != p1 && p2[-1] == '\n') p2--;
8378 if ((l1 - 1 - p2) & 1) {
8379 l1 -= 2;
8381 else break;
8383 else break;
8387 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8388 totlen += l1 - p1;
8389 if (!traditional && ap->raw_after == 0) {
8390 /* Ordinary expanded use of the argument.
8391 Put in newline-space markers to prevent token pasting. */
8392 xbuf[totlen++] = '\n';
8393 xbuf[totlen++] = ' ';
8395 } else {
8396 /* Ordinary expanded use of the argument.
8397 Put in newline-space markers to prevent token pasting. */
8398 if (!traditional) {
8399 xbuf[totlen++] = '\n';
8400 xbuf[totlen++] = ' ';
8402 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8403 arg->expand_length);
8404 totlen += arg->expand_length;
8405 if (!traditional) {
8406 xbuf[totlen++] = '\n';
8407 xbuf[totlen++] = ' ';
8409 /* If a macro argument with newlines is used multiple times,
8410 then only expand the newlines once. This avoids creating output
8411 lines which don't correspond to any input line, which confuses
8412 gdb and gcov. */
8413 if (arg->use_count > 1 && arg->newlines > 0) {
8414 /* Don't bother doing change_newlines for subsequent
8415 uses of arg. */
8416 arg->use_count = 1;
8417 arg->expand_length
8418 = change_newlines (arg->expanded, arg->expand_length);
8422 if (totlen > xbuf_len)
8423 abort ();
8426 /* if there is anything left of the definition
8427 after handling the arg list, copy that in too. */
8429 for (i = offset; i < defn->length; i++) {
8430 /* if we've reached the end of the macro */
8431 if (exp[i] == ')')
8432 rest_zero = 0;
8433 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8434 && last_ap->raw_after != 0))
8435 xbuf[totlen++] = exp[i];
8438 xbuf[totlen] = 0;
8439 xbuf_len = totlen;
8441 for (i = 0; i < nargs; i++) {
8442 if (args[i].free1 != 0)
8443 free (args[i].free1);
8444 if (args[i].free2 != 0)
8445 free (args[i].free2);
8448 } else {
8449 xbuf = defn->expansion;
8450 xbuf_len = defn->length;
8453 /* Now put the expansion on the input stack
8454 so our caller will commence reading from it. */
8456 register FILE_BUF *ip2;
8458 ip2 = &instack[++indepth];
8460 ip2->fname = 0;
8461 ip2->nominal_fname = 0;
8462 /* This may not be exactly correct, but will give much better error
8463 messages for nested macro calls than using a line number of zero. */
8464 ip2->lineno = start_line;
8465 ip2->buf = xbuf;
8466 ip2->length = xbuf_len;
8467 ip2->bufp = xbuf;
8468 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8469 ip2->macro = hp;
8470 ip2->if_stack = if_stack;
8471 ip2->system_header_p = 0;
8473 /* Recursive macro use sometimes works traditionally.
8474 #define foo(x,y) bar (x (y,0), y)
8475 foo (foo, baz) */
8477 if (!traditional)
8478 hp->type = T_DISABLED;
8483 * Parse a macro argument and store the info on it into *ARGPTR.
8484 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8485 * Return nonzero to indicate a syntax error.
8488 static char *
8489 macarg (argptr, rest_args)
8490 register struct argdata *argptr;
8491 int rest_args;
8493 FILE_BUF *ip = &instack[indepth];
8494 int paren = 0;
8495 int newlines = 0;
8496 int comments = 0;
8497 char *result = 0;
8499 /* Try to parse as much of the argument as exists at this
8500 input stack level. */
8501 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8502 &paren, &newlines, &comments, rest_args);
8504 /* If we find the end of the argument at this level,
8505 set up *ARGPTR to point at it in the input stack. */
8506 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8507 && bp != ip->buf + ip->length) {
8508 if (argptr != 0) {
8509 argptr->raw = ip->bufp;
8510 argptr->raw_length = bp - ip->bufp;
8511 argptr->newlines = newlines;
8513 ip->bufp = bp;
8514 } else {
8515 /* This input stack level ends before the macro argument does.
8516 We must pop levels and keep parsing.
8517 Therefore, we must allocate a temporary buffer and copy
8518 the macro argument into it. */
8519 int bufsize = bp - ip->bufp;
8520 int extra = newlines;
8521 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8522 int final_start = 0;
8524 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8525 ip->bufp = bp;
8526 ip->lineno += newlines;
8528 while (bp == ip->buf + ip->length) {
8529 if (instack[indepth].macro == 0) {
8530 result = "unterminated macro call";
8531 break;
8533 ip->macro->type = T_MACRO;
8534 if (ip->free_ptr)
8535 free (ip->free_ptr);
8536 ip = &instack[--indepth];
8537 newlines = 0;
8538 comments = 0;
8539 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8540 &newlines, &comments, rest_args);
8541 final_start = bufsize;
8542 bufsize += bp - ip->bufp;
8543 extra += newlines;
8544 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8545 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8546 bp - ip->bufp);
8547 ip->bufp = bp;
8548 ip->lineno += newlines;
8551 /* Now, if arg is actually wanted, record its raw form,
8552 discarding comments and duplicating newlines in whatever
8553 part of it did not come from a macro expansion.
8554 EXTRA space has been preallocated for duplicating the newlines.
8555 FINAL_START is the index of the start of that part. */
8556 if (argptr != 0) {
8557 argptr->raw = buffer;
8558 argptr->raw_length = bufsize;
8559 argptr->free1 = buffer;
8560 argptr->newlines = newlines;
8561 if ((newlines || comments) && ip->fname != 0)
8562 argptr->raw_length
8563 = final_start +
8564 discard_comments (argptr->raw + final_start,
8565 argptr->raw_length - final_start,
8566 newlines);
8567 argptr->raw[argptr->raw_length] = 0;
8568 if (argptr->raw_length > bufsize + extra)
8569 abort ();
8573 /* If we are not discarding this argument,
8574 macroexpand it and compute its length as stringified.
8575 All this info goes into *ARGPTR. */
8577 if (argptr != 0) {
8578 register U_CHAR *buf, *lim;
8579 register int totlen;
8581 buf = argptr->raw;
8582 lim = buf + argptr->raw_length;
8584 while (buf != lim && is_space[*buf])
8585 buf++;
8586 while (buf != lim && is_space[lim[-1]])
8587 lim--;
8588 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8589 while (buf != lim) {
8590 register U_CHAR c = *buf++;
8591 totlen++;
8592 /* Internal sequences of whitespace are replaced by one space
8593 in most cases, but not always. So count all the whitespace
8594 in case we need to keep it all. */
8595 #if 0
8596 if (is_space[c])
8597 SKIP_ALL_WHITE_SPACE (buf);
8598 else
8599 #endif
8600 if (c == '\"' || c == '\\') /* escape these chars */
8601 totlen++;
8602 else if (!isprint (c))
8603 totlen += 3;
8605 argptr->stringified_length = totlen;
8607 return result;
8610 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8611 counting parens in *DEPTHPTR,
8612 and return if reach LIMIT
8613 or before a `)' that would make *DEPTHPTR negative
8614 or before a comma when *DEPTHPTR is zero.
8615 Single and double quotes are matched and termination
8616 is inhibited within them. Comments also inhibit it.
8617 Value returned is pointer to stopping place.
8619 Increment *NEWLINES each time a newline is passed.
8620 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8621 Set *COMMENTS to 1 if a comment is seen. */
8623 static U_CHAR *
8624 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8625 U_CHAR *start;
8626 register U_CHAR *limit;
8627 int *depthptr, *newlines, *comments;
8628 int rest_args;
8630 register U_CHAR *bp = start;
8632 while (bp < limit) {
8633 switch (*bp) {
8634 case '(':
8635 (*depthptr)++;
8636 break;
8637 case ')':
8638 if (--(*depthptr) < 0)
8639 return bp;
8640 break;
8641 case '\\':
8642 /* Traditionally, backslash makes following char not special. */
8643 if (bp + 1 < limit && traditional)
8645 bp++;
8646 /* But count source lines anyway. */
8647 if (*bp == '\n')
8648 ++*newlines;
8650 break;
8651 case '\n':
8652 ++*newlines;
8653 break;
8654 case '/':
8655 if (bp[1] == '\\' && bp[2] == '\n')
8656 newline_fix (bp + 1);
8657 if (cplusplus_comments && bp[1] == '/') {
8658 *comments = 1;
8659 bp += 2;
8660 while (bp < limit && (*bp != '\n' || bp[-1] == '\\')) {
8661 if (*bp == '\n') ++*newlines;
8662 bp++;
8664 /* Now count the newline that we are about to skip. */
8665 ++*newlines;
8666 break;
8668 if (bp[1] != '*' || bp + 1 >= limit)
8669 break;
8670 *comments = 1;
8671 bp += 2;
8672 while (bp + 1 < limit) {
8673 if (bp[0] == '*'
8674 && bp[1] == '\\' && bp[2] == '\n')
8675 newline_fix (bp + 1);
8676 if (bp[0] == '*' && bp[1] == '/')
8677 break;
8678 if (*bp == '\n') ++*newlines;
8679 bp++;
8681 break;
8682 case '\'':
8683 case '\"':
8685 int quotec;
8686 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8687 if (*bp == '\\') {
8688 bp++;
8689 if (*bp == '\n')
8690 ++*newlines;
8691 while (*bp == '\\' && bp[1] == '\n') {
8692 bp += 2;
8694 } else if (*bp == '\n') {
8695 ++*newlines;
8696 if (quotec == '\'')
8697 break;
8701 break;
8702 case ',':
8703 /* if we've returned to lowest level and we aren't absorbing all args */
8704 if ((*depthptr) == 0 && rest_args == 0)
8705 return bp;
8706 break;
8708 bp++;
8711 return bp;
8714 /* Discard comments and duplicate newlines
8715 in the string of length LENGTH at START,
8716 except inside of string constants.
8717 The string is copied into itself with its beginning staying fixed.
8719 NEWLINES is the number of newlines that must be duplicated.
8720 We assume that that much extra space is available past the end
8721 of the string. */
8723 static int
8724 discard_comments (start, length, newlines)
8725 U_CHAR *start;
8726 int length;
8727 int newlines;
8729 register U_CHAR *ibp;
8730 register U_CHAR *obp;
8731 register U_CHAR *limit;
8732 register int c;
8734 /* If we have newlines to duplicate, copy everything
8735 that many characters up. Then, in the second part,
8736 we will have room to insert the newlines
8737 while copying down.
8738 NEWLINES may actually be too large, because it counts
8739 newlines in string constants, and we don't duplicate those.
8740 But that does no harm. */
8741 if (newlines > 0) {
8742 ibp = start + length;
8743 obp = ibp + newlines;
8744 limit = start;
8745 while (limit != ibp)
8746 *--obp = *--ibp;
8749 ibp = start + newlines;
8750 limit = start + length + newlines;
8751 obp = start;
8753 while (ibp < limit) {
8754 *obp++ = c = *ibp++;
8755 switch (c) {
8756 case '\n':
8757 /* Duplicate the newline. */
8758 *obp++ = '\n';
8759 break;
8761 case '\\':
8762 if (*ibp == '\n') {
8763 obp--;
8764 ibp++;
8766 break;
8768 case '/':
8769 if (*ibp == '\\' && ibp[1] == '\n')
8770 newline_fix (ibp);
8771 /* Delete any comment. */
8772 if (cplusplus_comments && ibp[0] == '/') {
8773 /* Comments are equivalent to spaces. */
8774 obp[-1] = ' ';
8775 ibp++;
8776 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8777 ibp++;
8778 break;
8780 if (ibp[0] != '*' || ibp + 1 >= limit)
8781 break;
8782 /* Comments are equivalent to spaces.
8783 For -traditional, a comment is equivalent to nothing. */
8784 if (traditional)
8785 obp--;
8786 else
8787 obp[-1] = ' ';
8788 ibp++;
8789 while (ibp + 1 < limit) {
8790 if (ibp[0] == '*'
8791 && ibp[1] == '\\' && ibp[2] == '\n')
8792 newline_fix (ibp + 1);
8793 if (ibp[0] == '*' && ibp[1] == '/')
8794 break;
8795 ibp++;
8797 ibp += 2;
8798 break;
8800 case '\'':
8801 case '\"':
8802 /* Notice and skip strings, so that we don't
8803 think that comments start inside them,
8804 and so we don't duplicate newlines in them. */
8806 int quotec = c;
8807 while (ibp < limit) {
8808 *obp++ = c = *ibp++;
8809 if (c == quotec)
8810 break;
8811 if (c == '\n' && quotec == '\'')
8812 break;
8813 if (c == '\\' && ibp < limit) {
8814 while (*ibp == '\\' && ibp[1] == '\n')
8815 ibp += 2;
8816 *obp++ = *ibp++;
8820 break;
8824 return obp - start;
8827 /* Turn newlines to spaces in the string of length LENGTH at START,
8828 except inside of string constants.
8829 The string is copied into itself with its beginning staying fixed. */
8831 static int
8832 change_newlines (start, length)
8833 U_CHAR *start;
8834 int length;
8836 register U_CHAR *ibp;
8837 register U_CHAR *obp;
8838 register U_CHAR *limit;
8839 register int c;
8841 ibp = start;
8842 limit = start + length;
8843 obp = start;
8845 while (ibp < limit) {
8846 *obp++ = c = *ibp++;
8847 switch (c) {
8848 case '\n':
8849 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8850 string. Skip past the newline and its duplicate.
8851 Put a space in the output. */
8852 if (*ibp == '\n')
8854 ibp++;
8855 obp--;
8856 *obp++ = ' ';
8858 break;
8860 case '\'':
8861 case '\"':
8862 /* Notice and skip strings, so that we don't delete newlines in them. */
8864 int quotec = c;
8865 while (ibp < limit) {
8866 *obp++ = c = *ibp++;
8867 if (c == quotec)
8868 break;
8869 if (c == '\n' && quotec == '\'')
8870 break;
8873 break;
8877 return obp - start;
8881 * my_strerror - return the descriptive text associated with an `errno' code.
8884 char *
8885 my_strerror (errnum)
8886 int errnum;
8888 char *result;
8890 #ifndef VMS
8891 #ifndef HAVE_STRERROR
8892 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8893 #else
8894 result = strerror (errnum);
8895 #endif
8896 #else /* VMS */
8897 /* VAXCRTL's strerror() takes an optional second argument, which only
8898 matters when the first argument is EVMSERR. However, it's simplest
8899 just to pass it unconditionally. `vaxc$errno' is declared in
8900 <errno.h>, and maintained by the library in parallel with `errno'.
8901 We assume that caller's `errnum' either matches the last setting of
8902 `errno' by the library or else does not have the value `EVMSERR'. */
8904 result = strerror (errnum, vaxc$errno);
8905 #endif
8907 if (!result)
8908 result = "undocumented I/O error";
8910 return result;
8914 * error - print error message and increment count of errors.
8917 void
8918 error (PRINTF_ALIST (msg))
8919 PRINTF_DCL (msg)
8921 va_list args;
8923 VA_START (args, msg);
8924 verror (msg, args);
8925 va_end (args);
8928 static void
8929 verror (msg, args)
8930 char *msg;
8931 va_list args;
8933 int i;
8934 FILE_BUF *ip = NULL;
8936 print_containing_files ();
8938 for (i = indepth; i >= 0; i--)
8939 if (instack[i].fname != NULL) {
8940 ip = &instack[i];
8941 break;
8944 if (ip != NULL)
8945 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8946 vfprintf (stderr, msg, args);
8947 fprintf (stderr, "\n");
8948 errors++;
8951 /* Error including a message from `errno'. */
8953 static void
8954 error_from_errno (name)
8955 char *name;
8957 int i;
8958 FILE_BUF *ip = NULL;
8960 print_containing_files ();
8962 for (i = indepth; i >= 0; i--)
8963 if (instack[i].fname != NULL) {
8964 ip = &instack[i];
8965 break;
8968 if (ip != NULL)
8969 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8971 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8973 errors++;
8976 /* Print error message but don't count it. */
8978 void
8979 warning (PRINTF_ALIST (msg))
8980 PRINTF_DCL (msg)
8982 va_list args;
8984 VA_START (args, msg);
8985 vwarning (msg, args);
8986 va_end (args);
8989 static void
8990 vwarning (msg, args)
8991 char *msg;
8992 va_list args;
8994 int i;
8995 FILE_BUF *ip = NULL;
8997 if (inhibit_warnings)
8998 return;
9000 if (warnings_are_errors)
9001 errors++;
9003 print_containing_files ();
9005 for (i = indepth; i >= 0; i--)
9006 if (instack[i].fname != NULL) {
9007 ip = &instack[i];
9008 break;
9011 if (ip != NULL)
9012 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
9013 fprintf (stderr, "warning: ");
9014 vfprintf (stderr, msg, args);
9015 fprintf (stderr, "\n");
9018 static void
9019 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9020 error_with_line (int line, PRINTF_ALIST (msg))
9021 #else
9022 error_with_line (line, PRINTF_ALIST (msg))
9023 int line;
9024 PRINTF_DCL (msg)
9025 #endif
9027 va_list args;
9029 VA_START (args, msg);
9030 verror_with_line (line, msg, args);
9031 va_end (args);
9034 static void
9035 verror_with_line (line, msg, args)
9036 int line;
9037 char *msg;
9038 va_list args;
9040 int i;
9041 FILE_BUF *ip = NULL;
9043 print_containing_files ();
9045 for (i = indepth; i >= 0; i--)
9046 if (instack[i].fname != NULL) {
9047 ip = &instack[i];
9048 break;
9051 if (ip != NULL)
9052 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
9053 vfprintf (stderr, msg, args);
9054 fprintf (stderr, "\n");
9055 errors++;
9058 static void
9059 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9060 warning_with_line (int line, PRINTF_ALIST (msg))
9061 #else
9062 warning_with_line (line, PRINTF_ALIST (msg))
9063 int line;
9064 PRINTF_DCL (msg)
9065 #endif
9067 va_list args;
9069 VA_START (args, msg);
9070 vwarning_with_line (line, msg, args);
9071 va_end (args);
9074 static void
9075 vwarning_with_line (line, msg, args)
9076 int line;
9077 char *msg;
9078 va_list args;
9080 int i;
9081 FILE_BUF *ip = NULL;
9083 if (inhibit_warnings)
9084 return;
9086 if (warnings_are_errors)
9087 errors++;
9089 print_containing_files ();
9091 for (i = indepth; i >= 0; i--)
9092 if (instack[i].fname != NULL) {
9093 ip = &instack[i];
9094 break;
9097 if (ip != NULL)
9098 fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
9099 fprintf (stderr, "warning: ");
9100 vfprintf (stderr, msg, args);
9101 fprintf (stderr, "\n");
9104 /* print an error message and maybe count it. */
9106 void
9107 pedwarn (PRINTF_ALIST (msg))
9108 PRINTF_DCL (msg)
9110 va_list args;
9112 VA_START (args, msg);
9113 if (pedantic_errors)
9114 verror (msg, args);
9115 else
9116 vwarning (msg, args);
9117 va_end (args);
9120 void
9121 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9122 pedwarn_with_line (int line, PRINTF_ALIST (msg))
9123 #else
9124 pedwarn_with_line (line, PRINTF_ALIST (msg))
9125 int line;
9126 PRINTF_DCL (msg)
9127 #endif
9129 va_list args;
9131 VA_START (args, msg);
9132 if (pedantic_errors)
9133 verror_with_line (line, msg, args);
9134 else
9135 vwarning_with_line (line, msg, args);
9136 va_end (args);
9139 /* Report a warning (or an error if pedantic_errors)
9140 giving specified file name and line number, not current. */
9142 static void
9143 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9144 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
9145 #else
9146 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
9147 char *file;
9148 int line;
9149 PRINTF_DCL (msg)
9150 #endif
9152 va_list args;
9154 if (!pedantic_errors && inhibit_warnings)
9155 return;
9156 if (file != NULL)
9157 fprintf (stderr, "%s:%d: ", file, line);
9158 if (pedantic_errors)
9159 errors++;
9160 if (!pedantic_errors)
9161 fprintf (stderr, "warning: ");
9162 VA_START (args, msg);
9163 vfprintf (stderr, msg, args);
9164 va_end (args);
9165 fprintf (stderr, "\n");
9168 /* Print the file names and line numbers of the #include
9169 directives which led to the current file. */
9171 static void
9172 print_containing_files ()
9174 FILE_BUF *ip = NULL;
9175 int i;
9176 int first = 1;
9178 /* If stack of files hasn't changed since we last printed
9179 this info, don't repeat it. */
9180 if (last_error_tick == input_file_stack_tick)
9181 return;
9183 for (i = indepth; i >= 0; i--)
9184 if (instack[i].fname != NULL) {
9185 ip = &instack[i];
9186 break;
9189 /* Give up if we don't find a source file. */
9190 if (ip == NULL)
9191 return;
9193 /* Find the other, outer source files. */
9194 for (i--; i >= 0; i--)
9195 if (instack[i].fname != NULL) {
9196 ip = &instack[i];
9197 if (first) {
9198 first = 0;
9199 fprintf (stderr, "In file included");
9200 } else {
9201 fprintf (stderr, ",\n ");
9204 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9206 if (! first)
9207 fprintf (stderr, ":\n");
9209 /* Record we have printed the status as of this time. */
9210 last_error_tick = input_file_stack_tick;
9213 /* Return the line at which an error occurred.
9214 The error is not necessarily associated with the current spot
9215 in the input stack, so LINE says where. LINE will have been
9216 copied from ip->lineno for the current input level.
9217 If the current level is for a file, we return LINE.
9218 But if the current level is not for a file, LINE is meaningless.
9219 In that case, we return the lineno of the innermost file. */
9221 static int
9222 line_for_error (line)
9223 int line;
9225 int i;
9226 int line1 = line;
9228 for (i = indepth; i >= 0; ) {
9229 if (instack[i].fname != 0)
9230 return line1;
9231 i--;
9232 if (i < 0)
9233 return 0;
9234 line1 = instack[i].lineno;
9236 abort ();
9237 /*NOTREACHED*/
9238 return 0;
9242 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9244 * As things stand, nothing is ever placed in the output buffer to be
9245 * removed again except when it's KNOWN to be part of an identifier,
9246 * so flushing and moving down everything left, instead of expanding,
9247 * should work ok.
9250 /* You might think void was cleaner for the return type,
9251 but that would get type mismatch in check_expand in strict ANSI. */
9252 static int
9253 grow_outbuf (obuf, needed)
9254 register FILE_BUF *obuf;
9255 register int needed;
9257 register U_CHAR *p;
9258 int minsize;
9260 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9261 return 0;
9263 /* Make it at least twice as big as it is now. */
9264 obuf->length *= 2;
9265 /* Make it have at least 150% of the free space we will need. */
9266 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9267 if (minsize > obuf->length)
9268 obuf->length = minsize;
9270 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9271 memory_full ();
9273 obuf->bufp = p + (obuf->bufp - obuf->buf);
9274 obuf->buf = p;
9276 return 0;
9279 /* Symbol table for macro names and special symbols */
9282 * install a name in the main hash table, even if it is already there.
9283 * name stops with first non alphanumeric, except leading '#'.
9284 * caller must check against redefinition if that is desired.
9285 * delete_macro () removes things installed by install () in fifo order.
9286 * this is important because of the `defined' special symbol used
9287 * in #if, and also if pushdef/popdef directives are ever implemented.
9289 * If LEN is >= 0, it is the length of the name.
9290 * Otherwise, compute the length by scanning the entire name.
9292 * If HASH is >= 0, it is the precomputed hash code.
9293 * Otherwise, compute the hash code.
9295 static HASHNODE *
9296 install (name, len, type, value, hash)
9297 U_CHAR *name;
9298 int len;
9299 enum node_type type;
9300 char *value;
9301 int hash;
9303 register HASHNODE *hp;
9304 register int i, bucket;
9305 register U_CHAR *p, *q;
9307 if (len < 0) {
9308 p = name;
9309 while (is_idchar[*p])
9310 p++;
9311 len = p - name;
9314 if (hash < 0)
9315 hash = hashf (name, len, HASHSIZE);
9317 i = sizeof (HASHNODE) + len + 1;
9318 hp = (HASHNODE *) xmalloc (i);
9319 bucket = hash;
9320 hp->bucket_hdr = &hashtab[bucket];
9321 hp->next = hashtab[bucket];
9322 hashtab[bucket] = hp;
9323 hp->prev = NULL;
9324 if (hp->next != NULL)
9325 hp->next->prev = hp;
9326 hp->type = type;
9327 hp->length = len;
9328 hp->value.cpval = value;
9329 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9330 p = hp->name;
9331 q = name;
9332 for (i = 0; i < len; i++)
9333 *p++ = *q++;
9334 hp->name[len] = 0;
9335 return hp;
9339 * find the most recent hash node for name name (ending with first
9340 * non-identifier char) installed by install
9342 * If LEN is >= 0, it is the length of the name.
9343 * Otherwise, compute the length by scanning the entire name.
9345 * If HASH is >= 0, it is the precomputed hash code.
9346 * Otherwise, compute the hash code.
9348 HASHNODE *
9349 lookup (name, len, hash)
9350 U_CHAR *name;
9351 int len;
9352 int hash;
9354 register U_CHAR *bp;
9355 register HASHNODE *bucket;
9357 if (len < 0) {
9358 for (bp = name; is_idchar[*bp]; bp++) ;
9359 len = bp - name;
9362 if (hash < 0)
9363 hash = hashf (name, len, HASHSIZE);
9365 bucket = hashtab[hash];
9366 while (bucket) {
9367 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9368 return bucket;
9369 bucket = bucket->next;
9371 return NULL;
9375 * Delete a hash node. Some weirdness to free junk from macros.
9376 * More such weirdness will have to be added if you define more hash
9377 * types that need it.
9380 /* Note that the DEFINITION of a macro is removed from the hash table
9381 but its storage is not freed. This would be a storage leak
9382 except that it is not reasonable to keep undefining and redefining
9383 large numbers of macros many times.
9384 In any case, this is necessary, because a macro can be #undef'd
9385 in the middle of reading the arguments to a call to it.
9386 If #undef freed the DEFINITION, that would crash. */
9388 static void
9389 delete_macro (hp)
9390 HASHNODE *hp;
9393 if (hp->prev != NULL)
9394 hp->prev->next = hp->next;
9395 if (hp->next != NULL)
9396 hp->next->prev = hp->prev;
9398 /* make sure that the bucket chain header that
9399 the deleted guy was on points to the right thing afterwards. */
9400 if (hp == *hp->bucket_hdr)
9401 *hp->bucket_hdr = hp->next;
9403 #if 0
9404 if (hp->type == T_MACRO) {
9405 DEFINITION *d = hp->value.defn;
9406 struct reflist *ap, *nextap;
9408 for (ap = d->pattern; ap != NULL; ap = nextap) {
9409 nextap = ap->next;
9410 free (ap);
9412 free (d);
9414 #endif
9415 free (hp);
9419 * return hash function on name. must be compatible with the one
9420 * computed a step at a time, elsewhere
9422 static int
9423 hashf (name, len, hashsize)
9424 register U_CHAR *name;
9425 register int len;
9426 int hashsize;
9428 register int r = 0;
9430 while (len--)
9431 r = HASHSTEP (r, *name++);
9433 return MAKE_POS (r) % hashsize;
9437 /* Dump the definition of a single macro HP to OF. */
9438 static void
9439 dump_single_macro (hp, of)
9440 register HASHNODE *hp;
9441 FILE *of;
9443 register DEFINITION *defn = hp->value.defn;
9444 struct reflist *ap;
9445 int offset;
9446 int concat;
9449 /* Print the definition of the macro HP. */
9451 fprintf (of, "#define %s", hp->name);
9453 if (defn->nargs >= 0) {
9454 int i;
9456 fprintf (of, "(");
9457 for (i = 0; i < defn->nargs; i++) {
9458 dump_arg_n (defn, i, of);
9459 if (i + 1 < defn->nargs)
9460 fprintf (of, ", ");
9462 fprintf (of, ")");
9465 fprintf (of, " ");
9467 offset = 0;
9468 concat = 0;
9469 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9470 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9471 offset += ap->nchars;
9472 if (!traditional) {
9473 if (ap->nchars != 0)
9474 concat = 0;
9475 if (ap->stringify) {
9476 switch (ap->stringify) {
9477 case SHARP_TOKEN: fprintf (of, "#"); break;
9478 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9479 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9480 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9481 default: abort ();
9484 if (ap->raw_before != 0) {
9485 if (concat) {
9486 switch (ap->raw_before) {
9487 case WHITE_SHARP_TOKEN:
9488 case WHITE_PERCENT_COLON_TOKEN:
9489 fprintf (of, " ");
9490 break;
9491 default:
9492 break;
9494 } else {
9495 switch (ap->raw_before) {
9496 case SHARP_TOKEN: fprintf (of, "##"); break;
9497 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9498 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9499 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9500 default: abort ();
9504 concat = 0;
9506 dump_arg_n (defn, ap->argno, of);
9507 if (!traditional && ap->raw_after != 0) {
9508 switch (ap->raw_after) {
9509 case SHARP_TOKEN: fprintf (of, "##"); break;
9510 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9511 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9512 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9513 default: abort ();
9515 concat = 1;
9518 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9519 fprintf (of, "\n");
9522 /* Dump all macro definitions as #defines to stdout. */
9524 static void
9525 dump_all_macros ()
9527 int bucket;
9529 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9530 register HASHNODE *hp;
9532 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9533 if (hp->type == T_MACRO)
9534 dump_single_macro (hp, stdout);
9539 /* Output to OF a substring of a macro definition.
9540 BASE is the beginning of the definition.
9541 Output characters START thru LENGTH.
9542 Unless traditional, discard newlines outside of strings, thus
9543 converting funny-space markers to ordinary spaces. */
9545 static void
9546 dump_defn_1 (base, start, length, of)
9547 U_CHAR *base;
9548 int start;
9549 int length;
9550 FILE *of;
9552 U_CHAR *p = base + start;
9553 U_CHAR *limit = base + start + length;
9555 if (traditional)
9556 fwrite (p, sizeof (*p), length, of);
9557 else {
9558 while (p < limit) {
9559 if (*p == '\"' || *p =='\'') {
9560 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9561 NULL_PTR, NULL_PTR);
9562 fwrite (p, sizeof (*p), p1 - p, of);
9563 p = p1;
9564 } else {
9565 if (*p != '\n')
9566 putc (*p, of);
9567 p++;
9573 /* Print the name of argument number ARGNUM of macro definition DEFN
9574 to OF.
9575 Recall that DEFN->args.argnames contains all the arg names
9576 concatenated in reverse order with comma-space in between. */
9578 static void
9579 dump_arg_n (defn, argnum, of)
9580 DEFINITION *defn;
9581 int argnum;
9582 FILE *of;
9584 register U_CHAR *p = defn->args.argnames;
9585 while (argnum + 1 < defn->nargs) {
9586 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9587 argnum++;
9590 while (*p && *p != ',') {
9591 putc (*p, of);
9592 p++;
9596 /* Initialize syntactic classifications of characters. */
9598 static void
9599 initialize_char_syntax ()
9601 register int i;
9604 * Set up is_idchar and is_idstart tables. These should be
9605 * faster than saying (is_alpha (c) || c == '_'), etc.
9606 * Set up these things before calling any routines tthat
9607 * refer to them.
9609 for (i = 'a'; i <= 'z'; i++) {
9610 is_idchar[i - 'a' + 'A'] = 1;
9611 is_idchar[i] = 1;
9612 is_idstart[i - 'a' + 'A'] = 1;
9613 is_idstart[i] = 1;
9615 for (i = '0'; i <= '9'; i++)
9616 is_idchar[i] = 1;
9617 is_idchar['_'] = 1;
9618 is_idstart['_'] = 1;
9619 is_idchar['$'] = dollars_in_ident;
9620 is_idstart['$'] = dollars_in_ident;
9622 /* horizontal space table */
9623 is_hor_space[' '] = 1;
9624 is_hor_space['\t'] = 1;
9625 is_hor_space['\v'] = 1;
9626 is_hor_space['\f'] = 1;
9627 is_hor_space['\r'] = 1;
9629 is_space[' '] = 1;
9630 is_space['\t'] = 1;
9631 is_space['\v'] = 1;
9632 is_space['\f'] = 1;
9633 is_space['\n'] = 1;
9634 is_space['\r'] = 1;
9636 char_name['\v'] = "vertical tab";
9637 char_name['\f'] = "formfeed";
9638 char_name['\r'] = "carriage return";
9641 /* Initialize the built-in macros. */
9643 static void
9644 initialize_builtins (inp, outp)
9645 FILE_BUF *inp;
9646 FILE_BUF *outp;
9648 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9649 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9650 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9651 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9652 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9653 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9654 #ifndef NO_BUILTIN_SIZE_TYPE
9655 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9656 #endif
9657 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9658 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9659 #endif
9660 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9661 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9662 NULL_PTR, -1);
9663 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9664 NULL_PTR, -1);
9665 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9666 NULL_PTR, -1);
9667 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9668 if (!traditional) {
9669 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9670 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9672 if (objc)
9673 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9674 /* This is supplied using a -D by the compiler driver
9675 so that it is present only when truly compiling with GNU C. */
9676 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9678 if (debug_output)
9680 char directive[2048];
9681 U_CHAR *udirective = (U_CHAR *) directive;
9682 register struct directive *dp = &directive_table[0];
9683 struct tm *timebuf = timestamp ();
9685 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9686 instack[0].nominal_fname);
9687 output_line_directive (inp, outp, 0, same_file);
9688 pass_thru_directive (udirective, &udirective[strlen (directive)],
9689 outp, dp);
9691 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9692 output_line_directive (inp, outp, 0, same_file);
9693 pass_thru_directive (udirective, &udirective[strlen (directive)],
9694 outp, dp);
9696 #ifndef NO_BUILTIN_SIZE_TYPE
9697 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9698 output_line_directive (inp, outp, 0, same_file);
9699 pass_thru_directive (udirective, &udirective[strlen (directive)],
9700 outp, dp);
9701 #endif
9703 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9704 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9705 output_line_directive (inp, outp, 0, same_file);
9706 pass_thru_directive (udirective, &udirective[strlen (directive)],
9707 outp, dp);
9708 #endif
9710 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9711 output_line_directive (inp, outp, 0, same_file);
9712 pass_thru_directive (udirective, &udirective[strlen (directive)],
9713 outp, dp);
9715 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9716 monthnames[timebuf->tm_mon],
9717 timebuf->tm_mday, timebuf->tm_year + 1900);
9718 output_line_directive (inp, outp, 0, same_file);
9719 pass_thru_directive (udirective, &udirective[strlen (directive)],
9720 outp, dp);
9722 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9723 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9724 output_line_directive (inp, outp, 0, same_file);
9725 pass_thru_directive (udirective, &udirective[strlen (directive)],
9726 outp, dp);
9728 if (!traditional)
9730 sprintf (directive, " __STDC__ 1");
9731 output_line_directive (inp, outp, 0, same_file);
9732 pass_thru_directive (udirective, &udirective[strlen (directive)],
9733 outp, dp);
9735 if (objc)
9737 sprintf (directive, " __OBJC__ 1");
9738 output_line_directive (inp, outp, 0, same_file);
9739 pass_thru_directive (udirective, &udirective[strlen (directive)],
9740 outp, dp);
9746 * process a given definition string, for initialization
9747 * If STR is just an identifier, define it with value 1.
9748 * If STR has anything after the identifier, then it should
9749 * be identifier=definition.
9752 static void
9753 make_definition (str, op)
9754 char *str;
9755 FILE_BUF *op;
9757 FILE_BUF *ip;
9758 struct directive *kt;
9759 U_CHAR *buf, *p;
9761 p = buf = (U_CHAR *) str;
9762 if (!is_idstart[*p]) {
9763 error ("malformed option `-D %s'", str);
9764 return;
9766 while (is_idchar[*++p])
9768 if (*p == '(') {
9769 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9771 if (*p++ != ')')
9772 p = (U_CHAR *) str; /* Error */
9774 if (*p == 0) {
9775 buf = (U_CHAR *) alloca (p - buf + 4);
9776 strcpy ((char *)buf, str);
9777 strcat ((char *)buf, " 1");
9778 } else if (*p != '=') {
9779 error ("malformed option `-D %s'", str);
9780 return;
9781 } else {
9782 U_CHAR *q;
9783 /* Copy the entire option so we can modify it. */
9784 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9785 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9786 /* Change the = to a space. */
9787 buf[p - (U_CHAR *) str] = ' ';
9788 /* Scan for any backslash-newline and remove it. */
9789 p++;
9790 q = &buf[p - (U_CHAR *) str];
9791 while (*p) {
9792 if (*p == '\"' || *p == '\'') {
9793 int unterminated = 0;
9794 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9795 NULL_PTR, NULL_PTR, &unterminated);
9796 if (unterminated)
9797 return;
9798 while (p != p1)
9799 if (*p == '\\' && p[1] == '\n')
9800 p += 2;
9801 else
9802 *q++ = *p++;
9803 } else if (*p == '\\' && p[1] == '\n')
9804 p += 2;
9805 /* Change newline chars into newline-markers. */
9806 else if (*p == '\n')
9808 *q++ = '\n';
9809 *q++ = '\n';
9810 p++;
9812 else
9813 *q++ = *p++;
9815 *q = 0;
9818 ip = &instack[++indepth];
9819 ip->nominal_fname = ip->fname = "*Initialization*";
9821 ip->buf = ip->bufp = buf;
9822 ip->length = strlen ((char *) buf);
9823 ip->lineno = 1;
9824 ip->macro = 0;
9825 ip->free_ptr = 0;
9826 ip->if_stack = if_stack;
9827 ip->system_header_p = 0;
9829 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9832 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9833 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9834 --indepth;
9837 /* JF, this does the work for the -U option */
9839 static void
9840 make_undef (str, op)
9841 char *str;
9842 FILE_BUF *op;
9844 FILE_BUF *ip;
9845 struct directive *kt;
9847 ip = &instack[++indepth];
9848 ip->nominal_fname = ip->fname = "*undef*";
9850 ip->buf = ip->bufp = (U_CHAR *) str;
9851 ip->length = strlen (str);
9852 ip->lineno = 1;
9853 ip->macro = 0;
9854 ip->free_ptr = 0;
9855 ip->if_stack = if_stack;
9856 ip->system_header_p = 0;
9858 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9861 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9862 --indepth;
9865 /* Process the string STR as if it appeared as the body of a #assert.
9866 OPTION is the option name for which STR was the argument. */
9868 static void
9869 make_assertion (option, str)
9870 char *option;
9871 char *str;
9873 FILE_BUF *ip;
9874 struct directive *kt;
9875 U_CHAR *buf, *p, *q;
9877 /* Copy the entire option so we can modify it. */
9878 buf = (U_CHAR *) alloca (strlen (str) + 2); /* 1 added to alloca length by AMB */
9879 strcpy ((char *) buf, str);
9880 /* Scan for any backslash-newline and remove it. */
9881 p = q = buf;
9882 while (*p) {
9883 if (*p == '\\' && p[1] == '\n')
9884 p += 2;
9885 else
9886 *q++ = *p++;
9888 *q = 0;
9890 p = buf;
9891 if (!is_idstart[*p]) {
9892 error ("malformed option `%s %s'", option, str);
9893 return;
9895 while (is_idchar[*++p])
9897 SKIP_WHITE_SPACE (p);
9898 if (! (*p == 0 || *p == '(' || *p == '=')) { /* Allowed to use 'foo=bar' instead of 'foo(bar)' by AMB */
9899 error ("malformed option `%s %s'", option, str);
9900 return;
9903 /* Start change added by AMB (handles gcc 3.x "-Afoo=bar") */
9904 if(*p=='=')
9906 *p='(';
9907 strcat(p,")");
9909 /* End change added by AMB (handles gcc 3.x "-Afoo=bar") */
9911 ip = &instack[++indepth];
9912 ip->nominal_fname = ip->fname = "*Initialization*";
9914 ip->buf = ip->bufp = buf;
9915 ip->length = strlen ((char *) buf);
9916 ip->lineno = 1;
9917 ip->macro = 0;
9918 ip->free_ptr = 0;
9919 ip->if_stack = if_stack;
9920 ip->system_header_p = 0;
9922 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9925 /* pass NULL as output ptr to do_define since we KNOW it never
9926 does any output.... */
9927 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9928 --indepth;
9931 /* Append a chain of `struct file_name_list's
9932 to the end of the main include chain.
9933 FIRST is the beginning of the chain to append, and LAST is the end. */
9935 static void
9936 append_include_chain (first, last)
9937 struct file_name_list *first, *last;
9939 struct file_name_list *dir;
9941 if (!first || !last)
9942 return;
9944 if (include == 0)
9945 include = first;
9946 else
9947 last_include->next = first;
9949 if (first_bracket_include == 0)
9950 first_bracket_include = first;
9952 for (dir = first; ; dir = dir->next) {
9953 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9954 if (len > max_include_len)
9955 max_include_len = len;
9956 if (dir == last)
9957 break;
9960 last->next = NULL;
9961 last_include = last;
9964 /* Add output to `deps_buffer' for the -M switch.
9965 STRING points to the text to be output.
9966 SPACER is ':' for targets, ' ' for dependencies. */
9968 static void
9969 deps_output (string, spacer)
9970 char *string;
9971 int spacer;
9973 int size = strlen (string);
9975 if (size == 0)
9976 return;
9978 #ifndef MAX_OUTPUT_COLUMNS
9979 #define MAX_OUTPUT_COLUMNS 72
9980 #endif
9981 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9982 && 1 < deps_column) {
9983 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9984 deps_size += 4;
9985 deps_column = 1;
9986 if (spacer == ' ')
9987 spacer = 0;
9990 if (deps_size + size + 8 > deps_allocated_size) {
9991 deps_allocated_size = (deps_size + size + 50) * 2;
9992 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
9994 if (spacer == ' ') {
9995 deps_buffer[deps_size++] = ' ';
9996 deps_column++;
9998 bcopy (string, &deps_buffer[deps_size], size);
9999 deps_size += size;
10000 deps_column += size;
10001 if (spacer == ':') {
10002 deps_buffer[deps_size++] = ':';
10003 deps_column++;
10005 deps_buffer[deps_size] = 0;
10008 static void
10009 fatal (PRINTF_ALIST (msg))
10010 PRINTF_DCL (msg)
10012 va_list args;
10014 fprintf (stderr, "%s: ", progname);
10015 VA_START (args, msg);
10016 vfprintf (stderr, msg, args);
10017 va_end (args);
10018 fprintf (stderr, "\n");
10019 exit (FATAL_EXIT_CODE);
10022 /* More 'friendly' abort that prints the line and file.
10023 config.h can #define abort fancy_abort if you like that sort of thing. */
10025 void
10026 fancy_abort ()
10028 fatal ("Internal gcc abort.");
10031 static void
10032 perror_with_name (name)
10033 char *name;
10035 fprintf (stderr, "%s: ", progname);
10036 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
10037 errors++;
10040 static void
10041 pfatal_with_name (name)
10042 char *name;
10044 perror_with_name (name);
10045 #ifdef VMS
10046 exit (vaxc$errno);
10047 #else
10048 exit (FATAL_EXIT_CODE);
10049 #endif
10052 /* Handler for SIGPIPE. */
10054 static void
10055 pipe_closed (signo)
10056 /* If this is missing, some compilers complain. */
10057 int signo;
10059 fatal ("output pipe has been closed");
10062 static void
10063 memory_full ()
10065 fatal ("Memory exhausted.");
10069 GENERIC_PTR
10070 xmalloc (size)
10071 size_t size;
10073 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10074 if (!ptr)
10075 memory_full ();
10076 return ptr;
10079 static GENERIC_PTR
10080 xrealloc (old, size)
10081 GENERIC_PTR old;
10082 size_t size;
10084 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10085 if (!ptr)
10086 memory_full ();
10087 return ptr;
10090 static GENERIC_PTR
10091 xcalloc (number, size)
10092 size_t number, size;
10094 register size_t total = number * size;
10095 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10096 if (!ptr)
10097 memory_full ();
10098 bzero (ptr, total);
10099 return ptr;
10102 static char *
10103 savestring (input)
10104 char *input;
10106 size_t size = strlen (input);
10107 char *output = xmalloc (size + 1);
10108 strcpy (output, input);
10109 return output;
10112 /* Get the file-mode and data size of the file open on FD
10113 and store them in *MODE_POINTER and *SIZE_POINTER. */
10115 static int
10116 file_size_and_mode (fd, mode_pointer, size_pointer)
10117 int fd;
10118 int *mode_pointer;
10119 long int *size_pointer;
10121 struct stat sbuf;
10123 if (fstat (fd, &sbuf) < 0) return (-1);
10124 if (mode_pointer) *mode_pointer = sbuf.st_mode;
10125 if (size_pointer) *size_pointer = sbuf.st_size;
10126 return 0;
10129 #ifdef VMS
10131 /* Under VMS we need to fix up the "include" specification
10132 filename so that everything following the 1st slash is
10133 changed into its correct VMS file specification. */
10135 static void
10136 hack_vms_include_specification (fname)
10137 char *fname;
10139 register char *cp, *cp1, *cp2;
10140 int f, check_filename_before_returning, no_prefix_seen;
10141 char Local[512];
10143 check_filename_before_returning = 0;
10144 no_prefix_seen = 0;
10146 /* Ignore leading "./"s */
10147 while (fname[0] == '.' && fname[1] == '/') {
10148 strcpy (fname, fname+2);
10149 no_prefix_seen = 1; /* mark this for later */
10151 /* Look for the boundary between the VMS and UNIX filespecs */
10152 cp = rindex (fname, ']'); /* Look for end of dirspec. */
10153 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
10154 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
10155 if (cp) {
10156 cp++;
10157 } else {
10158 cp = index (fname, '/'); /* Look for the "/" */
10162 * Check if we have a vax-c style '#include filename'
10163 * and add the missing .h
10165 if (cp == 0) {
10166 if (index(fname,'.') == 0)
10167 strcat(fname, ".h");
10168 } else {
10169 if (index(cp,'.') == 0)
10170 strcat(cp, ".h");
10173 cp2 = Local; /* initialize */
10175 /* We are trying to do a number of things here. First of all, we are
10176 trying to hammer the filenames into a standard format, such that later
10177 processing can handle them.
10179 If the file name contains something like [dir.], then it recognizes this
10180 as a root, and strips the ".]". Later processing will add whatever is
10181 needed to get things working properly.
10183 If no device is specified, then the first directory name is taken to be
10184 a device name (or a rooted logical). */
10186 /* See if we found that 1st slash */
10187 if (cp == 0) return; /* Nothing to do!!! */
10188 if (*cp != '/') return; /* Nothing to do!!! */
10189 /* Point to the UNIX filename part (which needs to be fixed!) */
10190 cp1 = cp+1;
10191 /* If the directory spec is not rooted, we can just copy
10192 the UNIX filename part and we are done */
10193 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10194 if (cp[-2] != '.') {
10196 * The VMS part ends in a `]', and the preceding character is not a `.'.
10197 * We strip the `]', and then splice the two parts of the name in the
10198 * usual way. Given the default locations for include files in cccp.c,
10199 * we will only use this code if the user specifies alternate locations
10200 * with the /include (-I) switch on the command line. */
10201 cp -= 1; /* Strip "]" */
10202 cp1--; /* backspace */
10203 } else {
10205 * The VMS part has a ".]" at the end, and this will not do. Later
10206 * processing will add a second directory spec, and this would be a syntax
10207 * error. Thus we strip the ".]", and thus merge the directory specs.
10208 * We also backspace cp1, so that it points to a '/'. This inhibits the
10209 * generation of the 000000 root directory spec (which does not belong here
10210 * in this case).
10212 cp -= 2; /* Strip ".]" */
10213 cp1--; }; /* backspace */
10214 } else {
10216 /* We drop in here if there is no VMS style directory specification yet.
10217 * If there is no device specification either, we make the first dir a
10218 * device and try that. If we do not do this, then we will be essentially
10219 * searching the users default directory (as if they did a #include "asdf.h").
10221 * Then all we need to do is to push a '[' into the output string. Later
10222 * processing will fill this in, and close the bracket.
10224 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10225 *cp2++ = '['; /* Open the directory specification */
10228 /* at this point we assume that we have the device spec, and (at least
10229 the opening "[" for a directory specification. We may have directories
10230 specified already */
10232 /* If there are no other slashes then the filename will be
10233 in the "root" directory. Otherwise, we need to add
10234 directory specifications. */
10235 if (index (cp1, '/') == 0) {
10236 /* Just add "000000]" as the directory string */
10237 strcpy (cp2, "000000]");
10238 cp2 += strlen (cp2);
10239 check_filename_before_returning = 1; /* we might need to fool with this later */
10240 } else {
10241 /* As long as there are still subdirectories to add, do them. */
10242 while (index (cp1, '/') != 0) {
10243 /* If this token is "." we can ignore it */
10244 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10245 cp1 += 2;
10246 continue;
10248 /* Add a subdirectory spec. Do not duplicate "." */
10249 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10250 *cp2++ = '.';
10251 /* If this is ".." then the spec becomes "-" */
10252 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10253 /* Add "-" and skip the ".." */
10254 *cp2++ = '-';
10255 cp1 += 3;
10256 continue;
10258 /* Copy the subdirectory */
10259 while (*cp1 != '/') *cp2++= *cp1++;
10260 cp1++; /* Skip the "/" */
10262 /* Close the directory specification */
10263 if (cp2[-1] == '.') /* no trailing periods */
10264 cp2--;
10265 *cp2++ = ']';
10267 /* Now add the filename */
10268 while (*cp1) *cp2++ = *cp1++;
10269 *cp2 = 0;
10270 /* Now append it to the original VMS spec. */
10271 strcpy (cp, Local);
10273 /* If we put a [000000] in the filename, try to open it first. If this fails,
10274 remove the [000000], and return that name. This provides flexibility
10275 to the user in that they can use both rooted and non-rooted logical names
10276 to point to the location of the file. */
10278 if (check_filename_before_returning && no_prefix_seen) {
10279 f = open (fname, O_RDONLY, 0666);
10280 if (f >= 0) {
10281 /* The file name is OK as it is, so return it as is. */
10282 close (f);
10283 return;
10285 /* The filename did not work. Try to remove the [000000] from the name,
10286 and return it. */
10287 cp = index (fname, '[');
10288 cp2 = index (fname, ']') + 1;
10289 strcpy (cp, cp2); /* this gets rid of it */
10291 return;
10293 #endif /* VMS */
10295 #ifdef VMS
10297 /* These are the read/write replacement routines for
10298 VAX-11 "C". They make read/write behave enough
10299 like their UNIX counterparts that CCCP will work */
10301 static int
10302 read (fd, buf, size)
10303 int fd;
10304 char *buf;
10305 int size;
10307 #undef read /* Get back the REAL read routine */
10308 register int i;
10309 register int total = 0;
10311 /* Read until the buffer is exhausted */
10312 while (size > 0) {
10313 /* Limit each read to 32KB */
10314 i = (size > (32*1024)) ? (32*1024) : size;
10315 i = read (fd, buf, i);
10316 if (i <= 0) {
10317 if (i == 0) return (total);
10318 return (i);
10320 /* Account for this read */
10321 total += i;
10322 buf += i;
10323 size -= i;
10325 return (total);
10328 static int
10329 write (fd, buf, size)
10330 int fd;
10331 char *buf;
10332 int size;
10334 #undef write /* Get back the REAL write routine */
10335 int i;
10336 int j;
10338 /* Limit individual writes to 32Kb */
10339 i = size;
10340 while (i > 0) {
10341 j = (i > (32*1024)) ? (32*1024) : i;
10342 if (write (fd, buf, j) < 0) return (-1);
10343 /* Account for the data written */
10344 buf += j;
10345 i -= j;
10347 return (size);
10350 /* The following wrapper functions supply additional arguments to the VMS
10351 I/O routines to optimize performance with file handling. The arguments
10352 are:
10353 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10354 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10355 "fop=tef"- Truncate unused portions of file when closing file.
10356 "shr=nil"- Disallow file sharing while file is open.
10359 static FILE *
10360 freopen (fname, type, oldfile)
10361 char *fname;
10362 char *type;
10363 FILE *oldfile;
10365 #undef freopen /* Get back the REAL fopen routine */
10366 if (strcmp (type, "w") == 0)
10367 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10368 return freopen (fname, type, oldfile, "mbc=16");
10371 static FILE *
10372 fopen (fname, type)
10373 char *fname;
10374 char *type;
10376 #undef fopen /* Get back the REAL fopen routine */
10377 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10378 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10379 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10380 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10382 if (*type == 'w')
10383 return (*vmslib_fopen) (fname, type, "mbc=32",
10384 "deq=64", "fop=tef", "shr=nil");
10385 else
10386 return (*vmslib_fopen) (fname, type, "mbc=32");
10389 static int
10390 open (fname, flags, prot)
10391 char *fname;
10392 int flags;
10393 int prot;
10395 #undef open /* Get back the REAL open routine */
10396 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10399 /* Avoid run-time library bug, where copying M out of N+M characters with
10400 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
10401 gcc-cpp exercises this particular bug. [Fixed in V5.5-2's VAXCRTL.] */
10403 static char *
10404 strncat (dst, src, cnt)
10405 char *dst;
10406 const char *src;
10407 unsigned cnt;
10409 register char *d = dst, *s = (char *) src;
10410 register int n = cnt; /* convert to _signed_ type */
10412 while (*d) d++; /* advance to end */
10413 while (--n >= 0)
10414 if (!(*d++ = *s++)) break;
10415 if (n < 0) *d = '\0';
10416 return dst;
10419 /* more VMS hackery */
10420 #include <fab.h>
10421 #include <nam.h>
10423 extern unsigned long sys$parse(), sys$search();
10425 /* Work around another library bug. If a file is located via a searchlist,
10426 and if the device it's on is not the same device as the one specified
10427 in the first element of that searchlist, then both stat() and fstat()
10428 will fail to return info about it. `errno' will be set to EVMSERR, and
10429 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10430 We can get around this by fully parsing the filename and then passing
10431 that absolute name to stat().
10433 Without this fix, we can end up failing to find header files, which is
10434 bad enough, but then compounding the problem by reporting the reason for
10435 failure as "normal successful completion." */
10437 #undef fstat /* get back to library version */
10439 static int
10440 VMS_fstat (fd, statbuf)
10441 int fd;
10442 struct stat *statbuf;
10444 int result = fstat (fd, statbuf);
10446 if (result < 0)
10448 FILE *fp;
10449 char nambuf[NAM$C_MAXRSS+1];
10451 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10452 result = VMS_stat (nambuf, statbuf);
10453 /* No fclose(fp) here; that would close(fd) as well. */
10456 return result;
10459 static int
10460 VMS_stat (name, statbuf)
10461 const char *name;
10462 struct stat *statbuf;
10464 int result = stat (name, statbuf);
10466 if (result < 0)
10468 struct FAB fab;
10469 struct NAM nam;
10470 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for sys$parse */
10471 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for sys$search */
10473 fab = cc$rms_fab;
10474 fab.fab$l_fna = (char *) name;
10475 fab.fab$b_fns = (unsigned char) strlen (name);
10476 fab.fab$l_nam = (void *) &nam;
10477 nam = cc$rms_nam;
10478 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10479 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10480 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10481 if (sys$parse (&fab) & 1)
10483 if (sys$search (&fab) & 1)
10485 res_nam[nam.nam$b_rsl] = '\0';
10486 result = stat (res_nam, statbuf);
10488 /* Clean up searchlist context cached by the system. */
10489 nam.nam$b_nop = NAM$M_SYNCHK;
10490 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10491 (void) sys$parse (&fab);
10495 return result;
10497 #endif /* VMS */