* decl.c (grokdeclarator): Remove const and volatile from type after
[official-gcc.git] / gcc / cccp.c
bloba989bbe814e2bb2bed258543f436810d19ae471a
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-96, 1997 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "config.h"
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <ctype.h>
25 #include <stdio.h>
26 #include <signal.h>
28 #ifdef TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # if HAVE_SYS_TIME_H
33 # include <sys/time.h>
34 # else
35 # include <time.h>
36 #endif
37 #endif
39 #ifdef HAVE_SYS_RESOURCE_H
40 # include <sys/resource.h>
41 #endif
43 #if HAVE_FCNTL_H
44 # include <fcntl.h>
45 #endif
47 #if HAVE_LIMITS_H
48 # include <limits.h>
49 #endif
51 #if HAVE_UNISTD_H
52 # include <unistd.h>
53 #endif
55 #include <errno.h>
57 #if HAVE_STDLIB_H
58 # include <stdlib.h>
59 #endif
61 #ifdef HAVE_STRING_H
62 # include <string.h>
63 #else
64 # ifdef HAVE_STRINGS_H
65 # include <strings.h>
66 #endif
67 #endif
69 typedef unsigned char U_CHAR;
71 #include "gansidecl.h"
72 #include "pcp.h"
74 #ifdef NEED_DECLARATION_INDEX
75 extern char *index ();
76 #endif
78 #ifdef NEED_DECLARATION_RINDEX
79 extern char *rindex ();
80 #endif
82 #ifdef NEED_DECLARATION_GETENV
83 extern char *getenv ();
84 #endif
86 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
87 # define __attribute__(x)
88 #endif
90 #ifndef STANDARD_INCLUDE_DIR
91 # define STANDARD_INCLUDE_DIR "/usr/include"
92 #endif
94 /* By default, colon separates directories in a path. */
95 #ifndef PATH_SEPARATOR
96 # define PATH_SEPARATOR ':'
97 #endif
99 /* By default, the suffix for object files is ".o". */
100 #ifdef OBJECT_SUFFIX
101 # define HAVE_OBJECT_SUFFIX
102 #else
103 # define OBJECT_SUFFIX ".o"
104 #endif
106 #if defined (__STDC__) && defined (HAVE_VPRINTF)
107 # include <stdarg.h>
108 # define PRINTF_ALIST(msg) char *msg, ...
109 # define PRINTF_DCL(msg)
110 # define PRINTF_PROTO(ARGS, m, n) PROTO (ARGS) __attribute__ ((format (__printf__, m, n)))
111 #else
112 # include <varargs.h>
113 # define PRINTF_ALIST(msg) msg, va_alist
114 # define PRINTF_DCL(msg) char *msg; va_dcl
115 # define PRINTF_PROTO(ARGS, m, n) () __attribute__ ((format (__printf__, m, n)))
116 # define vfprintf(file, msg, args) \
118 char *a0 = va_arg(args, char *); \
119 char *a1 = va_arg(args, char *); \
120 char *a2 = va_arg(args, char *); \
121 char *a3 = va_arg(args, char *); \
122 fprintf (file, msg, a0, a1, a2, a3); \
124 #endif
126 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
127 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
128 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
130 /* VMS-specific definitions */
131 #ifdef VMS
132 #include <descrip.h>
133 #include <ssdef.h>
134 #include <syidef.h>
135 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
136 #define fopen(fname,mode) VMS_fopen (fname,mode)
137 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
138 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
139 static int VMS_fstat (), VMS_stat ();
140 static int VMS_open ();
141 static FILE *VMS_fopen ();
142 static FILE *VMS_freopen ();
143 static void hack_vms_include_specification ();
144 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
145 #define INO_T_HASH(a) 0
146 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
147 #endif /* VMS */
149 /* Windows does not natively support inodes, and neither does MSDOS. */
150 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
151 #define INO_T_EQ(a, b) 0
152 #endif
154 #ifndef O_RDONLY
155 #define O_RDONLY 0
156 #endif
158 #undef MIN
159 #undef MAX
160 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
161 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
163 /* Find the largest host integer type and set its size and type.
164 Watch out: on some crazy hosts `long' is shorter than `int'. */
166 #ifndef HOST_WIDE_INT
167 # if HAVE_INTTYPES_H
168 # include <inttypes.h>
169 # define HOST_WIDE_INT intmax_t
170 # else
171 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
172 # define HOST_WIDE_INT int
173 # else
174 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
175 # define HOST_WIDE_INT long
176 # else
177 # define HOST_WIDE_INT long long
178 # endif
179 # endif
180 # endif
181 #endif
183 #ifndef S_ISREG
184 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
185 #endif
187 #ifndef S_ISDIR
188 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
189 #endif
191 #ifndef INO_T_EQ
192 #define INO_T_EQ(a, b) ((a) == (b))
193 #endif
195 #ifndef INO_T_HASH
196 #define INO_T_HASH(a) (a)
197 #endif
199 #ifndef INCLUDE_LEN_FUDGE
200 #define INCLUDE_LEN_FUDGE 0
201 #endif
203 /* External declarations. */
205 extern char *version_string;
206 extern char *update_path PROTO((char *, char *));
207 #ifndef VMS
208 #ifndef HAVE_STRERROR
209 extern int sys_nerr;
210 extern char *sys_errlist[];
211 #else /* HAVE_STRERROR */
212 char *strerror ();
213 #endif
214 #else /* VMS */
215 char *strerror (int,...);
216 #endif
217 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
218 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
220 #ifndef errno
221 extern int errno;
222 #endif
224 /* Name under which this program was invoked. */
226 static char *progname;
228 /* Nonzero means use extra default include directories for C++. */
230 static int cplusplus;
232 /* Nonzero means handle cplusplus style comments */
234 static int cplusplus_comments;
236 /* Nonzero means handle #import, for objective C. */
238 static int objc;
240 /* Nonzero means this is an assembly file, and allow
241 unknown directives, which could be comments. */
243 static int lang_asm;
245 /* Current maximum length of directory names in the search path
246 for include files. (Altered as we get more of them.) */
248 static int max_include_len;
250 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
252 static int for_lint = 0;
254 /* Nonzero means copy comments into the output file. */
256 static int put_out_comments = 0;
258 /* Nonzero means don't process the ANSI trigraph sequences. */
260 static int no_trigraphs = 0;
262 /* Nonzero means print the names of included files rather than
263 the preprocessed output. 1 means just the #include "...",
264 2 means #include <...> as well. */
266 static int print_deps = 0;
268 /* Nonzero if missing .h files in -M output are assumed to be generated
269 files and not errors. */
271 static int print_deps_missing_files = 0;
273 /* Nonzero means print names of header files (-H). */
275 static int print_include_names = 0;
277 /* Nonzero means don't output line number information. */
279 static int no_line_directives;
281 /* Nonzero means output the text in failing conditionals,
282 inside #failed ... #endfailed. */
284 static int output_conditionals;
286 /* dump_only means inhibit output of the preprocessed text
287 and instead output the definitions of all user-defined
288 macros in a form suitable for use as input to cccp.
289 dump_names means pass #define and the macro name through to output.
290 dump_definitions means pass the whole definition (plus #define) through
293 static enum {dump_none, dump_only, dump_names, dump_definitions}
294 dump_macros = dump_none;
296 /* Nonzero means pass all #define and #undef directives which we actually
297 process through to the output stream. This feature is used primarily
298 to allow cc1 to record the #defines and #undefs for the sake of
299 debuggers which understand about preprocessor macros, but it may
300 also be useful with -E to figure out how symbols are defined, and
301 where they are defined. */
302 static int debug_output = 0;
304 /* Nonzero means pass #include lines through to the output,
305 even if they are ifdefed out. */
306 static int dump_includes;
308 /* Nonzero indicates special processing used by the pcp program. The
309 special effects of this mode are:
311 Inhibit all macro expansion, except those inside #if directives.
313 Process #define directives normally, and output their contents
314 to the output file.
316 Output preconditions to pcp_outfile indicating all the relevant
317 preconditions for use of this file in a later cpp run.
319 static FILE *pcp_outfile;
321 /* Nonzero means we are inside an IF during a -pcp run. In this mode
322 macro expansion is done, and preconditions are output for all macro
323 uses requiring them. */
324 static int pcp_inside_if;
326 /* Nonzero means never to include precompiled files.
327 This is 1 since there's no way now to make precompiled files,
328 so it's not worth testing for them. */
329 static int no_precomp = 1;
331 /* Nonzero means give all the error messages the ANSI standard requires. */
333 int pedantic;
335 /* Nonzero means try to make failure to fit ANSI C an error. */
337 static int pedantic_errors;
339 /* Nonzero means don't print warning messages. -w. */
341 static int inhibit_warnings = 0;
343 /* Nonzero means warn if slash-star appears in a slash-star comment,
344 or if newline-backslash appears in a slash-slash comment. */
346 static int warn_comments;
348 /* Nonzero means warn if a macro argument is (or would be)
349 stringified with -traditional. */
351 static int warn_stringify;
353 /* Nonzero means warn if there are any trigraphs. */
355 static int warn_trigraphs;
357 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
359 static int warn_undef;
361 /* Nonzero means warn if #import is used. */
363 static int warn_import = 1;
365 /* Nonzero means turn warnings into errors. */
367 static int warnings_are_errors;
369 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
371 int traditional;
373 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
375 int c89;
377 /* Nonzero causes output not to be done,
378 but directives such as #define that have side effects
379 are still obeyed. */
381 static int no_output;
383 /* Nonzero means we should look for header.gcc files that remap file names. */
384 static int remap;
386 /* Nonzero means this file was included with a -imacros or -include
387 command line and should not be recorded as an include file. */
389 static int no_record_file;
391 /* Nonzero means that we have finished processing the command line options.
392 This flag is used to decide whether or not to issue certain errors
393 and/or warnings. */
395 static int done_initializing = 0;
397 /* Line where a newline was first seen in a string constant. */
399 static int multiline_string_line = 0;
401 /* I/O buffer structure.
402 The `fname' field is nonzero for source files and #include files
403 and for the dummy text used for -D and -U.
404 It is zero for rescanning results of macro expansion
405 and for expanding macro arguments. */
406 #define INPUT_STACK_MAX 400
407 static struct file_buf {
408 char *fname;
409 /* Filename specified with #line directive. */
410 char *nominal_fname;
411 /* Include file description. */
412 struct include_file *inc;
413 /* Record where in the search path this file was found.
414 For #include_next. */
415 struct file_name_list *dir;
416 int lineno;
417 int length;
418 U_CHAR *buf;
419 U_CHAR *bufp;
420 /* Macro that this level is the expansion of.
421 Included so that we can reenable the macro
422 at the end of this level. */
423 struct hashnode *macro;
424 /* Value of if_stack at start of this file.
425 Used to prohibit unmatched #endif (etc) in an include file. */
426 struct if_stack *if_stack;
427 /* Object to be freed at end of input at this level. */
428 U_CHAR *free_ptr;
429 /* True if this is a system header file; see is_system_include. */
430 char system_header_p;
431 } instack[INPUT_STACK_MAX];
433 static int last_error_tick; /* Incremented each time we print it. */
434 static int input_file_stack_tick; /* Incremented when the status changes. */
436 /* Current nesting level of input sources.
437 `instack[indepth]' is the level currently being read. */
438 static int indepth = -1;
439 #define CHECK_DEPTH(code) \
440 if (indepth >= (INPUT_STACK_MAX - 1)) \
442 error_with_line (line_for_error (instack[indepth].lineno), \
443 "macro or `#include' recursion too deep"); \
444 code; \
447 /* Current depth in #include directives that use <...>. */
448 static int system_include_depth = 0;
450 typedef struct file_buf FILE_BUF;
452 /* The output buffer. Its LENGTH field is the amount of room allocated
453 for the buffer, not the number of chars actually present. To get
454 that, subtract outbuf.buf from outbuf.bufp. */
456 #define OUTBUF_SIZE 10 /* initial size of output buffer */
457 static FILE_BUF outbuf;
459 /* Grow output buffer OBUF points at
460 so it can hold at least NEEDED more chars. */
462 #define check_expand(OBUF, NEEDED) \
463 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
464 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
466 struct file_name_list
468 struct file_name_list *next;
469 /* If the following is 1, it is a C-language system include
470 directory. */
471 int c_system_include_path;
472 /* Mapping of file names for this directory. */
473 struct file_name_map *name_map;
474 /* Non-zero if name_map is valid. */
475 int got_name_map;
476 /* The include directory status. */
477 struct stat st;
478 /* The include prefix: "" denotes the working directory,
479 otherwise fname must end in '/'.
480 The actual size is dynamically allocated. */
481 char fname[1];
484 /* #include "file" looks in source file dir, then stack. */
485 /* #include <file> just looks in the stack. */
486 /* -I directories are added to the end, then the defaults are added. */
487 /* The */
488 static struct default_include {
489 char *fname; /* The name of the directory. */
490 char *component; /* The component containing the directory */
491 int cplusplus; /* Only look here if we're compiling C++. */
492 int cxx_aware; /* Includes in this directory don't need to
493 be wrapped in extern "C" when compiling
494 C++. */
495 } include_defaults_array[]
496 #ifdef INCLUDE_DEFAULTS
497 = INCLUDE_DEFAULTS;
498 #else
500 /* Pick up GNU C++ specific include files. */
501 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
502 { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
503 #ifdef CROSS_COMPILE
504 /* This is the dir for fixincludes. Put it just before
505 the files that we fix. */
506 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
507 /* For cross-compilation, this dir name is generated
508 automatically in Makefile.in. */
509 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
510 #ifdef TOOL_INCLUDE_DIR
511 /* This is another place that the target system's headers might be. */
512 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
513 #endif
514 #else /* not CROSS_COMPILE */
515 #ifdef LOCAL_INCLUDE_DIR
516 /* This should be /usr/local/include and should come before
517 the fixincludes-fixed header files. */
518 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
519 #endif
520 #ifdef TOOL_INCLUDE_DIR
521 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
522 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
523 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
524 #endif
525 /* This is the dir for fixincludes. Put it just before
526 the files that we fix. */
527 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
528 /* Some systems have an extra dir of include files. */
529 #ifdef SYSTEM_INCLUDE_DIR
530 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
531 #endif
532 #ifndef STANDARD_INCLUDE_COMPONENT
533 #define STANDARD_INCLUDE_COMPONENT 0
534 #endif
535 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
536 #endif /* not CROSS_COMPILE */
537 { 0, 0, 0, 0 }
539 #endif /* no INCLUDE_DEFAULTS */
541 /* The code looks at the defaults through this pointer, rather than through
542 the constant structure above. This pointer gets changed if an environment
543 variable specifies other defaults. */
544 static struct default_include *include_defaults = include_defaults_array;
546 static struct file_name_list *include = 0; /* First dir to search */
547 /* First dir to search for <file> */
548 /* This is the first element to use for #include <...>.
549 If it is 0, use the entire chain for such includes. */
550 static struct file_name_list *first_bracket_include = 0;
551 /* This is the first element in the chain that corresponds to
552 a directory of system header files. */
553 static struct file_name_list *first_system_include = 0;
554 static struct file_name_list *last_include = 0; /* Last in chain */
556 /* Chain of include directories to put at the end of the other chain. */
557 static struct file_name_list *after_include = 0;
558 static struct file_name_list *last_after_include = 0; /* Last in chain */
560 /* Chain to put at the start of the system include files. */
561 static struct file_name_list *before_system = 0;
562 static struct file_name_list *last_before_system = 0; /* Last in chain */
564 /* Directory prefix that should replace `/usr' in the standard
565 include file directories. */
566 static char *include_prefix;
568 /* Maintain and search list of included files. */
570 struct include_file {
571 struct include_file *next; /* for include_hashtab */
572 struct include_file *next_ino; /* for include_ino_hashtab */
573 char *fname;
574 /* If the following is the empty string, it means #pragma once
575 was seen in this include file, or #import was applied to the file.
576 Otherwise, if it is nonzero, it is a macro name.
577 Don't include the file again if that macro is defined. */
578 U_CHAR *control_macro;
579 /* Nonzero if the dependency on this include file has been output. */
580 int deps_output;
581 struct stat st;
584 /* Hash tables of files already included with #include or #import.
585 include_hashtab is by full name; include_ino_hashtab is by inode number. */
587 #define INCLUDE_HASHSIZE 61
588 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
589 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
591 /* Global list of strings read in from precompiled files. This list
592 is kept in the order the strings are read in, with new strings being
593 added at the end through stringlist_tailp. We use this list to output
594 the strings at the end of the run.
596 static STRINGDEF *stringlist;
597 static STRINGDEF **stringlist_tailp = &stringlist;
600 /* Structure returned by create_definition */
601 typedef struct macrodef MACRODEF;
602 struct macrodef
604 struct definition *defn;
605 U_CHAR *symnam;
606 int symlen;
609 enum sharp_token_type {
610 NO_SHARP_TOKEN = 0, /* token not present */
612 SHARP_TOKEN = '#', /* token spelled with # only */
613 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
615 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
616 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
619 /* Structure allocated for every #define. For a simple replacement
620 such as
621 #define foo bar ,
622 nargs = -1, the `pattern' list is null, and the expansion is just
623 the replacement text. Nargs = 0 means a functionlike macro with no args,
624 e.g.,
625 #define getchar() getc (stdin) .
626 When there are args, the expansion is the replacement text with the
627 args squashed out, and the reflist is a list describing how to
628 build the output from the input: e.g., "3 chars, then the 1st arg,
629 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
630 The chars here come from the expansion. Whatever is left of the
631 expansion after the last arg-occurrence is copied after that arg.
632 Note that the reflist can be arbitrarily long---
633 its length depends on the number of times the arguments appear in
634 the replacement text, not how many args there are. Example:
635 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
636 pattern list
637 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
638 where (x, y) means (nchars, argno). */
640 typedef struct definition DEFINITION;
641 struct definition {
642 int nargs;
643 int length; /* length of expansion string */
644 int predefined; /* True if the macro was builtin or */
645 /* came from the command line */
646 U_CHAR *expansion;
647 int line; /* Line number of definition */
648 char *file; /* File of definition */
649 char rest_args; /* Nonzero if last arg. absorbs the rest */
650 struct reflist {
651 struct reflist *next;
653 enum sharp_token_type stringify; /* set if a # operator before arg */
654 enum sharp_token_type raw_before; /* set if a ## operator before arg */
655 enum sharp_token_type raw_after; /* set if a ## operator after arg */
657 char rest_args; /* Nonzero if this arg. absorbs the rest */
658 int nchars; /* Number of literal chars to copy before
659 this arg occurrence. */
660 int argno; /* Number of arg to substitute (origin-0) */
661 } *pattern;
662 union {
663 /* Names of macro args, concatenated in reverse order
664 with comma-space between them.
665 The only use of this is that we warn on redefinition
666 if this differs between the old and new definitions. */
667 U_CHAR *argnames;
668 } args;
671 /* different kinds of things that can appear in the value field
672 of a hash node. Actually, this may be useless now. */
673 union hashval {
674 char *cpval;
675 DEFINITION *defn;
676 KEYDEF *keydef;
680 * special extension string that can be added to the last macro argument to
681 * allow it to absorb the "rest" of the arguments when expanded. Ex:
682 * #define wow(a, b...) process (b, a, b)
683 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
684 * { wow (one, two); } -> { process (two, one, two); }
685 * if this "rest_arg" is used with the concat token '##' and if it is not
686 * supplied then the token attached to with ## will not be outputted. Ex:
687 * #define wow (a, b...) process (b ## , a, ## b)
688 * { wow (1, 2); } -> { process (2, 1, 2); }
689 * { wow (one); } -> { process (one); {
691 static char rest_extension[] = "...";
692 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
694 /* The structure of a node in the hash table. The hash table
695 has entries for all tokens defined by #define directives (type T_MACRO),
696 plus some special tokens like __LINE__ (these each have their own
697 type, and the appropriate code is run when that type of node is seen.
698 It does not contain control words like "#define", which are recognized
699 by a separate piece of code. */
701 /* different flavors of hash nodes --- also used in keyword table */
702 enum node_type {
703 T_DEFINE = 1, /* the `#define' keyword */
704 T_INCLUDE, /* the `#include' keyword */
705 T_INCLUDE_NEXT, /* the `#include_next' keyword */
706 T_IMPORT, /* the `#import' keyword */
707 T_IFDEF, /* the `#ifdef' keyword */
708 T_IFNDEF, /* the `#ifndef' keyword */
709 T_IF, /* the `#if' keyword */
710 T_ELSE, /* `#else' */
711 T_PRAGMA, /* `#pragma' */
712 T_ELIF, /* `#elif' */
713 T_UNDEF, /* `#undef' */
714 T_LINE, /* `#line' */
715 T_ERROR, /* `#error' */
716 T_WARNING, /* `#warning' */
717 T_ENDIF, /* `#endif' */
718 T_SCCS, /* `#sccs', used on system V. */
719 T_IDENT, /* `#ident', used on system V. */
720 T_ASSERT, /* `#assert', taken from system V. */
721 T_UNASSERT, /* `#unassert', taken from system V. */
722 T_SPECLINE, /* special symbol `__LINE__' */
723 T_DATE, /* `__DATE__' */
724 T_FILE, /* `__FILE__' */
725 T_BASE_FILE, /* `__BASE_FILE__' */
726 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
727 T_VERSION, /* `__VERSION__' */
728 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
729 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
730 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
731 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
732 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
733 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
734 T_TIME, /* `__TIME__' */
735 T_CONST, /* Constant value, used by `__STDC__' */
736 T_MACRO, /* macro defined by `#define' */
737 T_DISABLED, /* macro temporarily turned off for rescan */
738 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
739 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
740 T_UNUSED /* Used for something not defined. */
743 struct hashnode {
744 struct hashnode *next; /* double links for easy deletion */
745 struct hashnode *prev;
746 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
747 chain is kept, in case the node is the head
748 of the chain and gets deleted. */
749 enum node_type type; /* type of special token */
750 int length; /* length of token, for quick comparison */
751 U_CHAR *name; /* the actual name */
752 union hashval value; /* pointer to expansion, or whatever */
755 typedef struct hashnode HASHNODE;
757 /* Some definitions for the hash table. The hash function MUST be
758 computed as shown in hashf () below. That is because the rescan
759 loop computes the hash value `on the fly' for most tokens,
760 in order to avoid the overhead of a lot of procedure calls to
761 the hashf () function. Hashf () only exists for the sake of
762 politeness, for use when speed isn't so important. */
764 #define HASHSIZE 1403
765 static HASHNODE *hashtab[HASHSIZE];
766 #define HASHSTEP(old, c) ((old << 2) + c)
767 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
769 /* Symbols to predefine. */
771 #ifdef CPP_PREDEFINES
772 static char *predefs = CPP_PREDEFINES;
773 #else
774 static char *predefs = "";
775 #endif
777 /* We let tm.h override the types used here, to handle trivial differences
778 such as the choice of unsigned int or long unsigned int for size_t.
779 When machines start needing nontrivial differences in the size type,
780 it would be best to do something here to figure out automatically
781 from other information what type to use. */
783 /* The string value for __SIZE_TYPE__. */
785 #ifndef SIZE_TYPE
786 #define SIZE_TYPE "long unsigned int"
787 #endif
789 /* The string value for __PTRDIFF_TYPE__. */
791 #ifndef PTRDIFF_TYPE
792 #define PTRDIFF_TYPE "long int"
793 #endif
795 /* The string value for __WCHAR_TYPE__. */
797 #ifndef WCHAR_TYPE
798 #define WCHAR_TYPE "int"
799 #endif
800 char * wchar_type = WCHAR_TYPE;
801 #undef WCHAR_TYPE
803 /* The string value for __USER_LABEL_PREFIX__ */
805 #ifndef USER_LABEL_PREFIX
806 #define USER_LABEL_PREFIX ""
807 #endif
809 /* The string value for __REGISTER_PREFIX__ */
811 #ifndef REGISTER_PREFIX
812 #define REGISTER_PREFIX ""
813 #endif
815 /* The string value for __IMMEDIATE_PREFIX__ */
817 #ifndef IMMEDIATE_PREFIX
818 #define IMMEDIATE_PREFIX ""
819 #endif
821 /* In the definition of a #assert name, this structure forms
822 a list of the individual values asserted.
823 Each value is itself a list of "tokens".
824 These are strings that are compared by name. */
826 struct tokenlist_list {
827 struct tokenlist_list *next;
828 struct arglist *tokens;
831 struct assertion_hashnode {
832 struct assertion_hashnode *next; /* double links for easy deletion */
833 struct assertion_hashnode *prev;
834 /* also, a back pointer to this node's hash
835 chain is kept, in case the node is the head
836 of the chain and gets deleted. */
837 struct assertion_hashnode **bucket_hdr;
838 int length; /* length of token, for quick comparison */
839 U_CHAR *name; /* the actual name */
840 /* List of token-sequences. */
841 struct tokenlist_list *value;
844 typedef struct assertion_hashnode ASSERTION_HASHNODE;
846 /* Some definitions for the hash table. The hash function MUST be
847 computed as shown in hashf below. That is because the rescan
848 loop computes the hash value `on the fly' for most tokens,
849 in order to avoid the overhead of a lot of procedure calls to
850 the hashf function. hashf only exists for the sake of
851 politeness, for use when speed isn't so important. */
853 #define ASSERTION_HASHSIZE 37
854 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
856 /* Nonzero means inhibit macroexpansion of what seem to be
857 assertion tests, in rescan. For #if. */
858 static int assertions_flag;
860 /* `struct directive' defines one #-directive, including how to handle it. */
862 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
864 struct directive {
865 int length; /* Length of name */
866 int (*func) DO_PROTO; /* Function to handle directive */
867 char *name; /* Name of directive */
868 enum node_type type; /* Code which describes which directive. */
871 #define IS_INCLUDE_DIRECTIVE_TYPE(t) (T_INCLUDE <= (t) && (t) <= T_IMPORT)
873 /* These functions are declared to return int instead of void since they
874 are going to be placed in the table and some old compilers have trouble with
875 pointers to functions returning void. */
877 static int do_assert DO_PROTO;
878 static int do_define DO_PROTO;
879 static int do_elif DO_PROTO;
880 static int do_else DO_PROTO;
881 static int do_endif DO_PROTO;
882 static int do_error DO_PROTO;
883 static int do_ident DO_PROTO;
884 static int do_if DO_PROTO;
885 static int do_include DO_PROTO;
886 static int do_line DO_PROTO;
887 static int do_pragma DO_PROTO;
888 #ifdef SCCS_DIRECTIVE
889 static int do_sccs DO_PROTO;
890 #endif
891 static int do_unassert DO_PROTO;
892 static int do_undef DO_PROTO;
893 static int do_warning DO_PROTO;
894 static int do_xifdef DO_PROTO;
896 /* Here is the actual list of #-directives, most-often-used first. */
898 static struct directive directive_table[] = {
899 { 6, do_define, "define", T_DEFINE},
900 { 2, do_if, "if", T_IF},
901 { 5, do_xifdef, "ifdef", T_IFDEF},
902 { 6, do_xifdef, "ifndef", T_IFNDEF},
903 { 5, do_endif, "endif", T_ENDIF},
904 { 4, do_else, "else", T_ELSE},
905 { 4, do_elif, "elif", T_ELIF},
906 { 4, do_line, "line", T_LINE},
907 { 7, do_include, "include", T_INCLUDE},
908 { 12, do_include, "include_next", T_INCLUDE_NEXT},
909 { 6, do_include, "import", T_IMPORT},
910 { 5, do_undef, "undef", T_UNDEF},
911 { 5, do_error, "error", T_ERROR},
912 { 7, do_warning, "warning", T_WARNING},
913 #ifdef SCCS_DIRECTIVE
914 { 4, do_sccs, "sccs", T_SCCS},
915 #endif
916 { 6, do_pragma, "pragma", T_PRAGMA},
917 { 5, do_ident, "ident", T_IDENT},
918 { 6, do_assert, "assert", T_ASSERT},
919 { 8, do_unassert, "unassert", T_UNASSERT},
920 { -1, 0, "", T_UNUSED},
923 /* When a directive handler is called,
924 this points to the # (or the : of the %:) that started the directive. */
925 U_CHAR *directive_start;
927 /* table to tell if char can be part of a C identifier. */
928 U_CHAR is_idchar[256];
929 /* table to tell if char can be first char of a c identifier. */
930 U_CHAR is_idstart[256];
931 /* table to tell if c is horizontal space. */
932 static U_CHAR is_hor_space[256];
933 /* table to tell if c is horizontal or vertical space. */
934 U_CHAR is_space[256];
935 /* names of some characters */
936 static char *char_name[256];
938 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
939 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
941 static int errors = 0; /* Error counter for exit code */
943 /* Name of output file, for error messages. */
944 static char *out_fname;
947 /* Stack of conditionals currently in progress
948 (including both successful and failing conditionals). */
950 struct if_stack {
951 struct if_stack *next; /* for chaining to the next stack frame */
952 char *fname; /* copied from input when frame is made */
953 int lineno; /* similarly */
954 int if_succeeded; /* true if a leg of this if-group
955 has been passed through rescan */
956 U_CHAR *control_macro; /* For #ifndef at start of file,
957 this is the macro name tested. */
958 enum node_type type; /* type of last directive seen in this group */
960 typedef struct if_stack IF_STACK_FRAME;
961 static IF_STACK_FRAME *if_stack = NULL;
963 /* Buffer of -M output. */
964 static char *deps_buffer;
966 /* Number of bytes allocated in above. */
967 static int deps_allocated_size;
969 /* Number of bytes used. */
970 static int deps_size;
972 /* Number of bytes since the last newline. */
973 static int deps_column;
975 /* Nonzero means -I- has been seen,
976 so don't look for #include "foo" the source-file directory. */
977 static int ignore_srcdir;
979 static int safe_read PROTO((int, char *, int));
980 static void safe_write PROTO((int, char *, int));
982 int main PROTO((int, char **));
984 static void path_include PROTO((char *));
986 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
988 static void trigraph_pcp PROTO((FILE_BUF *));
990 static void newline_fix PROTO((U_CHAR *));
991 static void name_newline_fix PROTO((U_CHAR *));
993 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
995 static void rescan PROTO((FILE_BUF *, int));
997 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
999 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1001 static struct tm *timestamp PROTO((void));
1002 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1004 static int is_system_include PROTO((char *));
1005 static char *base_name PROTO((char *));
1006 static int absolute_filename PROTO((char *));
1007 static size_t simplify_filename PROTO((char *));
1009 static char *read_filename_string PROTO((int, FILE *));
1010 static struct file_name_map *read_name_map PROTO((char *));
1011 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
1012 static char *remap_include_file PROTO((char *, struct file_name_list *));
1013 static int lookup_ino_include PROTO((struct include_file *));
1015 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
1016 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
1018 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
1019 static int check_preconditions PROTO((char *));
1020 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1021 static void pcstring_used PROTO((HASHNODE *));
1022 static void write_output PROTO((void));
1023 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1025 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1027 static int check_macro_name PROTO((U_CHAR *, char *));
1028 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1029 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1031 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1033 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1034 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1036 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1037 static void free_token_list PROTO((struct arglist *));
1039 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1040 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1041 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1043 static void do_once PROTO((void));
1045 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1046 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1047 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1048 static void validate_else PROTO((U_CHAR *, U_CHAR *));
1050 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1051 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1052 static char *quote_string PROTO((char *, char *));
1053 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1055 /* Last arg to output_line_directive. */
1056 enum file_change_code {same_file, enter_file, leave_file};
1057 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1059 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1061 struct argdata;
1062 static char *macarg PROTO((struct argdata *, int));
1064 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1066 static int discard_comments PROTO((U_CHAR *, int, int));
1068 static int change_newlines PROTO((U_CHAR *, int));
1070 char *my_strerror PROTO((int));
1071 void error PRINTF_PROTO_1((char *, ...));
1072 static void verror PROTO((char *, va_list));
1073 static void error_from_errno PROTO((char *));
1074 void warning PRINTF_PROTO_1((char *, ...));
1075 static void vwarning PROTO((char *, va_list));
1076 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1077 static void verror_with_line PROTO((int, char *, va_list));
1078 static void vwarning_with_line PROTO((int, char *, va_list));
1079 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1080 void pedwarn PRINTF_PROTO_1((char *, ...));
1081 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1082 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1084 static void print_containing_files PROTO((void));
1086 static int line_for_error PROTO((int));
1087 static int grow_outbuf PROTO((FILE_BUF *, int));
1089 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1090 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1091 static void delete_macro PROTO((HASHNODE *));
1092 static int hashf PROTO((U_CHAR *, int, int));
1094 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1095 static void dump_all_macros PROTO((void));
1096 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1097 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1099 static void initialize_char_syntax PROTO((void));
1100 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1102 static void make_definition PROTO((char *, FILE_BUF *));
1103 static void make_undef PROTO((char *, FILE_BUF *));
1105 static void make_assertion PROTO((char *, char *));
1107 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1108 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1110 static int quote_string_for_make PROTO((char *, char *));
1111 static void deps_output PROTO((char *, int));
1113 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1114 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1115 static void perror_with_name PROTO((char *));
1116 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1117 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1119 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1120 GENERIC_PTR xmalloc PROTO((size_t));
1121 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1122 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1123 static char *savestring PROTO((char *));
1125 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1126 retrying if necessary. If MAX_READ_LEN is defined, read at most
1127 that bytes at a time. Return a negative value if an error occurs,
1128 otherwise return the actual number of bytes read,
1129 which must be LEN unless end-of-file was reached. */
1131 static int
1132 safe_read (desc, ptr, len)
1133 int desc;
1134 char *ptr;
1135 int len;
1137 int left, rcount, nchars;
1139 left = len;
1140 while (left > 0) {
1141 rcount = left;
1142 #ifdef MAX_READ_LEN
1143 if (rcount > MAX_READ_LEN)
1144 rcount = MAX_READ_LEN;
1145 #endif
1146 nchars = read (desc, ptr, rcount);
1147 if (nchars < 0)
1149 #ifdef EINTR
1150 if (errno == EINTR)
1151 continue;
1152 #endif
1153 return nchars;
1155 if (nchars == 0)
1156 break;
1157 ptr += nchars;
1158 left -= nchars;
1160 return len - left;
1163 /* Write LEN bytes at PTR to descriptor DESC,
1164 retrying if necessary, and treating any real error as fatal.
1165 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1167 static void
1168 safe_write (desc, ptr, len)
1169 int desc;
1170 char *ptr;
1171 int len;
1173 int wcount, written;
1175 while (len > 0) {
1176 wcount = len;
1177 #ifdef MAX_WRITE_LEN
1178 if (wcount > MAX_WRITE_LEN)
1179 wcount = MAX_WRITE_LEN;
1180 #endif
1181 written = write (desc, ptr, wcount);
1182 if (written < 0)
1184 #ifdef EINTR
1185 if (errno == EINTR)
1186 continue;
1187 #endif
1188 pfatal_with_name (out_fname);
1190 ptr += written;
1191 len -= written;
1196 main (argc, argv)
1197 int argc;
1198 char **argv;
1200 struct stat st;
1201 char *in_fname;
1202 char *cp;
1203 int f, i;
1204 FILE_BUF *fp;
1205 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1206 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1207 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1208 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1209 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1211 /* Record the option used with each element of pend_assertions.
1212 This is preparation for supporting more than one option for making
1213 an assertion. */
1214 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1215 int inhibit_predefs = 0;
1216 int no_standard_includes = 0;
1217 int no_standard_cplusplus_includes = 0;
1218 int missing_newline = 0;
1220 /* Non-0 means don't output the preprocessed program. */
1221 int inhibit_output = 0;
1222 /* Non-0 means -v, so print the full set of include dirs. */
1223 int verbose = 0;
1225 /* File name which deps are being written to.
1226 This is 0 if deps are being written to stdout. */
1227 char *deps_file = 0;
1228 /* Fopen file mode to open deps_file with. */
1229 char *deps_mode = "a";
1230 /* Stream on which to print the dependency information. */
1231 FILE *deps_stream = 0;
1232 /* Target-name to write with the dependency information. */
1233 char *deps_target = 0;
1235 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1236 /* Get rid of any avoidable limit on stack size. */
1238 struct rlimit rlim;
1240 /* Set the stack limit huge so that alloca (particularly stringtab
1241 in dbxread.c) does not fail. */
1242 getrlimit (RLIMIT_STACK, &rlim);
1243 rlim.rlim_cur = rlim.rlim_max;
1244 setrlimit (RLIMIT_STACK, &rlim);
1246 #endif
1248 #ifdef SIGPIPE
1249 signal (SIGPIPE, pipe_closed);
1250 #endif
1252 progname = base_name (argv[0]);
1254 #ifdef VMS
1256 /* Remove extension from PROGNAME. */
1257 char *p;
1258 char *s = progname = savestring (progname);
1260 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1261 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1262 && (p[1] == 'e' || p[1] == 'E')
1263 && (p[2] == 'x' || p[2] == 'X')
1264 && (p[3] == 'e' || p[3] == 'E')
1265 && !p[4])
1266 *p = '\0';
1268 #endif
1270 in_fname = NULL;
1271 out_fname = NULL;
1273 /* Initialize is_idchar. */
1274 initialize_char_syntax ();
1276 no_line_directives = 0;
1277 no_trigraphs = 1;
1278 dump_macros = dump_none;
1279 no_output = 0;
1280 cplusplus = 0;
1281 cplusplus_comments = 1;
1283 bzero ((char *) pend_files, argc * sizeof (char *));
1284 bzero ((char *) pend_defs, argc * sizeof (char *));
1285 bzero ((char *) pend_undefs, argc * sizeof (char *));
1286 bzero ((char *) pend_assertions, argc * sizeof (char *));
1287 bzero ((char *) pend_includes, argc * sizeof (char *));
1289 /* Process switches and find input file name. */
1291 for (i = 1; i < argc; i++) {
1292 if (argv[i][0] != '-') {
1293 if (out_fname != NULL)
1294 fatal ("Usage: %s [switches] input output", argv[0]);
1295 else if (in_fname != NULL)
1296 out_fname = argv[i];
1297 else
1298 in_fname = argv[i];
1299 } else {
1300 switch (argv[i][1]) {
1302 case 'i':
1303 if (!strcmp (argv[i], "-include")) {
1304 int temp = i;
1306 if (i + 1 == argc)
1307 fatal ("Filename missing after `-include' option");
1308 else
1309 simplify_filename (pend_includes[temp] = argv[++i]);
1311 if (!strcmp (argv[i], "-imacros")) {
1312 int temp = i;
1314 if (i + 1 == argc)
1315 fatal ("Filename missing after `-imacros' option");
1316 else
1317 simplify_filename (pend_files[temp] = argv[++i]);
1319 if (!strcmp (argv[i], "-iprefix")) {
1320 if (i + 1 == argc)
1321 fatal ("Filename missing after `-iprefix' option");
1322 else
1323 include_prefix = argv[++i];
1325 if (!strcmp (argv[i], "-ifoutput")) {
1326 output_conditionals = 1;
1328 if (!strcmp (argv[i], "-isystem")) {
1329 struct file_name_list *dirtmp;
1331 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1332 "", argv[++i])))
1333 break;
1334 dirtmp->c_system_include_path = 1;
1336 if (before_system == 0)
1337 before_system = dirtmp;
1338 else
1339 last_before_system->next = dirtmp;
1340 last_before_system = dirtmp; /* Tail follows the last one */
1342 /* Add directory to end of path for includes,
1343 with the default prefix at the front of its name. */
1344 if (!strcmp (argv[i], "-iwithprefix")) {
1345 struct file_name_list *dirtmp;
1346 char *prefix;
1348 if (include_prefix != 0)
1349 prefix = include_prefix;
1350 else {
1351 prefix = savestring (GCC_INCLUDE_DIR);
1352 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1353 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1354 prefix[strlen (prefix) - 7] = 0;
1357 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1358 prefix, argv[++i])))
1359 break;
1361 if (after_include == 0)
1362 after_include = dirtmp;
1363 else
1364 last_after_include->next = dirtmp;
1365 last_after_include = dirtmp; /* Tail follows the last one */
1367 /* Add directory to main path for includes,
1368 with the default prefix at the front of its name. */
1369 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1370 struct file_name_list *dirtmp;
1371 char *prefix;
1373 if (include_prefix != 0)
1374 prefix = include_prefix;
1375 else {
1376 prefix = savestring (GCC_INCLUDE_DIR);
1377 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1378 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1379 prefix[strlen (prefix) - 7] = 0;
1382 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1383 append_include_chain (dirtmp, dirtmp);
1385 /* Add directory to end of path for includes. */
1386 if (!strcmp (argv[i], "-idirafter")) {
1387 struct file_name_list *dirtmp;
1389 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1390 "", argv[++i])))
1391 break;
1393 if (after_include == 0)
1394 after_include = dirtmp;
1395 else
1396 last_after_include->next = dirtmp;
1397 last_after_include = dirtmp; /* Tail follows the last one */
1399 break;
1401 case 'o':
1402 if (out_fname != NULL)
1403 fatal ("Output filename specified twice");
1404 if (i + 1 == argc)
1405 fatal ("Filename missing after -o option");
1406 out_fname = argv[++i];
1407 if (!strcmp (out_fname, "-"))
1408 out_fname = "";
1409 break;
1411 case 'p':
1412 if (!strcmp (argv[i], "-pedantic"))
1413 pedantic = 1;
1414 else if (!strcmp (argv[i], "-pedantic-errors")) {
1415 pedantic = 1;
1416 pedantic_errors = 1;
1417 } else if (!strcmp (argv[i], "-pcp")) {
1418 char *pcp_fname;
1419 if (i + 1 == argc)
1420 fatal ("Filename missing after -pcp option");
1421 pcp_fname = argv[++i];
1422 pcp_outfile
1423 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1424 ? fopen (pcp_fname, "w")
1425 : stdout);
1426 if (pcp_outfile == 0)
1427 pfatal_with_name (pcp_fname);
1428 no_precomp = 1;
1430 break;
1432 case 't':
1433 if (!strcmp (argv[i], "-traditional")) {
1434 traditional = 1;
1435 cplusplus_comments = 0;
1436 } else if (!strcmp (argv[i], "-trigraphs")) {
1437 no_trigraphs = 0;
1439 break;
1441 case 'l':
1442 if (! strcmp (argv[i], "-lang-c"))
1443 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1444 if (! strcmp (argv[i], "-lang-c89"))
1445 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1446 if (! strcmp (argv[i], "-lang-c++"))
1447 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1448 if (! strcmp (argv[i], "-lang-objc"))
1449 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1450 if (! strcmp (argv[i], "-lang-objc++"))
1451 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1452 if (! strcmp (argv[i], "-lang-asm"))
1453 lang_asm = 1;
1454 if (! strcmp (argv[i], "-lint"))
1455 for_lint = 1;
1456 break;
1458 case '+':
1459 cplusplus = 1, cplusplus_comments = 1;
1460 break;
1462 case 'w':
1463 inhibit_warnings = 1;
1464 break;
1466 case 'W':
1467 if (!strcmp (argv[i], "-Wtrigraphs"))
1468 warn_trigraphs = 1;
1469 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1470 warn_trigraphs = 0;
1471 else if (!strcmp (argv[i], "-Wcomment"))
1472 warn_comments = 1;
1473 else if (!strcmp (argv[i], "-Wno-comment"))
1474 warn_comments = 0;
1475 else if (!strcmp (argv[i], "-Wcomments"))
1476 warn_comments = 1;
1477 else if (!strcmp (argv[i], "-Wno-comments"))
1478 warn_comments = 0;
1479 else if (!strcmp (argv[i], "-Wtraditional"))
1480 warn_stringify = 1;
1481 else if (!strcmp (argv[i], "-Wno-traditional"))
1482 warn_stringify = 0;
1483 else if (!strcmp (argv[i], "-Wundef"))
1484 warn_undef = 1;
1485 else if (!strcmp (argv[i], "-Wno-undef"))
1486 warn_undef = 0;
1487 else if (!strcmp (argv[i], "-Wimport"))
1488 warn_import = 1;
1489 else if (!strcmp (argv[i], "-Wno-import"))
1490 warn_import = 0;
1491 else if (!strcmp (argv[i], "-Werror"))
1492 warnings_are_errors = 1;
1493 else if (!strcmp (argv[i], "-Wno-error"))
1494 warnings_are_errors = 0;
1495 else if (!strcmp (argv[i], "-Wall"))
1497 warn_trigraphs = 1;
1498 warn_comments = 1;
1500 break;
1502 case 'M':
1503 /* The style of the choices here is a bit mixed.
1504 The chosen scheme is a hybrid of keeping all options in one string
1505 and specifying each option in a separate argument:
1506 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1507 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1508 -M[M][G][D file]. This is awkward to handle in specs, and is not
1509 as extensible. */
1510 /* ??? -MG must be specified in addition to one of -M or -MM.
1511 This can be relaxed in the future without breaking anything.
1512 The converse isn't true. */
1514 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1515 if (!strcmp (argv[i], "-MG"))
1517 print_deps_missing_files = 1;
1518 break;
1520 if (!strcmp (argv[i], "-M"))
1521 print_deps = 2;
1522 else if (!strcmp (argv[i], "-MM"))
1523 print_deps = 1;
1524 else if (!strcmp (argv[i], "-MD"))
1525 print_deps = 2;
1526 else if (!strcmp (argv[i], "-MMD"))
1527 print_deps = 1;
1528 /* For -MD and -MMD options, write deps on file named by next arg. */
1529 if (!strcmp (argv[i], "-MD")
1530 || !strcmp (argv[i], "-MMD")) {
1531 if (i + 1 == argc)
1532 fatal ("Filename missing after %s option", argv[i]);
1533 i++;
1534 deps_file = argv[i];
1535 deps_mode = "w";
1536 } else {
1537 /* For -M and -MM, write deps on standard output
1538 and suppress the usual output. */
1539 deps_stream = stdout;
1540 inhibit_output = 1;
1542 break;
1544 case 'd':
1546 char *p = argv[i] + 2;
1547 char c;
1548 while ((c = *p++)) {
1549 /* Arg to -d specifies what parts of macros to dump */
1550 switch (c) {
1551 case 'M':
1552 dump_macros = dump_only;
1553 no_output = 1;
1554 break;
1555 case 'N':
1556 dump_macros = dump_names;
1557 break;
1558 case 'D':
1559 dump_macros = dump_definitions;
1560 break;
1561 case 'I':
1562 dump_includes = 1;
1563 break;
1567 break;
1569 case 'g':
1570 if (argv[i][2] == '3')
1571 debug_output = 1;
1572 break;
1574 case 'v':
1575 fprintf (stderr, "GNU CPP version %s", version_string);
1576 #ifdef TARGET_VERSION
1577 TARGET_VERSION;
1578 #endif
1579 fprintf (stderr, "\n");
1580 verbose = 1;
1581 break;
1583 case 'H':
1584 print_include_names = 1;
1585 break;
1587 case 'D':
1588 if (argv[i][2] != 0)
1589 pend_defs[i] = argv[i] + 2;
1590 else if (i + 1 == argc)
1591 fatal ("Macro name missing after -D option");
1592 else
1593 i++, pend_defs[i] = argv[i];
1594 break;
1596 case 'A':
1598 char *p;
1600 if (argv[i][2] != 0)
1601 p = argv[i] + 2;
1602 else if (i + 1 == argc)
1603 fatal ("Assertion missing after -A option");
1604 else
1605 p = argv[++i];
1607 if (!strcmp (p, "-")) {
1608 /* -A- eliminates all predefined macros and assertions.
1609 Let's include also any that were specified earlier
1610 on the command line. That way we can get rid of any
1611 that were passed automatically in from GCC. */
1612 int j;
1613 inhibit_predefs = 1;
1614 for (j = 0; j < i; j++)
1615 pend_defs[j] = pend_assertions[j] = 0;
1616 } else {
1617 pend_assertions[i] = p;
1618 pend_assertion_options[i] = "-A";
1621 break;
1623 case 'U': /* JF #undef something */
1624 if (argv[i][2] != 0)
1625 pend_undefs[i] = argv[i] + 2;
1626 else if (i + 1 == argc)
1627 fatal ("Macro name missing after -U option");
1628 else
1629 pend_undefs[i] = argv[i+1], i++;
1630 break;
1632 case 'C':
1633 put_out_comments = 1;
1634 break;
1636 case 'E': /* -E comes from cc -E; ignore it. */
1637 break;
1639 case 'P':
1640 no_line_directives = 1;
1641 break;
1643 case '$': /* Don't include $ in identifiers. */
1644 is_idchar['$'] = is_idstart['$'] = 0;
1645 break;
1647 case 'I': /* Add directory to path for includes. */
1649 struct file_name_list *dirtmp;
1651 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1652 ignore_srcdir = 1;
1653 /* Don't use any preceding -I directories for #include <...>. */
1654 first_bracket_include = 0;
1656 else {
1657 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1658 argv[i][2] ? argv[i] + 2 : argv[++i]);
1659 append_include_chain (dirtmp, dirtmp);
1662 break;
1664 case 'n':
1665 if (!strcmp (argv[i], "-nostdinc"))
1666 /* -nostdinc causes no default include directories.
1667 You must specify all include-file directories with -I. */
1668 no_standard_includes = 1;
1669 else if (!strcmp (argv[i], "-nostdinc++"))
1670 /* -nostdinc++ causes no default C++-specific include directories. */
1671 no_standard_cplusplus_includes = 1;
1672 else if (!strcmp (argv[i], "-noprecomp"))
1673 no_precomp = 1;
1674 break;
1676 case 'r':
1677 if (!strcmp (argv[i], "-remap"))
1678 remap = 1;
1679 break;
1681 case 'u':
1682 /* Sun compiler passes undocumented switch "-undef".
1683 Let's assume it means to inhibit the predefined symbols. */
1684 inhibit_predefs = 1;
1685 break;
1687 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1688 if (in_fname == NULL) {
1689 in_fname = "";
1690 break;
1691 } else if (out_fname == NULL) {
1692 out_fname = "";
1693 break;
1694 } /* else fall through into error */
1696 default:
1697 fatal ("Invalid option `%s'", argv[i]);
1702 /* Add dirs from CPATH after dirs from -I. */
1703 /* There seems to be confusion about what CPATH should do,
1704 so for the moment it is not documented. */
1705 /* Some people say that CPATH should replace the standard include dirs,
1706 but that seems pointless: it comes before them, so it overrides them
1707 anyway. */
1708 cp = getenv ("CPATH");
1709 if (cp && ! no_standard_includes)
1710 path_include (cp);
1712 /* Initialize output buffer */
1714 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1715 outbuf.bufp = outbuf.buf;
1716 outbuf.length = OUTBUF_SIZE;
1718 /* Do partial setup of input buffer for the sake of generating
1719 early #line directives (when -g is in effect). */
1721 fp = &instack[++indepth];
1722 if (in_fname == NULL)
1723 in_fname = "";
1724 fp->nominal_fname = fp->fname = in_fname;
1725 fp->lineno = 0;
1727 /* In C++, wchar_t is a distinct basic type, and we can expect
1728 __wchar_t to be defined by cc1plus. */
1729 if (cplusplus)
1730 wchar_type = "__wchar_t";
1732 /* Install __LINE__, etc. Must follow initialize_char_syntax
1733 and option processing. */
1734 initialize_builtins (fp, &outbuf);
1736 /* Do standard #defines and assertions
1737 that identify system and machine type. */
1739 if (!inhibit_predefs) {
1740 char *p = (char *) alloca (strlen (predefs) + 1);
1742 #ifdef VMS
1743 struct dsc$descriptor_s lcl_name;
1744 struct item_list {
1745 unsigned short length; /* input length */
1746 unsigned short code; /* item code */
1747 unsigned long dptr; /* data ptr */
1748 unsigned long lptr; /* output length ptr */
1751 unsigned long syi_length;
1752 char syi_data[16];
1754 struct item_list items[] = {
1755 { 16, SYI$_VERSION, 0, 0 },
1756 { 0, 0, 0, 0 }
1759 items[0].dptr = (unsigned long)syi_data;
1760 items[0].lptr = (unsigned long)(&syi_length);
1762 if (SYS$GETSYIW (0, 0, 0, items, NULL, NULL, NULL, NULL) == SS$_NORMAL)
1764 unsigned long vms_version_value;
1765 char *vers;
1767 vers = syi_data;
1768 vms_version_value = 0;
1770 if (*vers == 'V')
1771 vers++;
1772 if (isdigit (*vers))
1774 vms_version_value = (*vers - '0') * 10000000;
1776 vers++;
1777 if (*vers == '.')
1779 vers++;
1780 if (isdigit (*vers))
1782 vms_version_value += (*vers - '0') * 100000;
1786 if (vms_version_value > 0)
1788 char versbuf[32];
1790 sprintf (versbuf, "__VMS_VER=%08ld", vms_version_value);
1791 if (debug_output)
1792 output_line_directive (fp, &outbuf, 0, same_file);
1793 make_definition (versbuf, &outbuf);
1796 #endif
1798 strcpy (p, predefs);
1799 while (*p) {
1800 char *q;
1801 while (*p == ' ' || *p == '\t')
1802 p++;
1803 /* Handle -D options. */
1804 if (p[0] == '-' && p[1] == 'D') {
1805 q = &p[2];
1806 while (*p && *p != ' ' && *p != '\t')
1807 p++;
1808 if (*p != 0)
1809 *p++= 0;
1810 if (debug_output)
1811 output_line_directive (fp, &outbuf, 0, same_file);
1812 make_definition (q, &outbuf);
1813 while (*p == ' ' || *p == '\t')
1814 p++;
1815 } else if (p[0] == '-' && p[1] == 'A') {
1816 /* Handle -A options (assertions). */
1817 char *assertion;
1818 char *past_name;
1819 char *value;
1820 char *past_value;
1821 char *termination;
1822 int save_char;
1824 assertion = &p[2];
1825 past_name = assertion;
1826 /* Locate end of name. */
1827 while (*past_name && *past_name != ' '
1828 && *past_name != '\t' && *past_name != '(')
1829 past_name++;
1830 /* Locate `(' at start of value. */
1831 value = past_name;
1832 while (*value && (*value == ' ' || *value == '\t'))
1833 value++;
1834 if (*value++ != '(')
1835 abort ();
1836 while (*value && (*value == ' ' || *value == '\t'))
1837 value++;
1838 past_value = value;
1839 /* Locate end of value. */
1840 while (*past_value && *past_value != ' '
1841 && *past_value != '\t' && *past_value != ')')
1842 past_value++;
1843 termination = past_value;
1844 while (*termination && (*termination == ' ' || *termination == '\t'))
1845 termination++;
1846 if (*termination++ != ')')
1847 abort ();
1848 if (*termination && *termination != ' ' && *termination != '\t')
1849 abort ();
1850 /* Temporarily null-terminate the value. */
1851 save_char = *termination;
1852 *termination = '\0';
1853 /* Install the assertion. */
1854 make_assertion ("-A", assertion);
1855 *termination = (char) save_char;
1856 p = termination;
1857 while (*p == ' ' || *p == '\t')
1858 p++;
1859 } else {
1860 abort ();
1865 /* Now handle the command line options. */
1867 /* Do -U's, -D's and -A's in the order they were seen. */
1868 for (i = 1; i < argc; i++) {
1869 if (pend_undefs[i]) {
1870 if (debug_output)
1871 output_line_directive (fp, &outbuf, 0, same_file);
1872 make_undef (pend_undefs[i], &outbuf);
1874 if (pend_defs[i]) {
1875 if (debug_output)
1876 output_line_directive (fp, &outbuf, 0, same_file);
1877 make_definition (pend_defs[i], &outbuf);
1879 if (pend_assertions[i])
1880 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1883 done_initializing = 1;
1885 { /* Read the appropriate environment variable and if it exists
1886 replace include_defaults with the listed path. */
1887 char *epath = 0;
1888 switch ((objc << 1) + cplusplus)
1890 case 0:
1891 epath = getenv ("C_INCLUDE_PATH");
1892 break;
1893 case 1:
1894 epath = getenv ("CPLUS_INCLUDE_PATH");
1895 break;
1896 case 2:
1897 epath = getenv ("OBJC_INCLUDE_PATH");
1898 break;
1899 case 3:
1900 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1901 break;
1903 /* If the environment var for this language is set,
1904 add to the default list of include directories. */
1905 if (epath) {
1906 int num_dirs;
1907 char *startp, *endp;
1909 for (num_dirs = 1, startp = epath; *startp; startp++)
1910 if (*startp == PATH_SEPARATOR)
1911 num_dirs++;
1912 include_defaults
1913 = (struct default_include *) xmalloc ((num_dirs
1914 * sizeof (struct default_include))
1915 + sizeof (include_defaults_array));
1916 startp = endp = epath;
1917 num_dirs = 0;
1918 while (1) {
1919 char c = *endp++;
1920 if (c == PATH_SEPARATOR || !c) {
1921 endp[-1] = 0;
1922 include_defaults[num_dirs].fname
1923 = startp == endp ? "." : savestring (startp);
1924 endp[-1] = c;
1925 include_defaults[num_dirs].component = 0;
1926 include_defaults[num_dirs].cplusplus = cplusplus;
1927 include_defaults[num_dirs].cxx_aware = 1;
1928 num_dirs++;
1929 if (!c)
1930 break;
1931 startp = endp;
1934 /* Put the usual defaults back in at the end. */
1935 bcopy ((char *) include_defaults_array,
1936 (char *) &include_defaults[num_dirs],
1937 sizeof (include_defaults_array));
1941 append_include_chain (before_system, last_before_system);
1942 first_system_include = before_system;
1944 /* Unless -fnostdinc,
1945 tack on the standard include file dirs to the specified list */
1946 if (!no_standard_includes) {
1947 struct default_include *p = include_defaults;
1948 char *specd_prefix = include_prefix;
1949 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1950 int default_len = 0;
1951 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1952 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1953 default_len = strlen (default_prefix) - 7;
1954 default_prefix[default_len] = 0;
1956 /* Search "translated" versions of GNU directories.
1957 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1958 if (specd_prefix != 0 && default_len != 0)
1959 for (p = include_defaults; p->fname; p++) {
1960 /* Some standard dirs are only for C++. */
1961 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1962 /* Does this dir start with the prefix? */
1963 if (!strncmp (p->fname, default_prefix, default_len)) {
1964 /* Yes; change prefix and add to search list. */
1965 struct file_name_list *new
1966 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1967 p->fname + default_len);
1968 if (new) {
1969 new->c_system_include_path = !p->cxx_aware;
1970 append_include_chain (new, new);
1971 if (first_system_include == 0)
1972 first_system_include = new;
1977 /* Search ordinary names for GNU include directories. */
1978 for (p = include_defaults; p->fname; p++) {
1979 /* Some standard dirs are only for C++. */
1980 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1981 struct file_name_list *new
1982 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1983 if (new) {
1984 new->c_system_include_path = !p->cxx_aware;
1985 append_include_chain (new, new);
1986 if (first_system_include == 0)
1987 first_system_include = new;
1993 /* Tack the after_include chain at the end of the include chain. */
1994 append_include_chain (after_include, last_after_include);
1995 if (first_system_include == 0)
1996 first_system_include = after_include;
1998 /* With -v, print the list of dirs to search. */
1999 if (verbose) {
2000 struct file_name_list *p;
2001 fprintf (stderr, "#include \"...\" search starts here:\n");
2002 for (p = include; p; p = p->next) {
2003 if (p == first_bracket_include)
2004 fprintf (stderr, "#include <...> search starts here:\n");
2005 if (!p->fname[0])
2006 fprintf (stderr, " .\n");
2007 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
2008 fprintf (stderr, " %s\n", p->fname);
2009 else
2010 /* Omit trailing '/'. */
2011 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
2013 fprintf (stderr, "End of search list.\n");
2016 /* -MG doesn't select the form of output and must be specified with one of
2017 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2018 inhibit compilation. */
2019 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2020 fatal ("-MG must be specified with one of -M or -MM");
2022 /* Either of two environment variables can specify output of deps.
2023 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2024 where OUTPUT_FILE is the file to write deps info to
2025 and DEPS_TARGET is the target to mention in the deps. */
2027 if (print_deps == 0
2028 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2029 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2030 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2031 char *s;
2032 char *output_file;
2034 if (spec == 0) {
2035 spec = getenv ("SUNPRO_DEPENDENCIES");
2036 print_deps = 2;
2038 else
2039 print_deps = 1;
2041 s = spec;
2042 /* Find the space before the DEPS_TARGET, if there is one. */
2043 /* This should use index. (mrs) */
2044 while (*s != 0 && *s != ' ') s++;
2045 if (*s != 0) {
2046 deps_target = s + 1;
2047 output_file = xmalloc (s - spec + 1);
2048 bcopy (spec, output_file, s - spec);
2049 output_file[s - spec] = 0;
2051 else {
2052 deps_target = 0;
2053 output_file = spec;
2056 deps_file = output_file;
2057 deps_mode = "a";
2060 /* For -M, print the expected object file name
2061 as the target of this Make-rule. */
2062 if (print_deps) {
2063 deps_allocated_size = 200;
2064 deps_buffer = xmalloc (deps_allocated_size);
2065 deps_buffer[0] = 0;
2066 deps_size = 0;
2067 deps_column = 0;
2069 if (deps_target) {
2070 deps_output (deps_target, ':');
2071 } else if (*in_fname == 0) {
2072 deps_output ("-", ':');
2073 } else {
2074 char *p, *q;
2075 int len;
2077 q = base_name (in_fname);
2079 /* Copy remainder to mungable area. */
2080 p = (char *) alloca (strlen(q) + 8);
2081 strcpy (p, q);
2083 /* Output P, but remove known suffixes. */
2084 len = strlen (p);
2085 q = p + len;
2086 if (len >= 2
2087 && p[len - 2] == '.'
2088 && index("cCsSm", p[len - 1]))
2089 q = p + (len - 2);
2090 else if (len >= 3
2091 && p[len - 3] == '.'
2092 && p[len - 2] == 'c'
2093 && p[len - 1] == 'c')
2094 q = p + (len - 3);
2095 else if (len >= 4
2096 && p[len - 4] == '.'
2097 && p[len - 3] == 'c'
2098 && p[len - 2] == 'x'
2099 && p[len - 1] == 'x')
2100 q = p + (len - 4);
2101 else if (len >= 4
2102 && p[len - 4] == '.'
2103 && p[len - 3] == 'c'
2104 && p[len - 2] == 'p'
2105 && p[len - 1] == 'p')
2106 q = p + (len - 4);
2108 /* Supply our own suffix. */
2109 strcpy (q, OBJECT_SUFFIX);
2111 deps_output (p, ':');
2112 deps_output (in_fname, ' ');
2116 /* Scan the -imacros files before the main input.
2117 Much like #including them, but with no_output set
2118 so that only their macro definitions matter. */
2120 no_output++; no_record_file++;
2121 for (i = 1; i < argc; i++)
2122 if (pend_files[i]) {
2123 struct include_file *inc;
2124 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2125 if (fd < 0) {
2126 perror_with_name (pend_files[i]);
2127 return FATAL_EXIT_CODE;
2129 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2131 no_output--; no_record_file--;
2133 /* Copy the entire contents of the main input file into
2134 the stacked input buffer previously allocated for it. */
2136 /* JF check for stdin */
2137 if (in_fname == NULL || *in_fname == 0) {
2138 in_fname = "";
2139 f = 0;
2140 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2141 goto perror;
2143 if (fstat (f, &st) != 0)
2144 pfatal_with_name (in_fname);
2145 fp->nominal_fname = fp->fname = in_fname;
2146 fp->lineno = 1;
2147 fp->system_header_p = 0;
2148 /* JF all this is mine about reading pipes and ttys */
2149 if (! S_ISREG (st.st_mode)) {
2150 /* Read input from a file that is not a normal disk file.
2151 We cannot preallocate a buffer with the correct size,
2152 so we must read in the file a piece at the time and make it bigger. */
2153 int size;
2154 int bsize;
2155 int cnt;
2157 if (S_ISDIR (st.st_mode))
2158 fatal ("Input file `%s' is a directory", in_fname);
2160 bsize = 2000;
2161 size = 0;
2162 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2163 for (;;) {
2164 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2165 if (cnt < 0) goto perror; /* error! */
2166 size += cnt;
2167 if (size != bsize) break; /* End of file */
2168 bsize *= 2;
2169 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2171 fp->length = size;
2172 } else {
2173 /* Read a file whose size we can determine in advance.
2174 For the sake of VMS, st.st_size is just an upper bound. */
2175 size_t s = (size_t) st.st_size;
2176 if (s != st.st_size || s + 2 < s)
2177 memory_full ();
2178 fp->buf = (U_CHAR *) xmalloc (s + 2);
2179 fp->length = safe_read (f, (char *) fp->buf, s);
2180 if (fp->length < 0) goto perror;
2182 fp->bufp = fp->buf;
2183 fp->if_stack = if_stack;
2185 /* Make sure data ends with a newline. And put a null after it. */
2187 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2188 /* Backslash-newline at end is not good enough. */
2189 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2190 fp->buf[fp->length++] = '\n';
2191 missing_newline = 1;
2193 fp->buf[fp->length] = '\0';
2195 /* Unless inhibited, convert trigraphs in the input. */
2197 if (!no_trigraphs)
2198 trigraph_pcp (fp);
2200 /* Now that we know the input file is valid, open the output. */
2202 if (!out_fname || !strcmp (out_fname, ""))
2203 out_fname = "stdout";
2204 else if (! freopen (out_fname, "w", stdout))
2205 pfatal_with_name (out_fname);
2207 output_line_directive (fp, &outbuf, 0, same_file);
2209 /* Scan the -include files before the main input. */
2211 no_record_file++;
2212 for (i = 1; i < argc; i++)
2213 if (pend_includes[i]) {
2214 struct include_file *inc;
2215 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2216 if (fd < 0) {
2217 perror_with_name (pend_includes[i]);
2218 return FATAL_EXIT_CODE;
2220 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2222 no_record_file--;
2224 /* Scan the input, processing macros and directives. */
2226 rescan (&outbuf, 0);
2228 if (missing_newline)
2229 fp->lineno--;
2231 if (pedantic && missing_newline)
2232 pedwarn ("file does not end in newline");
2234 /* Now we have processed the entire input
2235 Write whichever kind of output has been requested. */
2237 if (dump_macros == dump_only)
2238 dump_all_macros ();
2239 else if (! inhibit_output) {
2240 write_output ();
2243 if (print_deps) {
2244 /* Don't actually write the deps file if compilation has failed. */
2245 if (errors == 0) {
2246 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2247 pfatal_with_name (deps_file);
2248 fputs (deps_buffer, deps_stream);
2249 putc ('\n', deps_stream);
2250 if (deps_file) {
2251 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2252 fatal ("I/O error on output");
2257 if (pcp_outfile && pcp_outfile != stdout
2258 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2259 fatal ("I/O error on `-pcp' output");
2261 if (ferror (stdout) || fclose (stdout) != 0)
2262 fatal ("I/O error on output");
2264 if (errors)
2265 exit (FATAL_EXIT_CODE);
2266 exit (SUCCESS_EXIT_CODE);
2268 perror:
2269 pfatal_with_name (in_fname);
2270 return 0;
2273 /* Given a colon-separated list of file names PATH,
2274 add all the names to the search path for include files. */
2276 static void
2277 path_include (path)
2278 char *path;
2280 char *p;
2282 p = path;
2284 if (*p)
2285 while (1) {
2286 char *q = p;
2287 char c;
2288 struct file_name_list *dirtmp;
2290 /* Find the end of this name. */
2291 while ((c = *q++) != PATH_SEPARATOR && c)
2292 continue;
2294 q[-1] = 0;
2295 dirtmp = new_include_prefix (last_include, NULL_PTR,
2296 "", p == q ? "." : p);
2297 q[-1] = c;
2298 append_include_chain (dirtmp, dirtmp);
2300 /* Advance past this name. */
2301 p = q;
2302 if (! c)
2303 break;
2307 /* Return the address of the first character in S that equals C.
2308 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2309 Return 0 if there is no such character. Assume that C itself is not '\0'.
2310 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2311 but unfortunately memchr isn't autoconfigured yet. */
2313 static U_CHAR *
2314 index0 (s, c, n)
2315 U_CHAR *s;
2316 int c;
2317 size_t n;
2319 char *p = (char *) s;
2320 for (;;) {
2321 char *q = index (p, c);
2322 if (q)
2323 return (U_CHAR *) q;
2324 else {
2325 size_t l = strlen (p);
2326 if (l == n)
2327 return 0;
2328 l++;
2329 p += l;
2330 n -= l;
2335 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2336 before main CCCP processing. Name `pcp' is also in honor of the
2337 drugs the trigraph designers must have been on.
2339 Using an extra pass through the buffer takes a little extra time,
2340 but is infinitely less hairy than trying to handle trigraphs inside
2341 strings, etc. everywhere, and also makes sure that trigraphs are
2342 only translated in the top level of processing. */
2344 static void
2345 trigraph_pcp (buf)
2346 FILE_BUF *buf;
2348 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2349 int len;
2351 fptr = bptr = sptr = buf->buf;
2352 lptr = fptr + buf->length;
2353 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2354 if (*++sptr != '?')
2355 continue;
2356 switch (*++sptr) {
2357 case '=':
2358 c = '#';
2359 break;
2360 case '(':
2361 c = '[';
2362 break;
2363 case '/':
2364 c = '\\';
2365 break;
2366 case ')':
2367 c = ']';
2368 break;
2369 case '\'':
2370 c = '^';
2371 break;
2372 case '<':
2373 c = '{';
2374 break;
2375 case '!':
2376 c = '|';
2377 break;
2378 case '>':
2379 c = '}';
2380 break;
2381 case '-':
2382 c = '~';
2383 break;
2384 case '?':
2385 sptr--;
2386 continue;
2387 default:
2388 continue;
2390 len = sptr - fptr - 2;
2392 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2393 C, this will be memmove (). */
2394 if (bptr != fptr && len > 0)
2395 bcopy ((char *) fptr, (char *) bptr, len);
2397 bptr += len;
2398 *bptr++ = c;
2399 fptr = ++sptr;
2401 len = buf->length - (fptr - buf->buf);
2402 if (bptr != fptr && len > 0)
2403 bcopy ((char *) fptr, (char *) bptr, len);
2404 buf->length -= fptr - bptr;
2405 buf->buf[buf->length] = '\0';
2406 if (warn_trigraphs && fptr != bptr)
2407 warning_with_line (0, "%lu trigraph(s) encountered",
2408 (unsigned long) (fptr - bptr) / 2);
2411 /* Move all backslash-newline pairs out of embarrassing places.
2412 Exchange all such pairs following BP
2413 with any potentially-embarrassing characters that follow them.
2414 Potentially-embarrassing characters are / and *
2415 (because a backslash-newline inside a comment delimiter
2416 would cause it not to be recognized). */
2418 static void
2419 newline_fix (bp)
2420 U_CHAR *bp;
2422 register U_CHAR *p = bp;
2424 /* First count the backslash-newline pairs here. */
2426 while (p[0] == '\\' && p[1] == '\n')
2427 p += 2;
2429 /* What follows the backslash-newlines is not embarrassing. */
2431 if (*p != '/' && *p != '*')
2432 return;
2434 /* Copy all potentially embarrassing characters
2435 that follow the backslash-newline pairs
2436 down to where the pairs originally started. */
2438 while (*p == '*' || *p == '/')
2439 *bp++ = *p++;
2441 /* Now write the same number of pairs after the embarrassing chars. */
2442 while (bp < p) {
2443 *bp++ = '\\';
2444 *bp++ = '\n';
2448 /* Like newline_fix but for use within a directive-name.
2449 Move any backslash-newlines up past any following symbol constituents. */
2451 static void
2452 name_newline_fix (bp)
2453 U_CHAR *bp;
2455 register U_CHAR *p = bp;
2457 /* First count the backslash-newline pairs here. */
2458 while (p[0] == '\\' && p[1] == '\n')
2459 p += 2;
2461 /* What follows the backslash-newlines is not embarrassing. */
2463 if (!is_idchar[*p])
2464 return;
2466 /* Copy all potentially embarrassing characters
2467 that follow the backslash-newline pairs
2468 down to where the pairs originally started. */
2470 while (is_idchar[*p])
2471 *bp++ = *p++;
2473 /* Now write the same number of pairs after the embarrassing chars. */
2474 while (bp < p) {
2475 *bp++ = '\\';
2476 *bp++ = '\n';
2480 /* Look for lint commands in comments.
2482 When we come in here, ibp points into a comment. Limit is as one expects.
2483 scan within the comment -- it should start, after lwsp, with a lint command.
2484 If so that command is returned as a (constant) string.
2486 Upon return, any arg will be pointed to with argstart and will be
2487 arglen long. Note that we don't parse that arg since it will just
2488 be printed out again. */
2490 static char *
2491 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2492 register U_CHAR *ibp;
2493 register U_CHAR *limit;
2494 U_CHAR **argstart; /* point to command arg */
2495 int *arglen, *cmdlen; /* how long they are */
2497 HOST_WIDE_INT linsize;
2498 register U_CHAR *numptr; /* temp for arg parsing */
2500 *arglen = 0;
2502 SKIP_WHITE_SPACE (ibp);
2504 if (ibp >= limit) return NULL;
2506 linsize = limit - ibp;
2508 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2509 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2510 *cmdlen = 10;
2511 return "NOTREACHED";
2513 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2514 *cmdlen = 8;
2515 return "ARGSUSED";
2517 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2518 *cmdlen = 11;
2519 return "LINTLIBRARY";
2521 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2522 *cmdlen = 7;
2523 ibp += 7; linsize -= 7;
2524 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2526 /* OK, read a number */
2527 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2528 numptr++);
2529 *arglen = numptr - *argstart;
2530 return "VARARGS";
2532 return NULL;
2536 * The main loop of the program.
2538 * Read characters from the input stack, transferring them to the
2539 * output buffer OP.
2541 * Macros are expanded and push levels on the input stack.
2542 * At the end of such a level it is popped off and we keep reading.
2543 * At the end of any other kind of level, we return.
2544 * #-directives are handled, except within macros.
2546 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2547 * and insert them when appropriate. This is set while scanning macro
2548 * arguments before substitution. It is zero when scanning for final output.
2549 * There are three types of Newline markers:
2550 * * Newline - follows a macro name that was not expanded
2551 * because it appeared inside an expansion of the same macro.
2552 * This marker prevents future expansion of that identifier.
2553 * When the input is rescanned into the final output, these are deleted.
2554 * These are also deleted by ## concatenation.
2555 * * Newline Space (or Newline and any other whitespace character)
2556 * stands for a place that tokens must be separated or whitespace
2557 * is otherwise desirable, but where the ANSI standard specifies there
2558 * is no whitespace. This marker turns into a Space (or whichever other
2559 * whitespace char appears in the marker) in the final output,
2560 * but it turns into nothing in an argument that is stringified with #.
2561 * Such stringified arguments are the only place where the ANSI standard
2562 * specifies with precision that whitespace may not appear.
2564 * During this function, IP->bufp is kept cached in IBP for speed of access.
2565 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2566 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2567 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2568 * explicitly, and before RECACHE, since RECACHE uses OBP.
2571 static void
2572 rescan (op, output_marks)
2573 FILE_BUF *op;
2574 int output_marks;
2576 /* Character being scanned in main loop. */
2577 register U_CHAR c;
2579 /* Length of pending accumulated identifier. */
2580 register int ident_length = 0;
2582 /* Hash code of pending accumulated identifier. */
2583 register int hash = 0;
2585 /* Current input level (&instack[indepth]). */
2586 FILE_BUF *ip;
2588 /* Pointer for scanning input. */
2589 register U_CHAR *ibp;
2591 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2592 register U_CHAR *limit;
2594 /* Pointer for storing output. */
2595 register U_CHAR *obp;
2597 /* REDO_CHAR is nonzero if we are processing an identifier
2598 after backing up over the terminating character.
2599 Sometimes we process an identifier without backing up over
2600 the terminating character, if the terminating character
2601 is not special. Backing up is done so that the terminating character
2602 will be dispatched on again once the identifier is dealt with. */
2603 int redo_char = 0;
2605 /* 1 if within an identifier inside of which a concatenation
2606 marker (Newline -) has been seen. */
2607 int concatenated = 0;
2609 /* While scanning a comment or a string constant,
2610 this records the line it started on, for error messages. */
2611 int start_line;
2613 /* Record position of last `real' newline. */
2614 U_CHAR *beg_of_line;
2616 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2618 #define POPMACRO \
2619 do { ip->macro->type = T_MACRO; \
2620 if (ip->free_ptr) free (ip->free_ptr); \
2621 --indepth; } while (0)
2623 /* Reload `rescan's local variables that describe the current
2624 level of the input stack. */
2626 #define RECACHE \
2627 do { ip = &instack[indepth]; \
2628 ibp = ip->bufp; \
2629 limit = ip->buf + ip->length; \
2630 op->bufp = obp; \
2631 check_expand (op, limit - ibp); \
2632 beg_of_line = 0; \
2633 obp = op->bufp; } while (0)
2635 if (no_output && instack[indepth].fname != 0)
2636 skip_if_group (&instack[indepth], 1, NULL);
2638 obp = op->bufp;
2639 RECACHE;
2641 beg_of_line = ibp;
2643 /* Our caller must always put a null after the end of
2644 the input at each input stack level. */
2645 if (*limit != 0)
2646 abort ();
2648 while (1) {
2649 c = *ibp++;
2650 *obp++ = c;
2652 switch (c) {
2653 case '\\':
2654 if (*ibp == '\n' && !ip->macro) {
2655 /* At the top level, always merge lines ending with backslash-newline,
2656 even in middle of identifier. But do not merge lines in a macro,
2657 since backslash might be followed by a newline-space marker. */
2658 ++ibp;
2659 ++ip->lineno;
2660 --obp; /* remove backslash from obuf */
2661 break;
2663 /* If ANSI, backslash is just another character outside a string. */
2664 if (!traditional)
2665 goto randomchar;
2666 /* Otherwise, backslash suppresses specialness of following char,
2667 so copy it here to prevent the switch from seeing it.
2668 But first get any pending identifier processed. */
2669 if (ident_length > 0)
2670 goto specialchar;
2671 if (ibp < limit)
2672 *obp++ = *ibp++;
2673 break;
2675 case '%':
2676 if (ident_length || ip->macro || traditional)
2677 goto randomchar;
2678 while (*ibp == '\\' && ibp[1] == '\n') {
2679 ibp += 2;
2680 ++ip->lineno;
2682 if (*ibp != ':')
2683 break;
2684 /* Treat this %: digraph as if it were #. */
2685 /* Fall through. */
2687 case '#':
2688 if (assertions_flag) {
2689 if (ident_length)
2690 goto specialchar;
2691 /* Copy #foo (bar lose) without macro expansion. */
2692 obp[-1] = '#'; /* In case it was '%'. */
2693 SKIP_WHITE_SPACE (ibp);
2694 while (is_idchar[*ibp])
2695 *obp++ = *ibp++;
2696 SKIP_WHITE_SPACE (ibp);
2697 if (*ibp == '(') {
2698 ip->bufp = ibp;
2699 skip_paren_group (ip);
2700 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2701 obp += ip->bufp - ibp;
2702 ibp = ip->bufp;
2704 break;
2707 /* If this is expanding a macro definition, don't recognize
2708 preprocessing directives. */
2709 if (ip->macro != 0)
2710 goto randomchar;
2711 /* If this is expand_into_temp_buffer,
2712 don't recognize them either. Warn about them
2713 only after an actual newline at this level,
2714 not at the beginning of the input level. */
2715 if (! ip->fname) {
2716 if (ip->buf != beg_of_line)
2717 warning ("preprocessing directive not recognized within macro arg");
2718 goto randomchar;
2720 if (ident_length)
2721 goto specialchar;
2724 /* # keyword: a # must be first nonblank char on the line */
2725 if (beg_of_line == 0)
2726 goto randomchar;
2728 U_CHAR *bp;
2730 /* Scan from start of line, skipping whitespace, comments
2731 and backslash-newlines, and see if we reach this #.
2732 If not, this # is not special. */
2733 bp = beg_of_line;
2734 /* If -traditional, require # to be at beginning of line. */
2735 if (!traditional) {
2736 while (1) {
2737 if (is_hor_space[*bp])
2738 bp++;
2739 else if (*bp == '\\' && bp[1] == '\n')
2740 bp += 2;
2741 else if (*bp == '/' && bp[1] == '*') {
2742 bp += 2;
2743 while (!(*bp == '*' && bp[1] == '/'))
2744 bp++;
2745 bp += 2;
2747 /* There is no point in trying to deal with C++ // comments here,
2748 because if there is one, then this # must be part of the
2749 comment and we would never reach here. */
2750 else break;
2752 if (c == '%') {
2753 if (bp[0] != '%')
2754 break;
2755 while (bp[1] == '\\' && bp[2] == '\n')
2756 bp += 2;
2757 if (bp + 1 != ibp)
2758 break;
2759 /* %: appears at start of line; skip past the ':' too. */
2760 bp++;
2761 ibp++;
2764 if (bp + 1 != ibp)
2765 goto randomchar;
2768 /* This # can start a directive. */
2770 --obp; /* Don't copy the '#' */
2772 ip->bufp = ibp;
2773 op->bufp = obp;
2774 if (! handle_directive (ip, op)) {
2775 #ifdef USE_C_ALLOCA
2776 alloca (0);
2777 #endif
2778 /* Not a known directive: treat it as ordinary text.
2779 IP, OP, IBP, etc. have not been changed. */
2780 if (no_output && instack[indepth].fname) {
2781 /* If not generating expanded output,
2782 what we do with ordinary text is skip it.
2783 Discard everything until next # directive. */
2784 skip_if_group (&instack[indepth], 1, 0);
2785 RECACHE;
2786 beg_of_line = ibp;
2787 break;
2789 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2790 /* Don't expand an identifier that could be a macro directive.
2791 (Section 3.8.3 of the ANSI C standard) */
2792 SKIP_WHITE_SPACE (ibp);
2793 if (is_idstart[*ibp])
2795 *obp++ = *ibp++;
2796 while (is_idchar[*ibp])
2797 *obp++ = *ibp++;
2799 goto randomchar;
2801 #ifdef USE_C_ALLOCA
2802 alloca (0);
2803 #endif
2804 /* A # directive has been successfully processed. */
2805 /* If not generating expanded output, ignore everything until
2806 next # directive. */
2807 if (no_output && instack[indepth].fname)
2808 skip_if_group (&instack[indepth], 1, 0);
2809 obp = op->bufp;
2810 RECACHE;
2811 beg_of_line = ibp;
2812 break;
2814 case '\"': /* skip quoted string */
2815 case '\'':
2816 /* A single quoted string is treated like a double -- some
2817 programs (e.g., troff) are perverse this way */
2819 /* Handle any pending identifier;
2820 but the L in L'...' or L"..." is not an identifier. */
2821 if (ident_length
2822 && ! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2823 goto specialchar;
2825 start_line = ip->lineno;
2827 /* Skip ahead to a matching quote. */
2829 while (1) {
2830 if (ibp >= limit) {
2831 if (ip->macro != 0) {
2832 /* try harder: this string crosses a macro expansion boundary.
2833 This can happen naturally if -traditional.
2834 Otherwise, only -D can make a macro with an unmatched quote. */
2835 POPMACRO;
2836 RECACHE;
2837 continue;
2839 if (!traditional) {
2840 error_with_line (line_for_error (start_line),
2841 "unterminated string or character constant");
2842 error_with_line (multiline_string_line,
2843 "possible real start of unterminated constant");
2844 multiline_string_line = 0;
2846 break;
2848 *obp++ = *ibp;
2849 switch (*ibp++) {
2850 case '\n':
2851 ++ip->lineno;
2852 ++op->lineno;
2853 /* Traditionally, end of line ends a string constant with no error.
2854 So exit the loop and record the new line. */
2855 if (traditional) {
2856 beg_of_line = ibp;
2857 goto while2end;
2859 if (c == '\'') {
2860 error_with_line (line_for_error (start_line),
2861 "unterminated character constant");
2862 goto while2end;
2864 if (multiline_string_line == 0) {
2865 if (pedantic)
2866 pedwarn_with_line (line_for_error (start_line),
2867 "string constant runs past end of line");
2868 multiline_string_line = ip->lineno - 1;
2870 break;
2872 case '\\':
2873 if (ibp >= limit)
2874 break;
2875 if (*ibp == '\n') {
2876 /* Backslash newline is replaced by nothing at all,
2877 but keep the line counts correct. */
2878 --obp;
2879 ++ibp;
2880 ++ip->lineno;
2881 } else {
2882 /* ANSI stupidly requires that in \\ the second \
2883 is *not* prevented from combining with a newline. */
2884 while (*ibp == '\\' && ibp[1] == '\n') {
2885 ibp += 2;
2886 ++ip->lineno;
2888 *obp++ = *ibp++;
2890 break;
2892 case '\"':
2893 case '\'':
2894 if (ibp[-1] == c)
2895 goto while2end;
2896 break;
2899 while2end:
2900 break;
2902 case '/':
2903 if (*ibp == '\\' && ibp[1] == '\n')
2904 newline_fix (ibp);
2906 if (*ibp != '*'
2907 && !(cplusplus_comments && *ibp == '/'))
2908 goto randomchar;
2909 if (ip->macro != 0)
2910 goto randomchar;
2911 if (ident_length)
2912 goto specialchar;
2914 if (*ibp == '/') {
2915 /* C++ style comment... */
2916 start_line = ip->lineno;
2918 /* Comments are equivalent to spaces. */
2919 if (! put_out_comments)
2920 obp[-1] = ' ';
2923 U_CHAR *before_bp = ibp;
2925 while (++ibp < limit) {
2926 if (*ibp == '\n') {
2927 if (ibp[-1] != '\\') {
2928 if (put_out_comments) {
2929 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2930 obp += ibp - before_bp;
2932 break;
2934 if (warn_comments)
2935 warning ("multiline `//' comment");
2936 ++ip->lineno;
2937 /* Copy the newline into the output buffer, in order to
2938 avoid the pain of a #line every time a multiline comment
2939 is seen. */
2940 if (!put_out_comments)
2941 *obp++ = '\n';
2942 ++op->lineno;
2945 break;
2949 /* Ordinary C comment. Skip it, optionally copying it to output. */
2951 start_line = ip->lineno;
2953 ++ibp; /* Skip the star. */
2955 /* If this cpp is for lint, we peek inside the comments: */
2956 if (for_lint) {
2957 U_CHAR *argbp;
2958 int cmdlen, arglen;
2959 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2961 if (lintcmd != NULL) {
2962 op->bufp = obp;
2963 check_expand (op, cmdlen + arglen + 14);
2964 obp = op->bufp;
2965 /* I believe it is always safe to emit this newline: */
2966 obp[-1] = '\n';
2967 bcopy ("#pragma lint ", (char *) obp, 13);
2968 obp += 13;
2969 bcopy (lintcmd, (char *) obp, cmdlen);
2970 obp += cmdlen;
2972 if (arglen != 0) {
2973 *(obp++) = ' ';
2974 bcopy (argbp, (char *) obp, arglen);
2975 obp += arglen;
2978 /* OK, now bring us back to the state we were in before we entered
2979 this branch. We need #line because the #pragma's newline always
2980 messes up the line count. */
2981 op->bufp = obp;
2982 output_line_directive (ip, op, 0, same_file);
2983 check_expand (op, limit - ibp + 2);
2984 obp = op->bufp;
2985 *(obp++) = '/';
2989 /* Comments are equivalent to spaces.
2990 Note that we already output the slash; we might not want it.
2991 For -traditional, a comment is equivalent to nothing. */
2992 if (! put_out_comments) {
2993 if (traditional)
2994 obp--;
2995 else
2996 obp[-1] = ' ';
2998 else
2999 *obp++ = '*';
3002 U_CHAR *before_bp = ibp;
3004 for (;;) {
3005 switch (*ibp++) {
3006 case '*':
3007 if (ibp[-2] == '/' && warn_comments)
3008 warning ("`/*' within comment");
3009 if (*ibp == '\\' && ibp[1] == '\n')
3010 newline_fix (ibp);
3011 if (*ibp == '/')
3012 goto comment_end;
3013 break;
3015 case '\n':
3016 ++ip->lineno;
3017 /* Copy the newline into the output buffer, in order to
3018 avoid the pain of a #line every time a multiline comment
3019 is seen. */
3020 if (!put_out_comments)
3021 *obp++ = '\n';
3022 ++op->lineno;
3023 break;
3025 case 0:
3026 if (limit < ibp) {
3027 error_with_line (line_for_error (start_line),
3028 "unterminated comment");
3029 goto limit_reached;
3031 break;
3034 comment_end:
3036 ibp++;
3037 if (put_out_comments) {
3038 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3039 obp += ibp - before_bp;
3042 break;
3044 case '$':
3045 if (! is_idchar['$'])
3046 goto randomchar;
3047 if (pedantic)
3048 pedwarn ("`$' in identifier");
3049 goto letter;
3051 case '0': case '1': case '2': case '3': case '4':
3052 case '5': case '6': case '7': case '8': case '9':
3053 /* If digit is not part of identifier, it starts a number,
3054 which means that following letters are not an identifier.
3055 "0x5" does not refer to an identifier "x5".
3056 So copy all alphanumerics that follow without accumulating
3057 as an identifier. Periods also, for sake of "3.e7". */
3059 if (ident_length == 0) {
3060 for (;;) {
3061 while (ibp[0] == '\\' && ibp[1] == '\n') {
3062 ++ip->lineno;
3063 ibp += 2;
3065 c = *ibp++;
3066 if (!is_idchar[c] && c != '.') {
3067 --ibp;
3068 break;
3070 *obp++ = c;
3071 /* A sign can be part of a preprocessing number
3072 if it follows an `e' or `p'. */
3073 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3074 while (ibp[0] == '\\' && ibp[1] == '\n') {
3075 ++ip->lineno;
3076 ibp += 2;
3078 if (*ibp == '+' || *ibp == '-') {
3079 *obp++ = *ibp++;
3080 /* But traditional C does not let the token go past the sign,
3081 and C89 does not allow `p'. */
3082 if (traditional || (c89 && (c == 'p' || c == 'P')))
3083 break;
3087 break;
3089 /* fall through */
3091 case '_':
3092 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3093 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3094 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3095 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3096 case 'y': case 'z':
3097 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3098 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3099 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3100 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3101 case 'Y': case 'Z':
3102 letter:
3103 ident_length++;
3104 /* Compute step of hash function, to avoid a proc call on every token */
3105 hash = HASHSTEP (hash, c);
3106 break;
3108 case '\n':
3109 if (ip->fname == 0 && *ibp == '-') {
3110 /* Newline - inhibits expansion of preceding token.
3111 If expanding a macro arg, we keep the newline -.
3112 In final output, it is deleted.
3113 We recognize Newline - in macro bodies and macro args. */
3114 if (! concatenated) {
3115 ident_length = 0;
3116 hash = 0;
3118 ibp++;
3119 if (!output_marks) {
3120 obp--;
3121 } else {
3122 /* If expanding a macro arg, keep the newline -. */
3123 *obp++ = '-';
3125 break;
3128 /* If reprocessing a macro expansion, newline is a special marker. */
3129 else if (ip->macro != 0) {
3130 /* Newline White is a "funny space" to separate tokens that are
3131 supposed to be separate but without space between.
3132 Here White means any whitespace character.
3133 Newline - marks a recursive macro use that is not
3134 supposed to be expandable. */
3136 if (is_space[*ibp]) {
3137 /* Newline Space does not prevent expansion of preceding token
3138 so expand the preceding token and then come back. */
3139 if (ident_length > 0)
3140 goto specialchar;
3142 /* If generating final output, newline space makes a space. */
3143 if (!output_marks) {
3144 obp[-1] = *ibp++;
3145 /* And Newline Newline makes a newline, so count it. */
3146 if (obp[-1] == '\n')
3147 op->lineno++;
3148 } else {
3149 /* If expanding a macro arg, keep the newline space.
3150 If the arg gets stringified, newline space makes nothing. */
3151 *obp++ = *ibp++;
3153 } else abort (); /* Newline followed by something random? */
3154 break;
3157 /* If there is a pending identifier, handle it and come back here. */
3158 if (ident_length > 0)
3159 goto specialchar;
3161 beg_of_line = ibp;
3163 /* Update the line counts and output a #line if necessary. */
3164 ++ip->lineno;
3165 ++op->lineno;
3166 if (ip->lineno != op->lineno) {
3167 op->bufp = obp;
3168 output_line_directive (ip, op, 1, same_file);
3169 check_expand (op, limit - ibp);
3170 obp = op->bufp;
3172 break;
3174 /* Come here either after (1) a null character that is part of the input
3175 or (2) at the end of the input, because there is a null there. */
3176 case 0:
3177 if (ibp <= limit)
3178 /* Our input really contains a null character. */
3179 goto randomchar;
3181 limit_reached:
3182 /* At end of a macro-expansion level, pop it and read next level. */
3183 if (ip->macro != 0) {
3184 obp--;
3185 ibp--;
3186 /* If traditional, and we have an identifier that ends here,
3187 process it now, so we get the right error for recursion. */
3188 if (traditional && ident_length
3189 && ! is_idchar[*instack[indepth - 1].bufp]) {
3190 redo_char = 1;
3191 goto randomchar;
3193 POPMACRO;
3194 RECACHE;
3195 break;
3198 /* If we don't have a pending identifier,
3199 return at end of input. */
3200 if (ident_length == 0) {
3201 obp--;
3202 ibp--;
3203 op->bufp = obp;
3204 ip->bufp = ibp;
3205 goto ending;
3208 /* If we do have a pending identifier, just consider this null
3209 a special character and arrange to dispatch on it again.
3210 The second time, IDENT_LENGTH will be zero so we will return. */
3212 /* Fall through */
3214 specialchar:
3216 /* Handle the case of a character such as /, ', " or null
3217 seen following an identifier. Back over it so that
3218 after the identifier is processed the special char
3219 will be dispatched on again. */
3221 ibp--;
3222 obp--;
3223 redo_char = 1;
3225 default:
3227 randomchar:
3229 if (ident_length > 0) {
3230 register HASHNODE *hp;
3232 /* We have just seen an identifier end. If it's a macro, expand it.
3234 IDENT_LENGTH is the length of the identifier
3235 and HASH is its hash code.
3237 The identifier has already been copied to the output,
3238 so if it is a macro we must remove it.
3240 If REDO_CHAR is 0, the char that terminated the identifier
3241 has been skipped in the output and the input.
3242 OBP-IDENT_LENGTH-1 points to the identifier.
3243 If the identifier is a macro, we must back over the terminator.
3245 If REDO_CHAR is 1, the terminating char has already been
3246 backed over. OBP-IDENT_LENGTH points to the identifier. */
3248 if (!pcp_outfile || pcp_inside_if) {
3249 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3250 hp = hp->next) {
3252 if (hp->length == ident_length) {
3253 int obufp_before_macroname;
3254 int op_lineno_before_macroname;
3255 register int i = ident_length;
3256 register U_CHAR *p = hp->name;
3257 register U_CHAR *q = obp - i;
3258 int disabled;
3260 if (! redo_char)
3261 q--;
3263 do { /* All this to avoid a strncmp () */
3264 if (*p++ != *q++)
3265 goto hashcollision;
3266 } while (--i);
3268 /* We found a use of a macro name.
3269 see if the context shows it is a macro call. */
3271 /* Back up over terminating character if not already done. */
3272 if (! redo_char) {
3273 ibp--;
3274 obp--;
3277 /* Save this as a displacement from the beginning of the output
3278 buffer. We can not save this as a position in the output
3279 buffer, because it may get realloc'ed by RECACHE. */
3280 obufp_before_macroname = (obp - op->buf) - ident_length;
3281 op_lineno_before_macroname = op->lineno;
3283 if (hp->type == T_PCSTRING) {
3284 pcstring_used (hp); /* Mark the definition of this key
3285 as needed, ensuring that it
3286 will be output. */
3287 break; /* Exit loop, since the key cannot have a
3288 definition any longer. */
3291 /* Record whether the macro is disabled. */
3292 disabled = hp->type == T_DISABLED;
3294 /* This looks like a macro ref, but if the macro was disabled,
3295 just copy its name and put in a marker if requested. */
3297 if (disabled) {
3298 #if 0
3299 /* This error check caught useful cases such as
3300 #define foo(x,y) bar (x (y,0), y)
3301 foo (foo, baz) */
3302 if (traditional)
3303 error ("recursive use of macro `%s'", hp->name);
3304 #endif
3306 if (output_marks) {
3307 check_expand (op, limit - ibp + 2);
3308 *obp++ = '\n';
3309 *obp++ = '-';
3311 break;
3314 /* If macro wants an arglist, verify that a '(' follows.
3315 first skip all whitespace, copying it to the output
3316 after the macro name. Then, if there is no '(',
3317 decide this is not a macro call and leave things that way. */
3318 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3319 && hp->value.defn->nargs >= 0)
3321 U_CHAR *old_ibp = ibp;
3322 U_CHAR *old_obp = obp;
3323 int old_iln = ip->lineno;
3324 int old_oln = op->lineno;
3326 while (1) {
3327 /* Scan forward over whitespace, copying it to the output. */
3328 if (ibp == limit && ip->macro != 0) {
3329 POPMACRO;
3330 RECACHE;
3331 old_ibp = ibp;
3332 old_obp = obp;
3333 old_iln = ip->lineno;
3334 old_oln = op->lineno;
3336 /* A comment: copy it unchanged or discard it. */
3337 else if (*ibp == '/' && ibp[1] == '*') {
3338 if (put_out_comments) {
3339 *obp++ = '/';
3340 *obp++ = '*';
3341 } else if (! traditional) {
3342 *obp++ = ' ';
3344 ibp += 2;
3345 while (ibp + 1 != limit
3346 && !(ibp[0] == '*' && ibp[1] == '/')) {
3347 /* We need not worry about newline-marks,
3348 since they are never found in comments. */
3349 if (*ibp == '\n') {
3350 /* Newline in a file. Count it. */
3351 ++ip->lineno;
3352 ++op->lineno;
3354 if (put_out_comments)
3355 *obp++ = *ibp++;
3356 else
3357 ibp++;
3359 ibp += 2;
3360 if (put_out_comments) {
3361 *obp++ = '*';
3362 *obp++ = '/';
3365 else if (is_space[*ibp]) {
3366 *obp++ = *ibp++;
3367 if (ibp[-1] == '\n') {
3368 if (ip->macro == 0) {
3369 /* Newline in a file. Count it. */
3370 ++ip->lineno;
3371 ++op->lineno;
3372 } else if (!output_marks) {
3373 /* A newline mark, and we don't want marks
3374 in the output. If it is newline-hyphen,
3375 discard it entirely. Otherwise, it is
3376 newline-whitechar, so keep the whitechar. */
3377 obp--;
3378 if (*ibp == '-')
3379 ibp++;
3380 else {
3381 if (*ibp == '\n')
3382 ++op->lineno;
3383 *obp++ = *ibp++;
3385 } else {
3386 /* A newline mark; copy both chars to the output. */
3387 *obp++ = *ibp++;
3391 else break;
3393 if (*ibp != '(') {
3394 /* It isn't a macro call.
3395 Put back the space that we just skipped. */
3396 ibp = old_ibp;
3397 obp = old_obp;
3398 ip->lineno = old_iln;
3399 op->lineno = old_oln;
3400 /* Exit the for loop. */
3401 break;
3405 /* This is now known to be a macro call.
3406 Discard the macro name from the output,
3407 along with any following whitespace just copied,
3408 but preserve newlines if not outputting marks since this
3409 is more likely to do the right thing with line numbers. */
3410 obp = op->buf + obufp_before_macroname;
3411 if (output_marks)
3412 op->lineno = op_lineno_before_macroname;
3413 else {
3414 int newlines = op->lineno - op_lineno_before_macroname;
3415 while (0 < newlines--)
3416 *obp++ = '\n';
3419 /* Prevent accidental token-pasting with a character
3420 before the macro call. */
3421 if (!traditional && obp != op->buf) {
3422 switch (obp[-1]) {
3423 case '!': case '%': case '&': case '*':
3424 case '+': case '-': case '.': case '/':
3425 case ':': case '<': case '=': case '>':
3426 case '^': case '|':
3427 /* If we are expanding a macro arg, make a newline marker
3428 to separate the tokens. If we are making real output,
3429 a plain space will do. */
3430 if (output_marks)
3431 *obp++ = '\n';
3432 *obp++ = ' ';
3436 /* Expand the macro, reading arguments as needed,
3437 and push the expansion on the input stack. */
3438 ip->bufp = ibp;
3439 op->bufp = obp;
3440 macroexpand (hp, op);
3442 /* Reexamine input stack, since macroexpand has pushed
3443 a new level on it. */
3444 obp = op->bufp;
3445 RECACHE;
3446 break;
3448 hashcollision:
3450 } /* End hash-table-search loop */
3452 ident_length = hash = 0; /* Stop collecting identifier */
3453 redo_char = 0;
3454 concatenated = 0;
3455 } /* End if (ident_length > 0) */
3456 } /* End switch */
3457 } /* End per-char loop */
3459 /* Come here to return -- but first give an error message
3460 if there was an unterminated successful conditional. */
3461 ending:
3462 if (if_stack != ip->if_stack)
3464 char *str;
3466 switch (if_stack->type)
3468 case T_IF:
3469 str = "if";
3470 break;
3471 case T_IFDEF:
3472 str = "ifdef";
3473 break;
3474 case T_IFNDEF:
3475 str = "ifndef";
3476 break;
3477 case T_ELSE:
3478 str = "else";
3479 break;
3480 case T_ELIF:
3481 str = "elif";
3482 break;
3483 default:
3484 abort ();
3487 error_with_line (line_for_error (if_stack->lineno),
3488 "unterminated `#%s' conditional", str);
3490 if_stack = ip->if_stack;
3494 * Rescan a string into a temporary buffer and return the result
3495 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3497 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3498 * and insert such markers when appropriate. See `rescan' for details.
3499 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3500 * before substitution; it is 0 for other uses.
3502 static FILE_BUF
3503 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3504 U_CHAR *buf, *limit;
3505 int output_marks, assertions;
3507 register FILE_BUF *ip;
3508 FILE_BUF obuf;
3509 int length = limit - buf;
3510 U_CHAR *buf1;
3511 int odepth = indepth;
3512 int save_assertions_flag = assertions_flag;
3514 assertions_flag = assertions;
3516 if (length < 0)
3517 abort ();
3519 /* Set up the input on the input stack. */
3521 buf1 = (U_CHAR *) alloca (length + 1);
3523 register U_CHAR *p1 = buf;
3524 register U_CHAR *p2 = buf1;
3526 while (p1 != limit)
3527 *p2++ = *p1++;
3529 buf1[length] = 0;
3531 /* Set up to receive the output. */
3533 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3534 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3535 obuf.nominal_fname = 0;
3536 obuf.inc = 0;
3537 obuf.dir = 0;
3538 obuf.fname = 0;
3539 obuf.macro = 0;
3540 obuf.if_stack = 0;
3541 obuf.free_ptr = 0;
3542 obuf.system_header_p = 0;
3544 CHECK_DEPTH ({return obuf;});
3546 ++indepth;
3548 ip = &instack[indepth];
3549 ip->fname = 0;
3550 ip->nominal_fname = 0;
3551 ip->inc = 0;
3552 ip->system_header_p = 0;
3553 ip->macro = 0;
3554 ip->free_ptr = 0;
3555 ip->length = length;
3556 ip->buf = ip->bufp = buf1;
3557 ip->if_stack = if_stack;
3559 ip->lineno = obuf.lineno = 1;
3561 /* Scan the input, create the output. */
3562 rescan (&obuf, output_marks);
3564 /* Pop input stack to original state. */
3565 --indepth;
3567 if (indepth != odepth)
3568 abort ();
3570 /* Record the output. */
3571 obuf.length = obuf.bufp - obuf.buf;
3573 assertions_flag = save_assertions_flag;
3574 return obuf;
3578 * Process a # directive. Expects IP->bufp to point after the '#', as in
3579 * `#define foo bar'. Passes to the directive handler
3580 * (do_define, do_include, etc.): the addresses of the 1st and
3581 * last chars of the directive (starting immediately after the #
3582 * keyword), plus op and the keyword table pointer. If the directive
3583 * contains comments it is copied into a temporary buffer sans comments
3584 * and the temporary buffer is passed to the directive handler instead.
3585 * Likewise for backslash-newlines.
3587 * Returns nonzero if this was a known # directive.
3588 * Otherwise, returns zero, without advancing the input pointer.
3591 static int
3592 handle_directive (ip, op)
3593 FILE_BUF *ip, *op;
3595 register U_CHAR *bp, *cp;
3596 register struct directive *kt;
3597 register int ident_length;
3598 U_CHAR *resume_p;
3600 /* Nonzero means we must copy the entire directive
3601 to get rid of comments or backslash-newlines. */
3602 int copy_directive = 0;
3604 U_CHAR *ident, *after_ident;
3606 bp = ip->bufp;
3608 /* Record where the directive started. do_xifdef needs this. */
3609 directive_start = bp - 1;
3611 /* Skip whitespace and \-newline. */
3612 while (1) {
3613 if (is_hor_space[*bp]) {
3614 if (*bp != ' ' && *bp != '\t' && pedantic)
3615 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3616 bp++;
3617 } else if (*bp == '/' && (bp[1] == '*'
3618 || (cplusplus_comments && bp[1] == '/'))) {
3619 ip->bufp = bp + 2;
3620 skip_to_end_of_comment (ip, &ip->lineno, 0);
3621 bp = ip->bufp;
3622 } else if (*bp == '\\' && bp[1] == '\n') {
3623 bp += 2; ip->lineno++;
3624 } else break;
3627 /* Now find end of directive name.
3628 If we encounter a backslash-newline, exchange it with any following
3629 symbol-constituents so that we end up with a contiguous name. */
3631 cp = bp;
3632 while (1) {
3633 if (is_idchar[*cp])
3634 cp++;
3635 else {
3636 if (*cp == '\\' && cp[1] == '\n')
3637 name_newline_fix (cp);
3638 if (is_idchar[*cp])
3639 cp++;
3640 else break;
3643 ident_length = cp - bp;
3644 ident = bp;
3645 after_ident = cp;
3647 /* A line of just `#' becomes blank. */
3649 if (ident_length == 0 && *after_ident == '\n') {
3650 ip->bufp = after_ident;
3651 return 1;
3654 if (ident_length == 0 || !is_idstart[*ident]) {
3655 U_CHAR *p = ident;
3656 while (is_idchar[*p]) {
3657 if (*p < '0' || *p > '9')
3658 break;
3659 p++;
3661 /* Handle # followed by a line number. */
3662 if (p != ident && !is_idchar[*p]) {
3663 static struct directive line_directive_table[] = {
3664 { 4, do_line, "line", T_LINE},
3666 if (pedantic)
3667 pedwarn ("`#' followed by integer");
3668 after_ident = ident;
3669 kt = line_directive_table;
3670 goto old_linenum;
3673 /* Avoid error for `###' and similar cases unless -pedantic. */
3674 if (p == ident) {
3675 while (*p == '#' || is_hor_space[*p]) p++;
3676 if (*p == '\n') {
3677 if (pedantic && !lang_asm)
3678 warning ("invalid preprocessing directive");
3679 return 0;
3683 if (!lang_asm)
3684 error ("invalid preprocessing directive name");
3686 return 0;
3690 * Decode the keyword and call the appropriate expansion
3691 * routine, after moving the input pointer up to the next line.
3693 for (kt = directive_table; kt->length > 0; kt++) {
3694 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3695 register U_CHAR *buf;
3696 register U_CHAR *limit;
3697 int unterminated;
3698 int junk;
3699 int *already_output;
3701 /* Nonzero means do not delete comments within the directive.
3702 #define needs this when -traditional. */
3703 int keep_comments;
3705 old_linenum:
3707 limit = ip->buf + ip->length;
3708 unterminated = 0;
3709 already_output = 0;
3710 keep_comments = traditional && kt->type == T_DEFINE;
3711 /* #import is defined only in Objective C, or when on the NeXT. */
3712 if (kt->type == T_IMPORT
3713 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3714 break;
3716 /* Find the end of this directive (first newline not backslashed
3717 and not in a string or comment).
3718 Set COPY_DIRECTIVE if the directive must be copied
3719 (it contains a backslash-newline or a comment). */
3721 buf = bp = after_ident;
3722 while (bp < limit) {
3723 register U_CHAR c = *bp++;
3724 switch (c) {
3725 case '\\':
3726 if (bp < limit) {
3727 if (*bp == '\n') {
3728 ip->lineno++;
3729 copy_directive = 1;
3730 bp++;
3731 } else if (traditional)
3732 bp++;
3734 break;
3736 case '\'':
3737 case '\"':
3738 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3739 /* Don't bother calling the directive if we already got an error
3740 message due to unterminated string. Skip everything and pretend
3741 we called the directive. */
3742 if (unterminated) {
3743 if (traditional) {
3744 /* Traditional preprocessing permits unterminated strings. */
3745 ip->bufp = bp;
3746 goto endloop1;
3748 ip->bufp = bp;
3749 return 1;
3751 break;
3753 /* <...> is special for #include. */
3754 case '<':
3755 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3756 break;
3757 while (bp < limit && *bp != '>' && *bp != '\n') {
3758 if (*bp == '\\' && bp[1] == '\n') {
3759 ip->lineno++;
3760 copy_directive = 1;
3761 bp++;
3763 bp++;
3765 break;
3767 case '/':
3768 if (*bp == '\\' && bp[1] == '\n')
3769 newline_fix (bp);
3770 if (*bp == '*'
3771 || (cplusplus_comments && *bp == '/')) {
3772 U_CHAR *obp = bp - 1;
3773 ip->bufp = bp + 1;
3774 skip_to_end_of_comment (ip, &ip->lineno, 0);
3775 bp = ip->bufp;
3776 /* No need to copy the directive because of a comment at the end;
3777 just don't include the comment in the directive. */
3778 if (!put_out_comments) {
3779 U_CHAR *p;
3780 for (p = bp; *p == ' ' || *p == '\t'; p++)
3781 continue;
3782 if (*p == '\n') {
3783 bp = obp;
3784 goto endloop1;
3787 /* Don't remove the comments if -traditional. */
3788 if (! keep_comments)
3789 copy_directive++;
3791 break;
3793 case '\f':
3794 case '\r':
3795 case '\v':
3796 if (pedantic)
3797 pedwarn ("%s in preprocessing directive", char_name[c]);
3798 break;
3800 case '\n':
3801 --bp; /* Point to the newline */
3802 ip->bufp = bp;
3803 goto endloop1;
3806 ip->bufp = bp;
3808 endloop1:
3809 resume_p = ip->bufp;
3810 /* BP is the end of the directive.
3811 RESUME_P is the next interesting data after the directive.
3812 A comment may come between. */
3814 /* If a directive should be copied through, and -C was given,
3815 pass it through before removing comments. */
3816 if (!no_output && put_out_comments
3817 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
3818 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3819 : kt->type == T_PRAGMA)) {
3820 int len;
3822 /* Output directive name. */
3823 check_expand (op, kt->length + 2);
3824 /* Make sure # is at the start of a line */
3825 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3826 op->lineno++;
3827 *op->bufp++ = '\n';
3829 *op->bufp++ = '#';
3830 bcopy (kt->name, op->bufp, kt->length);
3831 op->bufp += kt->length;
3833 /* Output arguments. */
3834 len = (bp - buf);
3835 check_expand (op, len);
3836 bcopy (buf, (char *) op->bufp, len);
3837 op->bufp += len;
3838 /* Take account of any (escaped) newlines just output. */
3839 while (--len >= 0)
3840 if (buf[len] == '\n')
3841 op->lineno++;
3843 already_output = &junk;
3844 } /* Don't we need a newline or #line? */
3846 if (copy_directive) {
3847 register U_CHAR *xp = buf;
3848 /* Need to copy entire directive into temp buffer before dispatching */
3850 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3851 some slop */
3852 buf = cp;
3854 /* Copy to the new buffer, deleting comments
3855 and backslash-newlines (and whitespace surrounding the latter). */
3857 while (xp < bp) {
3858 register U_CHAR c = *xp++;
3859 *cp++ = c;
3861 switch (c) {
3862 case '\n':
3863 abort (); /* A bare newline should never part of the line. */
3864 break;
3866 /* <...> is special for #include. */
3867 case '<':
3868 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3869 break;
3870 while (xp < bp && c != '>') {
3871 c = *xp++;
3872 if (c == '\\' && xp < bp && *xp == '\n')
3873 xp++;
3874 else
3875 *cp++ = c;
3877 break;
3879 case '\\':
3880 if (*xp == '\n') {
3881 xp++;
3882 cp--;
3883 if (cp != buf && is_hor_space[cp[-1]]) {
3884 while (cp - 1 != buf && is_hor_space[cp[-2]])
3885 cp--;
3886 SKIP_WHITE_SPACE (xp);
3887 } else if (is_hor_space[*xp]) {
3888 *cp++ = *xp++;
3889 SKIP_WHITE_SPACE (xp);
3891 } else if (traditional && xp < bp) {
3892 *cp++ = *xp++;
3894 break;
3896 case '\'':
3897 case '\"':
3899 register U_CHAR *bp1
3900 = skip_quoted_string (xp - 1, bp, ip->lineno,
3901 NULL_PTR, NULL_PTR, NULL_PTR);
3902 while (xp != bp1)
3903 if (*xp == '\\') {
3904 if (*++xp != '\n')
3905 *cp++ = '\\';
3906 else
3907 xp++;
3908 } else
3909 *cp++ = *xp++;
3911 break;
3913 case '/':
3914 if (*xp == '*'
3915 || (cplusplus_comments && *xp == '/')) {
3916 ip->bufp = xp + 1;
3917 /* If we already copied the directive through,
3918 already_output != 0 prevents outputting comment now. */
3919 skip_to_end_of_comment (ip, already_output, 0);
3920 if (keep_comments)
3921 while (xp != ip->bufp)
3922 *cp++ = *xp++;
3923 /* Delete or replace the slash. */
3924 else if (traditional)
3925 cp--;
3926 else
3927 cp[-1] = ' ';
3928 xp = ip->bufp;
3933 /* Null-terminate the copy. */
3935 *cp = 0;
3936 } else
3937 cp = bp;
3939 ip->bufp = resume_p;
3941 /* Some directives should be written out for cc1 to process,
3942 just as if they were not defined. And sometimes we're copying
3943 directives through. */
3945 if (!no_output && already_output == 0
3946 && (kt->type == T_DEFINE ? dump_names <= dump_macros
3947 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3948 : kt->type == T_PRAGMA)) {
3949 int len;
3951 /* Output directive name. */
3952 check_expand (op, kt->length + 1);
3953 *op->bufp++ = '#';
3954 bcopy (kt->name, (char *) op->bufp, kt->length);
3955 op->bufp += kt->length;
3957 if (kt->type == T_DEFINE && dump_macros == dump_names) {
3958 /* Output `#define name' only. */
3959 U_CHAR *xp = buf;
3960 U_CHAR *yp;
3961 SKIP_WHITE_SPACE (xp);
3962 yp = xp;
3963 while (is_idchar[*xp]) xp++;
3964 len = (xp - yp);
3965 check_expand (op, len + 1);
3966 *op->bufp++ = ' ';
3967 bcopy (yp, (char *) op->bufp, len);
3968 } else {
3969 /* Output entire directive. */
3970 len = (cp - buf);
3971 check_expand (op, len);
3972 bcopy (buf, (char *) op->bufp, len);
3974 op->bufp += len;
3975 } /* Don't we need a newline or #line? */
3977 /* Call the appropriate directive handler. buf now points to
3978 either the appropriate place in the input buffer, or to
3979 the temp buffer if it was necessary to make one. cp
3980 points to the first char after the contents of the (possibly
3981 copied) directive, in either case. */
3982 (*kt->func) (buf, cp, op, kt);
3983 check_expand (op, ip->length - (ip->bufp - ip->buf));
3985 return 1;
3989 /* It is deliberate that we don't warn about undefined directives.
3990 That is the responsibility of cc1. */
3991 return 0;
3994 static struct tm *
3995 timestamp ()
3997 static struct tm *timebuf;
3998 if (!timebuf) {
3999 time_t t = time ((time_t *) 0);
4000 timebuf = localtime (&t);
4002 return timebuf;
4005 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4006 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4010 * expand things like __FILE__. Place the expansion into the output
4011 * buffer *without* rescanning.
4014 static void
4015 special_symbol (hp, op)
4016 HASHNODE *hp;
4017 FILE_BUF *op;
4019 char *buf;
4020 int i, len;
4021 int true_indepth;
4022 FILE_BUF *ip = NULL;
4023 struct tm *timebuf;
4025 int paren = 0; /* For special `defined' keyword */
4027 if (pcp_outfile && pcp_inside_if
4028 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4029 error ("Predefined macro `%s' used inside `#if' during precompilation",
4030 hp->name);
4032 for (i = indepth; i >= 0; i--)
4033 if (instack[i].fname != NULL) {
4034 ip = &instack[i];
4035 break;
4037 if (ip == NULL) {
4038 error ("cccp error: not in any file?!");
4039 return; /* the show must go on */
4042 switch (hp->type) {
4043 case T_FILE:
4044 case T_BASE_FILE:
4046 char *string;
4047 if (hp->type == T_FILE)
4048 string = ip->nominal_fname;
4049 else
4050 string = instack[0].nominal_fname;
4052 if (string)
4054 buf = (char *) alloca (3 + 4 * strlen (string));
4055 quote_string (buf, string);
4057 else
4058 buf = "\"\"";
4060 break;
4063 case T_INCLUDE_LEVEL:
4064 true_indepth = 0;
4065 for (i = indepth; i >= 0; i--)
4066 if (instack[i].fname != NULL)
4067 true_indepth++;
4069 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4070 sprintf (buf, "%d", true_indepth - 1);
4071 break;
4073 case T_VERSION:
4074 buf = (char *) alloca (3 + strlen (version_string));
4075 sprintf (buf, "\"%s\"", version_string);
4076 break;
4078 #ifndef NO_BUILTIN_SIZE_TYPE
4079 case T_SIZE_TYPE:
4080 buf = SIZE_TYPE;
4081 break;
4082 #endif
4084 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4085 case T_PTRDIFF_TYPE:
4086 buf = PTRDIFF_TYPE;
4087 break;
4088 #endif
4090 case T_WCHAR_TYPE:
4091 buf = wchar_type;
4092 break;
4094 case T_USER_LABEL_PREFIX_TYPE:
4095 buf = USER_LABEL_PREFIX;
4096 break;
4098 case T_REGISTER_PREFIX_TYPE:
4099 buf = REGISTER_PREFIX;
4100 break;
4102 case T_IMMEDIATE_PREFIX_TYPE:
4103 buf = IMMEDIATE_PREFIX;
4104 break;
4106 case T_CONST:
4107 buf = hp->value.cpval;
4108 #ifdef STDC_0_IN_SYSTEM_HEADERS
4109 if (ip->system_header_p
4110 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4111 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4112 buf = "0";
4113 #endif
4114 if (pcp_inside_if && pcp_outfile)
4115 /* Output a precondition for this macro use */
4116 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4117 break;
4119 case T_SPECLINE:
4120 buf = (char *) alloca (10);
4121 sprintf (buf, "%d", ip->lineno);
4122 break;
4124 case T_DATE:
4125 case T_TIME:
4126 buf = (char *) alloca (20);
4127 timebuf = timestamp ();
4128 if (hp->type == T_DATE)
4129 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4130 timebuf->tm_mday, timebuf->tm_year + 1900);
4131 else
4132 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4133 timebuf->tm_sec);
4134 break;
4136 case T_SPEC_DEFINED:
4137 buf = " 0 "; /* Assume symbol is not defined */
4138 ip = &instack[indepth];
4139 SKIP_WHITE_SPACE (ip->bufp);
4140 if (*ip->bufp == '(') {
4141 paren++;
4142 ip->bufp++; /* Skip over the paren */
4143 SKIP_WHITE_SPACE (ip->bufp);
4146 if (!is_idstart[*ip->bufp])
4147 goto oops;
4148 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4149 goto oops;
4150 if ((hp = lookup (ip->bufp, -1, -1))) {
4151 if (pcp_outfile && pcp_inside_if
4152 && (hp->type == T_CONST
4153 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4154 /* Output a precondition for this macro use. */
4155 fprintf (pcp_outfile, "#define %s\n", hp->name);
4156 buf = " 1 ";
4158 else
4159 if (pcp_outfile && pcp_inside_if) {
4160 /* Output a precondition for this macro use */
4161 U_CHAR *cp = ip->bufp;
4162 fprintf (pcp_outfile, "#undef ");
4163 while (is_idchar[*cp]) /* Ick! */
4164 fputc (*cp++, pcp_outfile);
4165 putc ('\n', pcp_outfile);
4167 while (is_idchar[*ip->bufp])
4168 ++ip->bufp;
4169 SKIP_WHITE_SPACE (ip->bufp);
4170 if (paren) {
4171 if (*ip->bufp != ')')
4172 goto oops;
4173 ++ip->bufp;
4175 break;
4177 oops:
4179 error ("`defined' without an identifier");
4180 break;
4182 default:
4183 error ("cccp error: invalid special hash type"); /* time for gdb */
4184 abort ();
4186 len = strlen (buf);
4187 check_expand (op, len);
4188 bcopy (buf, (char *) op->bufp, len);
4189 op->bufp += len;
4191 return;
4195 /* Routines to handle #directives */
4197 /* Handle #include and #import.
4198 This function expects to see "fname" or <fname> on the input. */
4200 static int
4201 do_include (buf, limit, op, keyword)
4202 U_CHAR *buf, *limit;
4203 FILE_BUF *op;
4204 struct directive *keyword;
4206 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4207 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4208 static int import_warning = 0;
4209 char *fname; /* Dynamically allocated fname buffer */
4210 char *pcftry;
4211 char *pcfname;
4212 char *fbeg, *fend; /* Beginning and end of fname */
4213 U_CHAR *fin;
4215 struct file_name_list *search_start = include; /* Chain of dirs to search */
4216 struct file_name_list *dsp; /* First in chain, if #include "..." */
4217 struct file_name_list *searchptr = 0;
4218 size_t flen;
4220 int f = -3; /* file number */
4221 struct include_file *inc = 0;
4223 int retried = 0; /* Have already tried macro
4224 expanding the include line*/
4225 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4226 #ifdef VMS
4227 int vaxc_include = 0; /* 1 for token without punctuation */
4228 #endif
4229 int pcf = -1;
4230 char *pcfbuf;
4231 char *pcfbuflimit;
4232 int pcfnum;
4234 if (pedantic && !instack[indepth].system_header_p)
4236 if (importing)
4237 pedwarn ("ANSI C does not allow `#import'");
4238 if (skip_dirs)
4239 pedwarn ("ANSI C does not allow `#include_next'");
4242 if (importing && warn_import && !inhibit_warnings
4243 && !instack[indepth].system_header_p && !import_warning) {
4244 import_warning = 1;
4245 warning ("using `#import' is not recommended");
4246 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4247 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4248 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4249 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4250 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4251 fprintf (stderr, " ... <real contents of file> ...\n");
4252 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4253 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4254 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4255 fprintf (stderr, "when it is equipped with such a conditional.\n");
4258 get_filename:
4260 fin = buf;
4261 SKIP_WHITE_SPACE (fin);
4262 /* Discard trailing whitespace so we can easily see
4263 if we have parsed all the significant chars we were given. */
4264 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4265 fbeg = fend = (char *) alloca (limit - fin);
4267 switch (*fin++) {
4268 case '\"':
4270 FILE_BUF *fp;
4271 /* Copy the operand text, concatenating the strings. */
4273 while (fin != limit) {
4274 while (fin != limit && *fin != '\"')
4275 *fend++ = *fin++;
4276 fin++;
4277 if (fin == limit)
4278 break;
4279 /* If not at the end, there had better be another string. */
4280 /* Skip just horiz space, and don't go past limit. */
4281 while (fin != limit && is_hor_space[*fin]) fin++;
4282 if (fin != limit && *fin == '\"')
4283 fin++;
4284 else
4285 goto fail;
4289 /* We have "filename". Figure out directory this source
4290 file is coming from and put it on the front of the list. */
4292 /* If -I- was specified, don't search current dir, only spec'd ones. */
4293 if (ignore_srcdir) break;
4295 for (fp = &instack[indepth]; fp >= instack; fp--)
4297 int n;
4298 char *nam;
4300 if ((nam = fp->nominal_fname) != NULL) {
4301 /* Found a named file. Figure out dir of the file,
4302 and put it in front of the search list. */
4303 dsp = ((struct file_name_list *)
4304 alloca (sizeof (struct file_name_list) + strlen (nam)));
4305 strcpy (dsp->fname, nam);
4306 simplify_filename (dsp->fname);
4307 nam = base_name (dsp->fname);
4308 *nam = 0;
4309 /* But for efficiency's sake, do not insert the dir
4310 if it matches the search list's first dir. */
4311 dsp->next = search_start;
4312 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4313 search_start = dsp;
4314 n = nam - dsp->fname;
4315 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4316 max_include_len = n + INCLUDE_LEN_FUDGE;
4318 dsp[0].got_name_map = 0;
4319 break;
4322 break;
4325 case '<':
4326 while (fin != limit && *fin != '>')
4327 *fend++ = *fin++;
4328 if (*fin == '>' && fin + 1 == limit) {
4329 angle_brackets = 1;
4330 /* If -I-, start with the first -I dir after the -I-. */
4331 search_start = first_bracket_include;
4332 break;
4334 goto fail;
4336 default:
4337 #ifdef VMS
4339 * Support '#include xyz' like VAX-C to allow for easy use of all the
4340 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4341 * code from case '<' is repeated here) and generates a warning.
4342 * (Note: macro expansion of `xyz' takes precedence.)
4344 if (retried && isalpha(*(U_CHAR *) (--fbeg))) {
4345 while (fin != limit && (!isspace(*fin)))
4346 *fend++ = *fin++;
4347 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4348 vaxc_include = 1;
4349 if (fin == limit) {
4350 angle_brackets = 1;
4351 /* If -I-, start with the first -I dir after the -I-. */
4352 search_start = first_bracket_include;
4353 break;
4356 #endif
4358 fail:
4359 if (retried) {
4360 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4361 return 0;
4362 } else {
4363 /* Expand buffer and then remove any newline markers.
4364 We can't just tell expand_to_temp_buffer to omit the markers,
4365 since it would put extra spaces in include file names. */
4366 FILE_BUF trybuf;
4367 U_CHAR *src;
4368 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4369 src = trybuf.buf;
4370 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4371 limit = buf;
4372 while (src != trybuf.bufp) {
4373 switch ((*limit++ = *src++)) {
4374 case '\n':
4375 limit--;
4376 src++;
4377 break;
4379 case '\'':
4380 case '\"':
4382 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4383 NULL_PTR, NULL_PTR, NULL_PTR);
4384 while (src != src1)
4385 *limit++ = *src++;
4387 break;
4390 *limit = 0;
4391 free (trybuf.buf);
4392 retried++;
4393 goto get_filename;
4397 /* For #include_next, skip in the search path
4398 past the dir in which the containing file was found. */
4399 if (skip_dirs) {
4400 FILE_BUF *fp;
4401 for (fp = &instack[indepth]; fp >= instack; fp--)
4402 if (fp->fname != NULL) {
4403 /* fp->dir is null if the containing file was specified
4404 with an absolute file name. In that case, don't skip anything. */
4405 if (fp->dir)
4406 search_start = fp->dir->next;
4407 break;
4411 *fend = 0;
4412 flen = simplify_filename (fbeg);
4414 if (flen == 0)
4416 error ("empty file name in `#%s'", keyword->name);
4417 return 0;
4420 /* Allocate this permanently, because it gets stored in the definitions
4421 of macros. */
4422 fname = xmalloc (max_include_len + flen + 1);
4423 /* + 1 above for terminating null. */
4425 system_include_depth += angle_brackets;
4427 /* If specified file name is absolute, just open it. */
4429 if (absolute_filename (fbeg)) {
4430 strcpy (fname, fbeg);
4431 f = open_include_file (fname, NULL_PTR, importing, &inc);
4432 } else {
4434 struct bypass_dir {
4435 struct bypass_dir *next;
4436 char *fname;
4437 struct file_name_list *searchptr;
4438 } **bypass_slot = 0;
4440 /* Search directory path, trying to open the file.
4441 Copy each filename tried into FNAME. */
4443 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4445 if (searchptr == first_bracket_include) {
4446 /* Go to bypass directory if we know we've seen this file before. */
4447 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4448 struct bypass_dir *p;
4449 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4450 INCLUDE_HASHSIZE)];
4451 for (p = *bypass_slot; p; p = p->next)
4452 if (!strcmp (fbeg, p->fname)) {
4453 searchptr = p->searchptr;
4454 bypass_slot = 0;
4455 break;
4459 strcpy (fname, searchptr->fname);
4460 strcat (fname, fbeg);
4461 #ifdef VMS
4462 /* Change this 1/2 Unix 1/2 VMS file specification into a
4463 full VMS file specification */
4464 if (searchptr->fname[0]) {
4465 /* Fix up the filename */
4466 hack_vms_include_specification (fname, vaxc_include);
4467 } else {
4468 /* This is a normal VMS filespec, so use it unchanged. */
4469 strcpy (fname, fbeg);
4470 /* if it's '#include filename', add the missing .h */
4471 if (vaxc_include && index(fname,'.')==NULL) {
4472 strcat (fname, ".h");
4475 #endif /* VMS */
4476 f = open_include_file (fname, searchptr, importing, &inc);
4477 if (f != -1) {
4478 if (bypass_slot && searchptr != first_bracket_include) {
4479 /* This is the first time we found this include file,
4480 and we found it after first_bracket_include.
4481 Record its location so that we can bypass to here next time. */
4482 struct bypass_dir *p
4483 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4484 p->next = *bypass_slot;
4485 p->fname = fname + strlen (searchptr->fname);
4486 p->searchptr = searchptr;
4487 *bypass_slot = p;
4489 break;
4491 #ifdef VMS
4492 /* Our VMS hacks can produce invalid filespecs, so don't worry
4493 about errors other than EACCES. */
4494 if (errno == EACCES)
4495 break;
4496 #else
4497 if (errno != ENOENT && errno != ENOTDIR)
4498 break;
4499 #endif
4504 if (f < 0) {
4506 if (f == -2) {
4507 /* The file was already included. */
4509 /* If generating dependencies and -MG was specified, we assume missing
4510 files are leaf files, living in the same directory as the source file
4511 or other similar place; these missing files may be generated from
4512 other files and may not exist yet (eg: y.tab.h). */
4513 } else if (print_deps_missing_files
4514 && (system_include_depth != 0) < print_deps)
4516 /* If it was requested as a system header file,
4517 then assume it belongs in the first place to look for such. */
4518 if (angle_brackets)
4520 if (search_start) {
4521 char *p = (char *) alloca (strlen (search_start->fname)
4522 + strlen (fbeg) + 1);
4523 strcpy (p, search_start->fname);
4524 strcat (p, fbeg);
4525 deps_output (p, ' ');
4528 else
4530 /* Otherwise, omit the directory, as if the file existed
4531 in the directory with the source. */
4532 deps_output (fbeg, ' ');
4535 /* If -M was specified, and this header file won't be added to the
4536 dependency list, then don't count this as an error, because we can
4537 still produce correct output. Otherwise, we can't produce correct
4538 output, because there may be dependencies we need inside the missing
4539 file, and we don't know what directory this missing file exists in. */
4540 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4541 warning ("No include path in which to find %s", fbeg);
4542 else if (f != -3)
4543 error_from_errno (fbeg);
4544 else
4545 error ("No include path in which to find %s", fbeg);
4547 } else {
4549 /* Actually process the file. */
4551 pcftry = (char *) alloca (strlen (fname) + 30);
4552 pcfbuf = 0;
4553 pcfnum = 0;
4555 if (!no_precomp)
4557 do {
4558 sprintf (pcftry, "%s%d", fname, pcfnum++);
4560 pcf = open (pcftry, O_RDONLY, 0666);
4561 if (pcf != -1)
4563 struct stat s;
4565 if (fstat (pcf, &s) != 0)
4566 pfatal_with_name (pcftry);
4567 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4568 || inc->st.st_dev != s.st_dev)
4570 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4571 /* Don't need it any more. */
4572 close (pcf);
4574 else
4576 /* Don't need it at all. */
4577 close (pcf);
4578 break;
4581 } while (pcf != -1 && !pcfbuf);
4584 /* Actually process the file */
4585 if (pcfbuf) {
4586 pcfname = xmalloc (strlen (pcftry) + 1);
4587 strcpy (pcfname, pcftry);
4588 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4589 (U_CHAR *) fname, op);
4591 else
4592 finclude (f, inc, op, is_system_include (fname), searchptr);
4595 system_include_depth -= angle_brackets;
4597 return 0;
4600 /* Return nonzero if the given FILENAME is an absolute pathname which
4601 designates a file within one of the known "system" include file
4602 directories. We assume here that if the given FILENAME looks like
4603 it is the name of a file which resides either directly in a "system"
4604 include file directory, or within any subdirectory thereof, then the
4605 given file must be a "system" include file. This function tells us
4606 if we should suppress pedantic errors/warnings for the given FILENAME.
4608 The value is 2 if the file is a C-language system header file
4609 for which C++ should (on most systems) assume `extern "C"'. */
4611 static int
4612 is_system_include (filename)
4613 register char *filename;
4615 struct file_name_list *searchptr;
4617 for (searchptr = first_system_include; searchptr;
4618 searchptr = searchptr->next)
4619 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4620 return searchptr->c_system_include_path + 1;
4621 return 0;
4624 /* Yield the non-directory suffix of a file name. */
4626 static char *
4627 base_name (fname)
4628 char *fname;
4630 char *s = fname;
4631 char *p;
4632 #if defined (__MSDOS__) || defined (_WIN32)
4633 if (isalpha (s[0]) && s[1] == ':') s += 2;
4634 #endif
4635 #ifdef VMS
4636 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4637 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4638 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4639 if (s != fname)
4640 return s;
4641 #endif
4642 if ((p = rindex (s, '/'))) s = p + 1;
4643 #ifdef DIR_SEPARATOR
4644 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4645 #endif
4646 return s;
4649 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4651 static int
4652 absolute_filename (filename)
4653 char *filename;
4655 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4656 if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4657 #endif
4658 #if defined (__CYGWIN32__)
4659 /* At present, any path that begins with a drive spec is absolute. */
4660 if (isalpha (filename[0]) && filename[1] == ':') return 1;
4661 #endif
4662 if (filename[0] == '/') return 1;
4663 #ifdef DIR_SEPARATOR
4664 if (filename[0] == DIR_SEPARATOR) return 1;
4665 #endif
4666 return 0;
4669 /* Remove unnecessary characters from FILENAME in place,
4670 to avoid unnecessary filename aliasing.
4671 Return the length of the resulting string.
4673 Do only the simplifications allowed by Posix.
4674 It is OK to miss simplifications on non-Posix hosts,
4675 since this merely leads to suboptimal results. */
4677 static size_t
4678 simplify_filename (filename)
4679 char *filename;
4681 register char *from = filename;
4682 register char *to = filename;
4683 char *to0;
4685 /* Remove redundant initial /s. */
4686 if (*from == '/') {
4687 *to++ = '/';
4688 if (*++from == '/') {
4689 if (*++from == '/') {
4690 /* 3 or more initial /s are equivalent to 1 /. */
4691 while (*++from == '/')
4692 continue;
4693 } else {
4694 /* On some hosts // differs from /; Posix allows this. */
4695 static int slashslash_vs_slash;
4696 if (slashslash_vs_slash == 0) {
4697 struct stat s1, s2;
4698 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4699 && INO_T_EQ (s1.st_ino, s2.st_ino)
4700 && s1.st_dev == s2.st_dev)
4701 ? 1 : -1);
4703 if (slashslash_vs_slash < 0)
4704 *to++ = '/';
4708 to0 = to;
4710 for (;;) {
4711 if (from[0] == '.' && from[1] == '/')
4712 from += 2;
4713 else {
4714 /* Copy this component and trailing /, if any. */
4715 while ((*to++ = *from++) != '/') {
4716 if (!to[-1]) {
4717 /* Trim . component at end of nonempty name. */
4718 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4720 /* Trim unnecessary trailing /s. */
4721 while (to0 < --to && to[-1] == '/')
4722 continue;
4724 *to = 0;
4725 return to - filename;
4730 /* Skip /s after a /. */
4731 while (*from == '/')
4732 from++;
4736 /* The file_name_map structure holds a mapping of file names for a
4737 particular directory. This mapping is read from the file named
4738 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4739 map filenames on a file system with severe filename restrictions,
4740 such as DOS. The format of the file name map file is just a series
4741 of lines with two tokens on each line. The first token is the name
4742 to map, and the second token is the actual name to use. */
4744 struct file_name_map
4746 struct file_name_map *map_next;
4747 char *map_from;
4748 char *map_to;
4751 #define FILE_NAME_MAP_FILE "header.gcc"
4753 /* Read a space delimited string of unlimited length from a stdio
4754 file. */
4756 static char *
4757 read_filename_string (ch, f)
4758 int ch;
4759 FILE *f;
4761 char *alloc, *set;
4762 int len;
4764 len = 20;
4765 set = alloc = xmalloc (len + 1);
4766 if (! is_space[ch])
4768 *set++ = ch;
4769 while ((ch = getc (f)) != EOF && ! is_space[ch])
4771 if (set - alloc == len)
4773 len *= 2;
4774 alloc = xrealloc (alloc, len + 1);
4775 set = alloc + len / 2;
4777 *set++ = ch;
4780 *set = '\0';
4781 ungetc (ch, f);
4782 return alloc;
4785 /* Read the file name map file for DIRNAME.
4786 If DIRNAME is empty, read the map file for the working directory;
4787 otherwise DIRNAME must end in '/'. */
4789 static struct file_name_map *
4790 read_name_map (dirname)
4791 char *dirname;
4793 /* This structure holds a linked list of file name maps, one per
4794 directory. */
4795 struct file_name_map_list
4797 struct file_name_map_list *map_list_next;
4798 char *map_list_name;
4799 struct file_name_map *map_list_map;
4801 static struct file_name_map_list *map_list;
4802 register struct file_name_map_list *map_list_ptr;
4803 char *name;
4804 FILE *f;
4805 size_t dirlen;
4807 for (map_list_ptr = map_list; map_list_ptr;
4808 map_list_ptr = map_list_ptr->map_list_next)
4809 if (! strcmp (map_list_ptr->map_list_name, dirname))
4810 return map_list_ptr->map_list_map;
4812 map_list_ptr = ((struct file_name_map_list *)
4813 xmalloc (sizeof (struct file_name_map_list)));
4814 map_list_ptr->map_list_name = savestring (dirname);
4815 map_list_ptr->map_list_map = NULL;
4817 dirlen = strlen (dirname);
4818 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4819 strcpy (name, dirname);
4820 strcat (name, FILE_NAME_MAP_FILE);
4821 f = fopen (name, "r");
4822 if (!f)
4823 map_list_ptr->map_list_map = NULL;
4824 else
4826 int ch;
4828 while ((ch = getc (f)) != EOF)
4830 char *from, *to;
4831 struct file_name_map *ptr;
4832 size_t tolen;
4834 if (is_space[ch])
4835 continue;
4836 from = read_filename_string (ch, f);
4837 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4839 to = read_filename_string (ch, f);
4841 simplify_filename (from);
4842 tolen = simplify_filename (to);
4844 ptr = ((struct file_name_map *)
4845 xmalloc (sizeof (struct file_name_map)));
4846 ptr->map_from = from;
4848 /* Make the real filename absolute. */
4849 if (absolute_filename (to))
4850 ptr->map_to = to;
4851 else
4853 ptr->map_to = xmalloc (dirlen + tolen + 1);
4854 strcpy (ptr->map_to, dirname);
4855 strcat (ptr->map_to, to);
4856 free (to);
4859 ptr->map_next = map_list_ptr->map_list_map;
4860 map_list_ptr->map_list_map = ptr;
4862 while ((ch = getc (f)) != '\n')
4863 if (ch == EOF)
4864 break;
4866 fclose (f);
4869 map_list_ptr->map_list_next = map_list;
4870 map_list = map_list_ptr;
4872 return map_list_ptr->map_list_map;
4875 /* Try to open include file FILENAME. SEARCHPTR is the directory
4876 being tried from the include file search path.
4877 IMPORTING is "" if we are importing, null otherwise.
4878 Return -2 if found, either a matching name or a matching inode.
4879 Otherwise, open the file and return a file descriptor if successful
4880 or -1 if unsuccessful.
4881 Unless unsuccessful, put a descriptor of the included file into *PINC.
4882 This function maps filenames on file systems based on information read by
4883 read_name_map. */
4885 static int
4886 open_include_file (filename, searchptr, importing, pinc)
4887 char *filename;
4888 struct file_name_list *searchptr;
4889 U_CHAR *importing;
4890 struct include_file **pinc;
4892 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
4893 int fd = -2;
4895 /* Look up FNAME in include_hashtab. */
4896 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4897 strlen (fname),
4898 INCLUDE_HASHSIZE)];
4899 struct include_file *inc, *head = *phead;
4900 for (inc = head; inc; inc = inc->next)
4901 if (!strcmp (fname, inc->fname))
4902 break;
4904 if (!inc
4905 || ! inc->control_macro
4906 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4908 fd = open (fname, O_RDONLY, 0);
4910 if (fd < 0)
4911 return fd;
4913 if (!inc) {
4914 /* FNAME was not in include_hashtab; insert a new entry. */
4915 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4916 inc->next = head;
4917 inc->fname = fname;
4918 inc->control_macro = 0;
4919 inc->deps_output = 0;
4920 if (fstat (fd, &inc->st) != 0)
4921 pfatal_with_name (fname);
4922 *phead = inc;
4924 /* Look for another file with the same inode and device. */
4925 if (lookup_ino_include (inc)
4926 && inc->control_macro
4927 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4928 close (fd);
4929 fd = -2;
4933 /* For -M, add this file to the dependencies. */
4934 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4935 inc->deps_output = 1;
4936 deps_output (fname, ' ');
4939 /* Handle -H option. */
4940 if (print_include_names)
4941 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4944 if (importing)
4945 inc->control_macro = importing;
4947 *pinc = inc;
4948 return fd;
4951 /* Return the remapped name of the the include file FILENAME.
4952 SEARCHPTR is the directory being tried from the include file path. */
4954 static char *
4955 remap_include_file (filename, searchptr)
4956 char *filename;
4957 struct file_name_list *searchptr;
4959 register struct file_name_map *map;
4960 register char *from;
4962 if (searchptr)
4964 if (! searchptr->got_name_map)
4966 searchptr->name_map = read_name_map (searchptr->fname);
4967 searchptr->got_name_map = 1;
4970 /* Check the mapping for the directory we are using. */
4971 from = filename + strlen (searchptr->fname);
4972 for (map = searchptr->name_map; map; map = map->map_next)
4973 if (! strcmp (map->map_from, from))
4974 return map->map_to;
4977 from = base_name (filename);
4979 if (from != filename || !searchptr)
4981 /* Try to find a mapping file for the particular directory we are
4982 looking in. Thus #include <sys/types.h> will look up sys/types.h
4983 in /usr/include/header.gcc and look up types.h in
4984 /usr/include/sys/header.gcc. */
4986 char *dir = (char *) alloca (from - filename + 1);
4987 bcopy (filename, dir, from - filename);
4988 dir[from - filename] = '\0';
4990 for (map = read_name_map (dir); map; map = map->map_next)
4991 if (! strcmp (map->map_from, from))
4992 return map->map_to;
4995 return filename;
4998 /* Insert INC into the include file table, hashed by device and inode number.
4999 If a file with different name but same dev+ino was already in the table,
5000 return 1 and set INC's control macro to the already-known macro. */
5002 static int
5003 lookup_ino_include (inc)
5004 struct include_file *inc;
5006 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5007 % INCLUDE_HASHSIZE);
5008 struct include_file *i = include_ino_hashtab[hash];
5009 inc->next_ino = i;
5010 include_ino_hashtab[hash] = inc;
5012 for (; i; i = i->next_ino)
5013 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5014 && inc->st.st_dev == i->st.st_dev) {
5015 inc->control_macro = i->control_macro;
5016 return 1;
5019 return 0;
5022 /* Process file descriptor F, which corresponds to include file INC,
5023 with output to OP.
5024 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5025 "system" include directories (as decided by the `is_system_include'
5026 function above).
5027 DIRPTR is the link in the dir path through which this file was found,
5028 or 0 if the file name was absolute. */
5030 static void
5031 finclude (f, inc, op, system_header_p, dirptr)
5032 int f;
5033 struct include_file *inc;
5034 FILE_BUF *op;
5035 int system_header_p;
5036 struct file_name_list *dirptr;
5038 char *fname = inc->fname;
5039 int i;
5040 FILE_BUF *fp; /* For input stack frame */
5041 int missing_newline = 0;
5043 CHECK_DEPTH (return;);
5045 fp = &instack[indepth + 1];
5046 bzero ((char *) fp, sizeof (FILE_BUF));
5047 fp->nominal_fname = fp->fname = fname;
5048 fp->inc = inc;
5049 fp->length = 0;
5050 fp->lineno = 1;
5051 fp->if_stack = if_stack;
5052 fp->system_header_p = system_header_p;
5053 fp->dir = dirptr;
5055 if (S_ISREG (inc->st.st_mode)) {
5056 size_t s = (size_t) inc->st.st_size;
5057 if (s != inc->st.st_size || s + 2 < s)
5058 memory_full ();
5059 fp->buf = (U_CHAR *) xmalloc (s + 2);
5060 fp->bufp = fp->buf;
5062 /* Read the file contents, knowing that s is an upper bound
5063 on the number of bytes we can read. */
5064 fp->length = safe_read (f, (char *) fp->buf, s);
5065 if (fp->length < 0) goto nope;
5067 else if (S_ISDIR (inc->st.st_mode)) {
5068 error ("directory `%s' specified in #include", fname);
5069 close (f);
5070 return;
5071 } else {
5072 /* Cannot count its file size before reading.
5073 First read the entire file into heap and
5074 copy them into buffer on stack. */
5076 int bsize = 2000;
5077 int st_size = 0;
5079 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5081 for (;;) {
5082 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5083 if (i < 0)
5084 goto nope; /* error! */
5085 st_size += i;
5086 if (st_size != bsize)
5087 break; /* End of file */
5088 bsize *= 2;
5089 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5091 fp->bufp = fp->buf;
5092 fp->length = st_size;
5095 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5096 /* Backslash-newline at end is not good enough. */
5097 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5098 fp->buf[fp->length++] = '\n';
5099 missing_newline = 1;
5101 fp->buf[fp->length] = '\0';
5103 /* Close descriptor now, so nesting does not use lots of descriptors. */
5104 close (f);
5106 /* Must do this before calling trigraph_pcp, so that the correct file name
5107 will be printed in warning messages. */
5109 indepth++;
5110 input_file_stack_tick++;
5112 if (!no_trigraphs)
5113 trigraph_pcp (fp);
5115 output_line_directive (fp, op, 0, enter_file);
5116 rescan (op, 0);
5118 if (missing_newline)
5119 fp->lineno--;
5121 if (pedantic && missing_newline)
5122 pedwarn ("file does not end in newline");
5124 indepth--;
5125 input_file_stack_tick++;
5126 output_line_directive (&instack[indepth], op, 0, leave_file);
5127 free (fp->buf);
5128 return;
5130 nope:
5132 perror_with_name (fname);
5133 close (f);
5134 free (fp->buf);
5137 /* Record that inclusion of the include file INC
5138 should be controlled by the macro named MACRO_NAME.
5139 This means that trying to include the file again
5140 will do something if that macro is defined. */
5142 static void
5143 record_control_macro (inc, macro_name)
5144 struct include_file *inc;
5145 U_CHAR *macro_name;
5147 if (!inc->control_macro || inc->control_macro[0])
5148 inc->control_macro = macro_name;
5151 /* Load the specified precompiled header into core, and verify its
5152 preconditions. PCF indicates the file descriptor to read, which must
5153 be a regular file. *ST is its file status.
5154 FNAME indicates the file name of the original header.
5155 *LIMIT will be set to an address one past the end of the file.
5156 If the preconditions of the file are not satisfied, the buffer is
5157 freed and we return 0. If the preconditions are satisfied, return
5158 the address of the buffer following the preconditions. The buffer, in
5159 this case, should never be freed because various pieces of it will
5160 be referred to until all precompiled strings are output at the end of
5161 the run. */
5163 static char *
5164 check_precompiled (pcf, st, fname, limit)
5165 int pcf;
5166 struct stat *st;
5167 char *fname;
5168 char **limit;
5170 int length = 0;
5171 char *buf;
5172 char *cp;
5174 if (pcp_outfile)
5175 return 0;
5177 if (S_ISREG (st->st_mode))
5179 size_t s = (size_t) st->st_size;
5180 if (s != st->st_size || s + 2 < s)
5181 memory_full ();
5182 buf = xmalloc (s + 2);
5183 length = safe_read (pcf, buf, s);
5184 if (length < 0)
5185 goto nope;
5187 else
5188 abort ();
5190 if (length > 0 && buf[length-1] != '\n')
5191 buf[length++] = '\n';
5192 buf[length] = '\0';
5194 *limit = buf + length;
5196 /* File is in core. Check the preconditions. */
5197 if (!check_preconditions (buf))
5198 goto nope;
5199 for (cp = buf; *cp; cp++)
5201 #ifdef DEBUG_PCP
5202 fprintf (stderr, "Using preinclude %s\n", fname);
5203 #endif
5204 return cp + 1;
5206 nope:
5207 #ifdef DEBUG_PCP
5208 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5209 #endif
5210 free (buf);
5211 return 0;
5214 /* PREC (null terminated) points to the preconditions of a
5215 precompiled header. These are a series of #define and #undef
5216 lines which must match the current contents of the hash
5217 table. */
5219 static int
5220 check_preconditions (prec)
5221 char *prec;
5223 MACRODEF mdef;
5224 char *lineend;
5226 while (*prec) {
5227 lineend = index (prec, '\n');
5229 if (*prec++ != '#') {
5230 error ("Bad format encountered while reading precompiled file");
5231 return 0;
5233 if (!strncmp (prec, "define", 6)) {
5234 HASHNODE *hp;
5236 prec += 6;
5237 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5239 if (mdef.defn == 0)
5240 abort ();
5242 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5243 || (hp->type != T_MACRO && hp->type != T_CONST)
5244 || (hp->type == T_MACRO
5245 && !compare_defs (mdef.defn, hp->value.defn)
5246 && (mdef.defn->length != 2
5247 || mdef.defn->expansion[0] != '\n'
5248 || mdef.defn->expansion[1] != ' ')))
5249 return 0;
5250 } else if (!strncmp (prec, "undef", 5)) {
5251 char *name;
5252 int len;
5254 prec += 5;
5255 while (is_hor_space[(U_CHAR) *prec])
5256 prec++;
5257 name = prec;
5258 while (is_idchar[(U_CHAR) *prec])
5259 prec++;
5260 len = prec - name;
5262 if (lookup ((U_CHAR *) name, len, -1))
5263 return 0;
5264 } else {
5265 error ("Bad format encountered while reading precompiled file");
5266 return 0;
5268 prec = lineend + 1;
5270 /* They all passed successfully */
5271 return 1;
5274 /* Process the main body of a precompiled file. BUF points to the
5275 string section of the file, following the preconditions. LIMIT is one
5276 character past the end. NAME is the name of the file being read
5277 in. OP is the main output buffer. */
5279 static void
5280 pcfinclude (buf, limit, name, op)
5281 U_CHAR *buf, *limit, *name;
5282 FILE_BUF *op;
5284 FILE_BUF tmpbuf;
5285 int nstrings;
5286 U_CHAR *cp = buf;
5288 /* First in the file comes 4 bytes indicating the number of strings, */
5289 /* in network byte order. (MSB first). */
5290 nstrings = *cp++;
5291 nstrings = (nstrings << 8) | *cp++;
5292 nstrings = (nstrings << 8) | *cp++;
5293 nstrings = (nstrings << 8) | *cp++;
5295 /* Looping over each string... */
5296 while (nstrings--) {
5297 U_CHAR *string_start;
5298 U_CHAR *endofthiskey;
5299 STRINGDEF *str;
5300 int nkeys;
5302 /* Each string starts with a STRINGDEF structure (str), followed */
5303 /* by the text of the string (string_start) */
5305 /* First skip to a longword boundary */
5306 /* ??? Why a 4-byte boundary? On all machines? */
5307 /* NOTE: This works correctly even if size_t
5308 is narrower than a pointer.
5309 Do not try risky measures here to get another type to use!
5310 Do not include stddef.h--it will fail! */
5311 if ((size_t) cp & 3)
5312 cp += 4 - ((size_t) cp & 3);
5314 /* Now get the string. */
5315 str = (STRINGDEF *) (GENERIC_PTR) cp;
5316 string_start = cp += sizeof (STRINGDEF);
5318 for (; *cp; cp++) /* skip the string */
5321 /* We need to macro expand the string here to ensure that the
5322 proper definition environment is in place. If it were only
5323 expanded when we find out it is needed, macros necessary for
5324 its proper expansion might have had their definitions changed. */
5325 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5326 /* Lineno is already set in the precompiled file */
5327 str->contents = tmpbuf.buf;
5328 str->len = tmpbuf.length;
5329 str->writeflag = 0;
5330 str->filename = name;
5331 str->output_mark = outbuf.bufp - outbuf.buf;
5333 str->chain = 0;
5334 *stringlist_tailp = str;
5335 stringlist_tailp = &str->chain;
5337 /* Next comes a fourbyte number indicating the number of keys
5338 for this string. */
5339 nkeys = *cp++;
5340 nkeys = (nkeys << 8) | *cp++;
5341 nkeys = (nkeys << 8) | *cp++;
5342 nkeys = (nkeys << 8) | *cp++;
5344 /* If this number is -1, then the string is mandatory. */
5345 if (nkeys == -1)
5346 str->writeflag = 1;
5347 else
5348 /* Otherwise, for each key, */
5349 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5350 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5351 HASHNODE *hp;
5353 /* It starts with a KEYDEF structure */
5354 cp += sizeof (KEYDEF);
5356 /* Find the end of the key. At the end of this for loop we
5357 advance CP to the start of the next key using this variable. */
5358 endofthiskey = cp + strlen ((char *) cp);
5359 kp->str = str;
5361 /* Expand the key, and enter it into the hash table. */
5362 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5363 tmpbuf.bufp = tmpbuf.buf;
5365 while (is_hor_space[*tmpbuf.bufp])
5366 tmpbuf.bufp++;
5367 if (!is_idstart[*tmpbuf.bufp]
5368 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5369 str->writeflag = 1;
5370 continue;
5373 hp = lookup (tmpbuf.bufp, -1, -1);
5374 if (hp == NULL) {
5375 kp->chain = 0;
5376 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5378 else if (hp->type == T_PCSTRING) {
5379 kp->chain = hp->value.keydef;
5380 hp->value.keydef = kp;
5382 else
5383 str->writeflag = 1;
5386 /* This output_line_directive serves to switch us back to the current
5387 input file in case some of these strings get output (which will
5388 result in line directives for the header file being output). */
5389 output_line_directive (&instack[indepth], op, 0, enter_file);
5392 /* Called from rescan when it hits a key for strings. Mark them all
5393 used and clean up. */
5395 static void
5396 pcstring_used (hp)
5397 HASHNODE *hp;
5399 KEYDEF *kp;
5401 for (kp = hp->value.keydef; kp; kp = kp->chain)
5402 kp->str->writeflag = 1;
5403 delete_macro (hp);
5406 /* Write the output, interspersing precompiled strings in their
5407 appropriate places. */
5409 static void
5410 write_output ()
5412 STRINGDEF *next_string;
5413 U_CHAR *cur_buf_loc;
5414 int line_directive_len = 80;
5415 char *line_directive = xmalloc (line_directive_len);
5416 int len;
5418 /* In each run through the loop, either cur_buf_loc ==
5419 next_string_loc, in which case we print a series of strings, or
5420 it is less than next_string_loc, in which case we write some of
5421 the buffer. */
5422 cur_buf_loc = outbuf.buf;
5423 next_string = stringlist;
5425 while (cur_buf_loc < outbuf.bufp || next_string) {
5426 if (next_string
5427 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5428 if (next_string->writeflag) {
5429 len = 4 * strlen ((char *) next_string->filename) + 32;
5430 while (len > line_directive_len)
5431 line_directive = xrealloc (line_directive,
5432 line_directive_len *= 2);
5433 sprintf (line_directive, "\n# %d ", next_string->lineno);
5434 strcpy (quote_string (line_directive + strlen (line_directive),
5435 (char *) next_string->filename),
5436 "\n");
5437 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5438 safe_write (fileno (stdout),
5439 (char *) next_string->contents, next_string->len);
5441 next_string = next_string->chain;
5443 else {
5444 len = (next_string
5445 ? (next_string->output_mark
5446 - (cur_buf_loc - outbuf.buf))
5447 : outbuf.bufp - cur_buf_loc);
5449 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5450 cur_buf_loc += len;
5453 free (line_directive);
5456 /* Pass a directive through to the output file.
5457 BUF points to the contents of the directive, as a contiguous string.
5458 LIMIT points to the first character past the end of the directive.
5459 KEYWORD is the keyword-table entry for the directive. */
5461 static void
5462 pass_thru_directive (buf, limit, op, keyword)
5463 U_CHAR *buf, *limit;
5464 FILE_BUF *op;
5465 struct directive *keyword;
5467 register unsigned keyword_length = keyword->length;
5469 check_expand (op, 1 + keyword_length + (limit - buf));
5470 *op->bufp++ = '#';
5471 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5472 op->bufp += keyword_length;
5473 if (limit != buf && buf[0] != ' ')
5474 *op->bufp++ = ' ';
5475 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5476 op->bufp += (limit - buf);
5477 #if 0
5478 *op->bufp++ = '\n';
5479 /* Count the line we have just made in the output,
5480 to get in sync properly. */
5481 op->lineno++;
5482 #endif
5485 /* The arglist structure is built by do_define to tell
5486 collect_definition where the argument names begin. That
5487 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5488 would contain pointers to the strings x, y, and z.
5489 Collect_definition would then build a DEFINITION node,
5490 with reflist nodes pointing to the places x, y, and z had
5491 appeared. So the arglist is just convenience data passed
5492 between these two routines. It is not kept around after
5493 the current #define has been processed and entered into the
5494 hash table. */
5496 struct arglist {
5497 struct arglist *next;
5498 U_CHAR *name;
5499 int length;
5500 int argno;
5501 char rest_args;
5504 /* Create a DEFINITION node from a #define directive. Arguments are
5505 as for do_define. */
5507 static MACRODEF
5508 create_definition (buf, limit, op)
5509 U_CHAR *buf, *limit;
5510 FILE_BUF *op;
5512 U_CHAR *bp; /* temp ptr into input buffer */
5513 U_CHAR *symname; /* remember where symbol name starts */
5514 int sym_length; /* and how long it is */
5515 int line = instack[indepth].lineno;
5516 char *file = instack[indepth].nominal_fname;
5517 int rest_args = 0;
5519 DEFINITION *defn;
5520 int arglengths = 0; /* Accumulate lengths of arg names
5521 plus number of args. */
5522 MACRODEF mdef;
5524 bp = buf;
5526 while (is_hor_space[*bp])
5527 bp++;
5529 symname = bp; /* remember where it starts */
5530 sym_length = check_macro_name (bp, "macro");
5531 bp += sym_length;
5533 /* Lossage will occur if identifiers or control keywords are broken
5534 across lines using backslash. This is not the right place to take
5535 care of that. */
5537 if (*bp == '(') {
5538 struct arglist *arg_ptrs = NULL;
5539 int argno = 0;
5541 bp++; /* skip '(' */
5542 SKIP_WHITE_SPACE (bp);
5544 /* Loop over macro argument names. */
5545 while (*bp != ')') {
5546 struct arglist *temp;
5548 temp = (struct arglist *) alloca (sizeof (struct arglist));
5549 temp->name = bp;
5550 temp->next = arg_ptrs;
5551 temp->argno = argno++;
5552 temp->rest_args = 0;
5553 arg_ptrs = temp;
5555 if (rest_args)
5556 pedwarn ("another parameter follows `%s'",
5557 rest_extension);
5559 if (!is_idstart[*bp])
5560 pedwarn ("invalid character in macro parameter name");
5562 /* Find the end of the arg name. */
5563 while (is_idchar[*bp]) {
5564 bp++;
5565 /* do we have a "special" rest-args extension here? */
5566 if (limit - bp > REST_EXTENSION_LENGTH
5567 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5568 if (pedantic && !instack[indepth].system_header_p)
5569 pedwarn ("ANSI C does not allow macro with variable arguments");
5570 rest_args = 1;
5571 temp->rest_args = 1;
5572 break;
5575 temp->length = bp - temp->name;
5576 if (rest_args == 1)
5577 bp += REST_EXTENSION_LENGTH;
5578 arglengths += temp->length + 2;
5579 SKIP_WHITE_SPACE (bp);
5580 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5581 error ("badly punctuated parameter list in `#define'");
5582 goto nope;
5584 if (*bp == ',') {
5585 bp++;
5586 SKIP_WHITE_SPACE (bp);
5587 /* A comma at this point can only be followed by an identifier. */
5588 if (!is_idstart[*bp]) {
5589 error ("badly punctuated parameter list in `#define'");
5590 goto nope;
5593 if (bp >= limit) {
5594 error ("unterminated parameter list in `#define'");
5595 goto nope;
5598 struct arglist *otemp;
5600 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5601 if (temp->length == otemp->length
5602 && bcmp (temp->name, otemp->name, temp->length) == 0) {
5603 error ("duplicate argument name `%.*s' in `#define'",
5604 temp->length, temp->name);
5605 goto nope;
5610 ++bp; /* skip paren */
5611 SKIP_WHITE_SPACE (bp);
5612 /* now everything from bp before limit is the definition. */
5613 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5614 defn->rest_args = rest_args;
5616 /* Now set defn->args.argnames to the result of concatenating
5617 the argument names in reverse order
5618 with comma-space between them. */
5619 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5621 struct arglist *temp;
5622 int i = 0;
5623 for (temp = arg_ptrs; temp; temp = temp->next) {
5624 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5625 i += temp->length;
5626 if (temp->next != 0) {
5627 defn->args.argnames[i++] = ',';
5628 defn->args.argnames[i++] = ' ';
5631 defn->args.argnames[i] = 0;
5633 } else {
5634 /* Simple expansion or empty definition. */
5636 if (bp < limit)
5638 if (is_hor_space[*bp]) {
5639 bp++;
5640 SKIP_WHITE_SPACE (bp);
5641 } else if (sym_length) {
5642 switch (*bp) {
5643 case '!': case '"': case '#': case '%': case '&': case '\'':
5644 case ')': case '*': case '+': case ',': case '-': case '.':
5645 case '/': case ':': case ';': case '<': case '=': case '>':
5646 case '?': case '[': case '\\': case ']': case '^': case '{':
5647 case '|': case '}': case '~':
5648 warning ("missing white space after `#define %.*s'",
5649 sym_length, symname);
5650 break;
5652 default:
5653 pedwarn ("missing white space after `#define %.*s'",
5654 sym_length, symname);
5655 break;
5659 /* Now everything from bp before limit is the definition. */
5660 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5661 defn->args.argnames = (U_CHAR *) "";
5664 defn->line = line;
5665 defn->file = file;
5667 /* OP is null if this is a predefinition */
5668 defn->predefined = !op;
5669 mdef.defn = defn;
5670 mdef.symnam = symname;
5671 mdef.symlen = sym_length;
5673 return mdef;
5675 nope:
5676 mdef.defn = 0;
5677 return mdef;
5680 /* Process a #define directive.
5681 BUF points to the contents of the #define directive, as a contiguous string.
5682 LIMIT points to the first character past the end of the definition.
5683 KEYWORD is the keyword-table entry for #define. */
5685 static int
5686 do_define (buf, limit, op, keyword)
5687 U_CHAR *buf, *limit;
5688 FILE_BUF *op;
5689 struct directive *keyword;
5691 int hashcode;
5692 MACRODEF mdef;
5694 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5695 if (pcp_outfile && op)
5696 pass_thru_directive (buf, limit, op, keyword);
5698 mdef = create_definition (buf, limit, op);
5699 if (mdef.defn == 0)
5700 goto nope;
5702 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5705 HASHNODE *hp;
5706 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5707 int ok = 0;
5708 /* Redefining a precompiled key is ok. */
5709 if (hp->type == T_PCSTRING)
5710 ok = 1;
5711 /* Redefining a macro is ok if the definitions are the same. */
5712 else if (hp->type == T_MACRO)
5713 ok = ! compare_defs (mdef.defn, hp->value.defn);
5714 /* Redefining a constant is ok with -D. */
5715 else if (hp->type == T_CONST)
5716 ok = ! done_initializing;
5717 /* Print the warning if it's not ok. */
5718 if (!ok) {
5719 /* If we are passing through #define and #undef directives, do
5720 that for this re-definition now. */
5721 if (debug_output && op)
5722 pass_thru_directive (buf, limit, op, keyword);
5724 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5725 if (hp->type == T_MACRO)
5726 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5727 "this is the location of the previous definition");
5729 /* Replace the old definition. */
5730 hp->type = T_MACRO;
5731 hp->value.defn = mdef.defn;
5732 } else {
5733 /* If we are passing through #define and #undef directives, do
5734 that for this new definition now. */
5735 if (debug_output && op)
5736 pass_thru_directive (buf, limit, op, keyword);
5737 install (mdef.symnam, mdef.symlen, T_MACRO,
5738 (char *) mdef.defn, hashcode);
5742 return 0;
5744 nope:
5746 return 1;
5749 /* Check a purported macro name SYMNAME, and yield its length.
5750 USAGE is the kind of name this is intended for. */
5752 static int
5753 check_macro_name (symname, usage)
5754 U_CHAR *symname;
5755 char *usage;
5757 U_CHAR *p;
5758 int sym_length;
5760 for (p = symname; is_idchar[*p]; p++)
5762 sym_length = p - symname;
5763 if (sym_length == 0
5764 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5765 error ("invalid %s name", usage);
5766 else if (!is_idstart[*symname]
5767 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5768 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5769 return sym_length;
5772 /* Return zero if two DEFINITIONs are isomorphic. */
5774 static int
5775 compare_defs (d1, d2)
5776 DEFINITION *d1, *d2;
5778 register struct reflist *a1, *a2;
5779 register U_CHAR *p1 = d1->expansion;
5780 register U_CHAR *p2 = d2->expansion;
5781 int first = 1;
5783 if (d1->nargs != d2->nargs)
5784 return 1;
5785 if (pedantic
5786 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5787 return 1;
5788 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5789 a1 = a1->next, a2 = a2->next) {
5790 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5791 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5792 || a1->argno != a2->argno
5793 || a1->stringify != a2->stringify
5794 || a1->raw_before != a2->raw_before
5795 || a1->raw_after != a2->raw_after)
5796 return 1;
5797 first = 0;
5798 p1 += a1->nchars;
5799 p2 += a2->nchars;
5801 if (a1 != a2)
5802 return 1;
5803 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5804 p2, d2->length - (p2 - d2->expansion), 1))
5805 return 1;
5806 return 0;
5809 /* Return 1 if two parts of two macro definitions are effectively different.
5810 One of the parts starts at BEG1 and has LEN1 chars;
5811 the other has LEN2 chars at BEG2.
5812 Any sequence of whitespace matches any other sequence of whitespace.
5813 FIRST means these parts are the first of a macro definition;
5814 so ignore leading whitespace entirely.
5815 LAST means these parts are the last of a macro definition;
5816 so ignore trailing whitespace entirely. */
5818 static int
5819 comp_def_part (first, beg1, len1, beg2, len2, last)
5820 int first;
5821 U_CHAR *beg1, *beg2;
5822 int len1, len2;
5823 int last;
5825 register U_CHAR *end1 = beg1 + len1;
5826 register U_CHAR *end2 = beg2 + len2;
5827 if (first) {
5828 while (beg1 != end1 && is_space[*beg1]) beg1++;
5829 while (beg2 != end2 && is_space[*beg2]) beg2++;
5831 if (last) {
5832 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5833 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5835 while (beg1 != end1 && beg2 != end2) {
5836 if (is_space[*beg1] && is_space[*beg2]) {
5837 while (beg1 != end1 && is_space[*beg1]) beg1++;
5838 while (beg2 != end2 && is_space[*beg2]) beg2++;
5839 } else if (*beg1 == *beg2) {
5840 beg1++; beg2++;
5841 } else break;
5843 return (beg1 != end1) || (beg2 != end2);
5846 /* Read a replacement list for a macro with parameters.
5847 Build the DEFINITION structure.
5848 Reads characters of text starting at BUF until END.
5849 ARGLIST specifies the formal parameters to look for
5850 in the text of the definition; NARGS is the number of args
5851 in that list, or -1 for a macro name that wants no argument list.
5852 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5853 and NAMELEN is its length in characters.
5855 Note that comments, backslash-newlines, and leading white space
5856 have already been deleted from the argument. */
5858 /* If there is no trailing whitespace, a Newline Space is added at the end
5859 to prevent concatenation that would be contrary to the standard. */
5861 static DEFINITION *
5862 collect_expansion (buf, end, nargs, arglist)
5863 U_CHAR *buf, *end;
5864 int nargs;
5865 struct arglist *arglist;
5867 DEFINITION *defn;
5868 register U_CHAR *p, *limit, *lastp, *exp_p;
5869 struct reflist *endpat = NULL;
5870 /* Pointer to first nonspace after last ## seen. */
5871 U_CHAR *concat = 0;
5872 /* Pointer to first nonspace after last single-# seen. */
5873 U_CHAR *stringify = 0;
5874 /* How those tokens were spelled. */
5875 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5876 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5877 int maxsize;
5878 int expected_delimiter = '\0';
5880 /* Scan thru the replacement list, ignoring comments and quoted
5881 strings, picking up on the macro calls. It does a linear search
5882 thru the arg list on every potential symbol. Profiling might say
5883 that something smarter should happen. */
5885 if (end < buf)
5886 abort ();
5888 /* Find the beginning of the trailing whitespace. */
5889 limit = end;
5890 p = buf;
5891 while (p < limit && is_space[limit[-1]]) limit--;
5893 /* Allocate space for the text in the macro definition.
5894 Each input char may or may not need 1 byte,
5895 so this is an upper bound.
5896 The extra 3 are for invented trailing newline-marker and final null. */
5897 maxsize = (sizeof (DEFINITION)
5898 + (limit - p) + 3);
5899 defn = (DEFINITION *) xcalloc (1, maxsize);
5901 defn->nargs = nargs;
5902 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5903 lastp = exp_p;
5905 if (p[0] == '#'
5906 ? p[1] == '#'
5907 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5908 error ("`##' at start of macro definition");
5909 p += p[0] == '#' ? 2 : 4;
5912 /* Process the main body of the definition. */
5913 while (p < limit) {
5914 int skipped_arg = 0;
5915 register U_CHAR c = *p++;
5917 *exp_p++ = c;
5919 if (!traditional) {
5920 switch (c) {
5921 case '\'':
5922 case '\"':
5923 if (expected_delimiter != '\0') {
5924 if (c == expected_delimiter)
5925 expected_delimiter = '\0';
5926 } else
5927 expected_delimiter = c;
5928 break;
5930 case '\\':
5931 if (p < limit && expected_delimiter) {
5932 /* In a string, backslash goes through
5933 and makes next char ordinary. */
5934 *exp_p++ = *p++;
5936 break;
5938 case '%':
5939 if (!expected_delimiter && *p == ':') {
5940 /* %: is not a digraph if preceded by an odd number of '<'s. */
5941 U_CHAR *p0 = p - 1;
5942 while (buf < p0 && p0[-1] == '<')
5943 p0--;
5944 if ((p - p0) & 1) {
5945 /* Treat %:%: as ## and %: as #. */
5946 if (p[1] == '%' && p[2] == ':') {
5947 p += 2;
5948 goto sharp_sharp_token;
5950 if (nargs >= 0) {
5951 p++;
5952 goto sharp_token;
5956 break;
5958 case '#':
5959 /* # is ordinary inside a string. */
5960 if (expected_delimiter)
5961 break;
5962 if (*p == '#') {
5963 sharp_sharp_token:
5964 /* ##: concatenate preceding and following tokens. */
5965 /* Take out the first #, discard preceding whitespace. */
5966 exp_p--;
5967 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5968 --exp_p;
5969 /* Skip the second #. */
5970 p++;
5971 concat_sharp_token_type = c;
5972 if (is_hor_space[*p]) {
5973 concat_sharp_token_type = c + 1;
5974 p++;
5975 SKIP_WHITE_SPACE (p);
5977 concat = p;
5978 if (p == limit)
5979 error ("`##' at end of macro definition");
5980 } else if (nargs >= 0) {
5981 /* Single #: stringify following argument ref.
5982 Don't leave the # in the expansion. */
5983 sharp_token:
5984 exp_p--;
5985 stringify_sharp_token_type = c;
5986 if (is_hor_space[*p]) {
5987 stringify_sharp_token_type = c + 1;
5988 p++;
5989 SKIP_WHITE_SPACE (p);
5991 if (! is_idstart[*p] || nargs == 0
5992 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
5993 error ("`#' operator is not followed by a macro argument name");
5994 else
5995 stringify = p;
5997 break;
5999 } else {
6000 /* In -traditional mode, recognize arguments inside strings and
6001 and character constants, and ignore special properties of #.
6002 Arguments inside strings are considered "stringified", but no
6003 extra quote marks are supplied. */
6004 switch (c) {
6005 case '\'':
6006 case '\"':
6007 if (expected_delimiter != '\0') {
6008 if (c == expected_delimiter)
6009 expected_delimiter = '\0';
6010 } else
6011 expected_delimiter = c;
6012 break;
6014 case '\\':
6015 /* Backslash quotes delimiters and itself, but not macro args. */
6016 if (expected_delimiter != 0 && p < limit
6017 && (*p == expected_delimiter || *p == '\\')) {
6018 *exp_p++ = *p++;
6019 continue;
6021 break;
6023 case '/':
6024 if (expected_delimiter != '\0') /* No comments inside strings. */
6025 break;
6026 if (*p == '*') {
6027 /* If we find a comment that wasn't removed by handle_directive,
6028 this must be -traditional. So replace the comment with
6029 nothing at all. */
6030 exp_p--;
6031 while (++p < limit) {
6032 if (p[0] == '*' && p[1] == '/') {
6033 p += 2;
6034 break;
6037 #if 0
6038 /* Mark this as a concatenation-point, as if it had been ##. */
6039 concat = p;
6040 #endif
6042 break;
6046 /* Handle the start of a symbol. */
6047 if (is_idchar[c] && nargs > 0) {
6048 U_CHAR *id_beg = p - 1;
6049 int id_len;
6051 --exp_p;
6052 while (p != limit && is_idchar[*p]) p++;
6053 id_len = p - id_beg;
6055 if (is_idstart[c]
6056 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6057 register struct arglist *arg;
6059 for (arg = arglist; arg != NULL; arg = arg->next) {
6060 struct reflist *tpat;
6062 if (arg->name[0] == c
6063 && arg->length == id_len
6064 && bcmp (arg->name, id_beg, id_len) == 0) {
6065 enum sharp_token_type tpat_stringify;
6066 if (expected_delimiter) {
6067 if (warn_stringify) {
6068 if (traditional) {
6069 warning ("macro argument `%.*s' is stringified.",
6070 id_len, arg->name);
6071 } else {
6072 warning ("macro arg `%.*s' would be stringified with -traditional.",
6073 id_len, arg->name);
6076 /* If ANSI, don't actually substitute inside a string. */
6077 if (!traditional)
6078 break;
6079 tpat_stringify = SHARP_TOKEN;
6080 } else {
6081 tpat_stringify
6082 = (stringify == id_beg
6083 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6085 /* make a pat node for this arg and append it to the end of
6086 the pat list */
6087 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6088 tpat->next = NULL;
6089 tpat->raw_before
6090 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6091 tpat->raw_after = NO_SHARP_TOKEN;
6092 tpat->rest_args = arg->rest_args;
6093 tpat->stringify = tpat_stringify;
6095 if (endpat == NULL)
6096 defn->pattern = tpat;
6097 else
6098 endpat->next = tpat;
6099 endpat = tpat;
6101 tpat->argno = arg->argno;
6102 tpat->nchars = exp_p - lastp;
6104 register U_CHAR *p1 = p;
6105 SKIP_WHITE_SPACE (p1);
6106 if (p1[0]=='#'
6107 ? p1[1]=='#'
6108 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6109 tpat->raw_after = p1[0] + (p != p1);
6111 lastp = exp_p; /* place to start copying from next time */
6112 skipped_arg = 1;
6113 break;
6118 /* If this was not a macro arg, copy it into the expansion. */
6119 if (! skipped_arg) {
6120 register U_CHAR *lim1 = p;
6121 p = id_beg;
6122 while (p != lim1)
6123 *exp_p++ = *p++;
6124 if (stringify == id_beg)
6125 error ("`#' operator should be followed by a macro argument name");
6130 if (!traditional && expected_delimiter == 0) {
6131 /* If ANSI, put in a newline-space marker to prevent token pasting.
6132 But not if "inside a string" (which in ANSI mode happens only for
6133 -D option). */
6134 *exp_p++ = '\n';
6135 *exp_p++ = ' ';
6138 *exp_p = '\0';
6140 defn->length = exp_p - defn->expansion;
6142 /* Crash now if we overrun the allocated size. */
6143 if (defn->length + 1 > maxsize)
6144 abort ();
6146 #if 0
6147 /* This isn't worth the time it takes. */
6148 /* give back excess storage */
6149 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6150 #endif
6152 return defn;
6155 static int
6156 do_assert (buf, limit, op, keyword)
6157 U_CHAR *buf, *limit;
6158 FILE_BUF *op;
6159 struct directive *keyword;
6161 U_CHAR *bp; /* temp ptr into input buffer */
6162 U_CHAR *symname; /* remember where symbol name starts */
6163 int sym_length; /* and how long it is */
6164 struct arglist *tokens = NULL;
6166 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6167 pedwarn ("ANSI C does not allow `#assert'");
6169 bp = buf;
6171 while (is_hor_space[*bp])
6172 bp++;
6174 symname = bp; /* remember where it starts */
6175 sym_length = check_macro_name (bp, "assertion");
6176 bp += sym_length;
6177 /* #define doesn't do this, but we should. */
6178 SKIP_WHITE_SPACE (bp);
6180 /* Lossage will occur if identifiers or control tokens are broken
6181 across lines using backslash. This is not the right place to take
6182 care of that. */
6184 if (*bp != '(') {
6185 error ("missing token-sequence in `#assert'");
6186 return 1;
6190 int error_flag = 0;
6192 bp++; /* skip '(' */
6193 SKIP_WHITE_SPACE (bp);
6195 tokens = read_token_list (&bp, limit, &error_flag);
6196 if (error_flag)
6197 return 1;
6198 if (tokens == 0) {
6199 error ("empty token-sequence in `#assert'");
6200 return 1;
6203 ++bp; /* skip paren */
6204 SKIP_WHITE_SPACE (bp);
6207 /* If this name isn't already an assertion name, make it one.
6208 Error if it was already in use in some other way. */
6211 ASSERTION_HASHNODE *hp;
6212 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6213 struct tokenlist_list *value
6214 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6216 hp = assertion_lookup (symname, sym_length, hashcode);
6217 if (hp == NULL) {
6218 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6219 error ("`defined' redefined as assertion");
6220 hp = assertion_install (symname, sym_length, hashcode);
6223 /* Add the spec'd token-sequence to the list of such. */
6224 value->tokens = tokens;
6225 value->next = hp->value;
6226 hp->value = value;
6229 return 0;
6232 static int
6233 do_unassert (buf, limit, op, keyword)
6234 U_CHAR *buf, *limit;
6235 FILE_BUF *op;
6236 struct directive *keyword;
6238 U_CHAR *bp; /* temp ptr into input buffer */
6239 U_CHAR *symname; /* remember where symbol name starts */
6240 int sym_length; /* and how long it is */
6242 struct arglist *tokens = NULL;
6243 int tokens_specified = 0;
6245 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6246 pedwarn ("ANSI C does not allow `#unassert'");
6248 bp = buf;
6250 while (is_hor_space[*bp])
6251 bp++;
6253 symname = bp; /* remember where it starts */
6254 sym_length = check_macro_name (bp, "assertion");
6255 bp += sym_length;
6256 /* #define doesn't do this, but we should. */
6257 SKIP_WHITE_SPACE (bp);
6259 /* Lossage will occur if identifiers or control tokens are broken
6260 across lines using backslash. This is not the right place to take
6261 care of that. */
6263 if (*bp == '(') {
6264 int error_flag = 0;
6266 bp++; /* skip '(' */
6267 SKIP_WHITE_SPACE (bp);
6269 tokens = read_token_list (&bp, limit, &error_flag);
6270 if (error_flag)
6271 return 1;
6272 if (tokens == 0) {
6273 error ("empty token list in `#unassert'");
6274 return 1;
6277 tokens_specified = 1;
6279 ++bp; /* skip paren */
6280 SKIP_WHITE_SPACE (bp);
6284 ASSERTION_HASHNODE *hp;
6285 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6286 struct tokenlist_list *tail, *prev;
6288 hp = assertion_lookup (symname, sym_length, hashcode);
6289 if (hp == NULL)
6290 return 1;
6292 /* If no token list was specified, then eliminate this assertion
6293 entirely. */
6294 if (! tokens_specified) {
6295 struct tokenlist_list *next;
6296 for (tail = hp->value; tail; tail = next) {
6297 next = tail->next;
6298 free_token_list (tail->tokens);
6299 free (tail);
6301 delete_assertion (hp);
6302 } else {
6303 /* If a list of tokens was given, then delete any matching list. */
6305 tail = hp->value;
6306 prev = 0;
6307 while (tail) {
6308 struct tokenlist_list *next = tail->next;
6309 if (compare_token_lists (tail->tokens, tokens)) {
6310 if (prev)
6311 prev->next = next;
6312 else
6313 hp->value = tail->next;
6314 free_token_list (tail->tokens);
6315 free (tail);
6316 } else {
6317 prev = tail;
6319 tail = next;
6324 return 0;
6327 /* Test whether there is an assertion named NAME
6328 and optionally whether it has an asserted token list TOKENS.
6329 NAME is not null terminated; its length is SYM_LENGTH.
6330 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6333 check_assertion (name, sym_length, tokens_specified, tokens)
6334 U_CHAR *name;
6335 int sym_length;
6336 int tokens_specified;
6337 struct arglist *tokens;
6339 ASSERTION_HASHNODE *hp;
6340 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6342 if (pedantic && !instack[indepth].system_header_p)
6343 pedwarn ("ANSI C does not allow testing assertions");
6345 hp = assertion_lookup (name, sym_length, hashcode);
6346 if (hp == NULL)
6347 /* It is not an assertion; just return false. */
6348 return 0;
6350 /* If no token list was specified, then value is 1. */
6351 if (! tokens_specified)
6352 return 1;
6355 struct tokenlist_list *tail;
6357 tail = hp->value;
6359 /* If a list of tokens was given,
6360 then succeed if the assertion records a matching list. */
6362 while (tail) {
6363 if (compare_token_lists (tail->tokens, tokens))
6364 return 1;
6365 tail = tail->next;
6368 /* Fail if the assertion has no matching list. */
6369 return 0;
6373 /* Compare two lists of tokens for equality including order of tokens. */
6375 static int
6376 compare_token_lists (l1, l2)
6377 struct arglist *l1, *l2;
6379 while (l1 && l2) {
6380 if (l1->length != l2->length)
6381 return 0;
6382 if (bcmp (l1->name, l2->name, l1->length))
6383 return 0;
6384 l1 = l1->next;
6385 l2 = l2->next;
6388 /* Succeed if both lists end at the same time. */
6389 return l1 == l2;
6392 /* Read a space-separated list of tokens ending in a close parenthesis.
6393 Return a list of strings, in the order they were written.
6394 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6395 Parse the text starting at *BPP, and update *BPP.
6396 Don't parse beyond LIMIT. */
6398 static struct arglist *
6399 read_token_list (bpp, limit, error_flag)
6400 U_CHAR **bpp;
6401 U_CHAR *limit;
6402 int *error_flag;
6404 struct arglist *token_ptrs = 0;
6405 U_CHAR *bp = *bpp;
6406 int depth = 1;
6408 *error_flag = 0;
6410 /* Loop over the assertion value tokens. */
6411 while (depth > 0) {
6412 struct arglist *temp;
6413 int eofp = 0;
6414 U_CHAR *beg = bp;
6416 /* Find the end of the token. */
6417 if (*bp == '(') {
6418 bp++;
6419 depth++;
6420 } else if (*bp == ')') {
6421 depth--;
6422 if (depth == 0)
6423 break;
6424 bp++;
6425 } else if (*bp == '"' || *bp == '\'')
6426 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6427 else
6428 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6429 && *bp != '"' && *bp != '\'' && bp != limit)
6430 bp++;
6432 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6433 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6434 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6435 temp->name[bp - beg] = 0;
6436 temp->next = token_ptrs;
6437 token_ptrs = temp;
6438 temp->length = bp - beg;
6440 SKIP_WHITE_SPACE (bp);
6442 if (bp >= limit) {
6443 error ("unterminated token sequence in `#assert' or `#unassert'");
6444 *error_flag = -1;
6445 return 0;
6448 *bpp = bp;
6450 /* We accumulated the names in reverse order.
6451 Now reverse them to get the proper order. */
6453 register struct arglist *prev = 0, *this, *next;
6454 for (this = token_ptrs; this; this = next) {
6455 next = this->next;
6456 this->next = prev;
6457 prev = this;
6459 return prev;
6463 static void
6464 free_token_list (tokens)
6465 struct arglist *tokens;
6467 while (tokens) {
6468 struct arglist *next = tokens->next;
6469 free (tokens->name);
6470 free (tokens);
6471 tokens = next;
6475 /* Install a name in the assertion hash table.
6477 If LEN is >= 0, it is the length of the name.
6478 Otherwise, compute the length by scanning the entire name.
6480 If HASH is >= 0, it is the precomputed hash code.
6481 Otherwise, compute the hash code. */
6483 static ASSERTION_HASHNODE *
6484 assertion_install (name, len, hash)
6485 U_CHAR *name;
6486 int len;
6487 int hash;
6489 register ASSERTION_HASHNODE *hp;
6490 register int i, bucket;
6491 register U_CHAR *p, *q;
6493 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6494 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6495 bucket = hash;
6496 hp->bucket_hdr = &assertion_hashtab[bucket];
6497 hp->next = assertion_hashtab[bucket];
6498 assertion_hashtab[bucket] = hp;
6499 hp->prev = NULL;
6500 if (hp->next != NULL)
6501 hp->next->prev = hp;
6502 hp->length = len;
6503 hp->value = 0;
6504 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6505 p = hp->name;
6506 q = name;
6507 for (i = 0; i < len; i++)
6508 *p++ = *q++;
6509 hp->name[len] = 0;
6510 return hp;
6513 /* Find the most recent hash node for name name (ending with first
6514 non-identifier char) installed by install
6516 If LEN is >= 0, it is the length of the name.
6517 Otherwise, compute the length by scanning the entire name.
6519 If HASH is >= 0, it is the precomputed hash code.
6520 Otherwise, compute the hash code. */
6522 static ASSERTION_HASHNODE *
6523 assertion_lookup (name, len, hash)
6524 U_CHAR *name;
6525 int len;
6526 int hash;
6528 register ASSERTION_HASHNODE *bucket;
6530 bucket = assertion_hashtab[hash];
6531 while (bucket) {
6532 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6533 return bucket;
6534 bucket = bucket->next;
6536 return NULL;
6539 static void
6540 delete_assertion (hp)
6541 ASSERTION_HASHNODE *hp;
6544 if (hp->prev != NULL)
6545 hp->prev->next = hp->next;
6546 if (hp->next != NULL)
6547 hp->next->prev = hp->prev;
6549 /* Make sure that the bucket chain header that the deleted guy was
6550 on points to the right thing afterwards. */
6551 if (hp == *hp->bucket_hdr)
6552 *hp->bucket_hdr = hp->next;
6554 free (hp);
6558 * interpret #line directive. Remembers previously seen fnames
6559 * in its very own hash table.
6561 #define FNAME_HASHSIZE 37
6563 static int
6564 do_line (buf, limit, op, keyword)
6565 U_CHAR *buf, *limit;
6566 FILE_BUF *op;
6567 struct directive *keyword;
6569 register U_CHAR *bp;
6570 FILE_BUF *ip = &instack[indepth];
6571 FILE_BUF tem;
6572 int new_lineno;
6573 enum file_change_code file_change = same_file;
6575 /* Expand any macros. */
6576 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6578 /* Point to macroexpanded line, which is null-terminated now. */
6579 bp = tem.buf;
6580 SKIP_WHITE_SPACE (bp);
6582 if (!isdigit (*bp)) {
6583 error ("invalid format `#line' directive");
6584 return 0;
6587 /* The Newline at the end of this line remains to be processed.
6588 To put the next line at the specified line number,
6589 we must store a line number now that is one less. */
6590 new_lineno = atoi ((char *) bp) - 1;
6592 /* NEW_LINENO is one less than the actual line number here. */
6593 if (pedantic && new_lineno < 0)
6594 pedwarn ("line number out of range in `#line' directive");
6596 /* skip over the line number. */
6597 while (isdigit (*bp))
6598 bp++;
6600 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6601 if (*bp && !is_space[*bp]) {
6602 error ("invalid format `#line' directive");
6603 return;
6605 #endif
6607 SKIP_WHITE_SPACE (bp);
6609 if (*bp == '\"') {
6610 static HASHNODE *fname_table[FNAME_HASHSIZE];
6611 HASHNODE *hp, **hash_bucket;
6612 U_CHAR *fname, *p;
6613 int fname_length;
6615 fname = ++bp;
6617 /* Turn the file name, which is a character string literal,
6618 into a null-terminated string. Do this in place. */
6619 p = bp;
6620 for (;;)
6621 switch ((*p++ = *bp++)) {
6622 case '\0':
6623 error ("invalid format `#line' directive");
6624 return 0;
6626 case '\\':
6628 char *bpc = (char *) bp;
6629 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6630 bp = (U_CHAR *) bpc;
6631 if (c < 0)
6632 p--;
6633 else
6634 p[-1] = c;
6636 break;
6638 case '\"':
6639 p[-1] = 0;
6640 goto fname_done;
6642 fname_done:
6643 fname_length = p - fname;
6645 SKIP_WHITE_SPACE (bp);
6646 if (*bp) {
6647 if (pedantic)
6648 pedwarn ("garbage at end of `#line' directive");
6649 if (*bp == '1')
6650 file_change = enter_file;
6651 else if (*bp == '2')
6652 file_change = leave_file;
6653 else if (*bp == '3')
6654 ip->system_header_p = 1;
6655 else if (*bp == '4')
6656 ip->system_header_p = 2;
6657 else {
6658 error ("invalid format `#line' directive");
6659 return 0;
6662 bp++;
6663 SKIP_WHITE_SPACE (bp);
6664 if (*bp == '3') {
6665 ip->system_header_p = 1;
6666 bp++;
6667 SKIP_WHITE_SPACE (bp);
6669 if (*bp == '4') {
6670 ip->system_header_p = 2;
6671 bp++;
6672 SKIP_WHITE_SPACE (bp);
6674 if (*bp) {
6675 error ("invalid format `#line' directive");
6676 return 0;
6680 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6681 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6682 if (hp->length == fname_length &&
6683 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6684 ip->nominal_fname = hp->value.cpval;
6685 break;
6687 if (hp == 0) {
6688 /* Didn't find it; cons up a new one. */
6689 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6690 hp->next = *hash_bucket;
6691 *hash_bucket = hp;
6693 hp->length = fname_length;
6694 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6695 bcopy (fname, hp->value.cpval, fname_length);
6697 } else if (*bp) {
6698 error ("invalid format `#line' directive");
6699 return 0;
6702 ip->lineno = new_lineno;
6703 output_line_directive (ip, op, 0, file_change);
6704 check_expand (op, ip->length - (ip->bufp - ip->buf));
6705 return 0;
6708 /* Remove the definition of a symbol from the symbol table.
6709 according to un*x /lib/cpp, it is not an error to undef
6710 something that has no definitions, so it isn't one here either. */
6712 static int
6713 do_undef (buf, limit, op, keyword)
6714 U_CHAR *buf, *limit;
6715 FILE_BUF *op;
6716 struct directive *keyword;
6718 int sym_length;
6719 HASHNODE *hp;
6720 U_CHAR *orig_buf = buf;
6722 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6723 if (pcp_outfile && op)
6724 pass_thru_directive (buf, limit, op, keyword);
6726 SKIP_WHITE_SPACE (buf);
6727 sym_length = check_macro_name (buf, "macro");
6729 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6730 /* If we are generating additional info for debugging (with -g) we
6731 need to pass through all effective #undef directives. */
6732 if (debug_output && op)
6733 pass_thru_directive (orig_buf, limit, op, keyword);
6734 if (hp->type != T_MACRO)
6735 warning ("undefining `%s'", hp->name);
6736 delete_macro (hp);
6739 if (pedantic) {
6740 buf += sym_length;
6741 SKIP_WHITE_SPACE (buf);
6742 if (buf != limit)
6743 pedwarn ("garbage after `#undef' directive");
6745 return 0;
6748 /* Report an error detected by the program we are processing.
6749 Use the text of the line in the error message.
6750 (We use error because it prints the filename & line#.) */
6752 static int
6753 do_error (buf, limit, op, keyword)
6754 U_CHAR *buf, *limit;
6755 FILE_BUF *op;
6756 struct directive *keyword;
6758 int length = limit - buf;
6759 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6760 bcopy ((char *) buf, (char *) copy, length);
6761 copy[length] = 0;
6762 SKIP_WHITE_SPACE (copy);
6763 error ("#error %s", copy);
6764 return 0;
6767 /* Report a warning detected by the program we are processing.
6768 Use the text of the line in the warning message, then continue.
6769 (We use error because it prints the filename & line#.) */
6771 static int
6772 do_warning (buf, limit, op, keyword)
6773 U_CHAR *buf, *limit;
6774 FILE_BUF *op;
6775 struct directive *keyword;
6777 int length = limit - buf;
6778 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6779 bcopy ((char *) buf, (char *) copy, length);
6780 copy[length] = 0;
6781 SKIP_WHITE_SPACE (copy);
6782 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
6783 if -pedantic-errors is given, #warning should cause an error. */
6784 pedwarn ("#warning %s", copy);
6785 return 0;
6788 /* Remember the name of the current file being read from so that we can
6789 avoid ever including it again. */
6791 static void
6792 do_once ()
6794 int i;
6796 for (i = indepth; i >= 0; i--)
6797 if (instack[i].inc) {
6798 record_control_macro (instack[i].inc, (U_CHAR *) "");
6799 break;
6803 /* Report program identification. */
6805 static int
6806 do_ident (buf, limit, op, keyword)
6807 U_CHAR *buf, *limit;
6808 FILE_BUF *op;
6809 struct directive *keyword;
6811 FILE_BUF trybuf;
6812 int len;
6814 /* Allow #ident in system headers, since that's not user's fault. */
6815 if (pedantic && !instack[indepth].system_header_p)
6816 pedwarn ("ANSI C does not allow `#ident'");
6818 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6819 buf = trybuf.buf;
6820 len = trybuf.bufp - buf;
6822 /* Output expanded directive. */
6823 check_expand (op, 7 + len);
6824 bcopy ("#ident ", (char *) op->bufp, 7);
6825 op->bufp += 7;
6826 bcopy ((char *) buf, (char *) op->bufp, len);
6827 op->bufp += len;
6829 free (buf);
6830 return 0;
6833 /* #pragma and its argument line have already been copied to the output file.
6834 Just check for some recognized pragmas that need validation here. */
6836 static int
6837 do_pragma (buf, limit, op, keyword)
6838 U_CHAR *buf, *limit;
6839 FILE_BUF *op;
6840 struct directive *keyword;
6842 SKIP_WHITE_SPACE (buf);
6843 if (!strncmp ((char *) buf, "once", 4)) {
6844 /* Allow #pragma once in system headers, since that's not the user's
6845 fault. */
6846 if (!instack[indepth].system_header_p)
6847 warning ("`#pragma once' is obsolete");
6848 do_once ();
6851 if (!strncmp ((char *) buf, "implementation", 14)) {
6852 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6853 been included yet. */
6855 int h;
6856 U_CHAR *p = buf + 14, *fname;
6857 SKIP_WHITE_SPACE (p);
6858 if (*p != '\"')
6859 return 0;
6861 fname = p + 1;
6862 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6863 *p = '\0';
6865 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6866 struct include_file *inc;
6867 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6868 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6869 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6870 return 0;
6875 return 0;
6878 #if 0
6879 /* This was a fun hack, but #pragma seems to start to be useful.
6880 By failing to recognize it, we pass it through unchanged to cc1. */
6882 /* The behavior of the #pragma directive is implementation defined.
6883 this implementation defines it as follows. */
6885 static int
6886 do_pragma ()
6888 close (0);
6889 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6890 goto nope;
6891 close (1);
6892 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6893 goto nope;
6894 execl ("/usr/games/hack", "#pragma", 0);
6895 execl ("/usr/games/rogue", "#pragma", 0);
6896 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6897 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6898 nope:
6899 fatal ("You are in a maze of twisty compiler features, all different");
6901 #endif
6903 #ifdef SCCS_DIRECTIVE
6905 /* Just ignore #sccs, on systems where we define it at all. */
6907 static int
6908 do_sccs (buf, limit, op, keyword)
6909 U_CHAR *buf, *limit;
6910 FILE_BUF *op;
6911 struct directive *keyword;
6913 if (pedantic)
6914 pedwarn ("ANSI C does not allow `#sccs'");
6915 return 0;
6918 #endif /* defined (SCCS_DIRECTIVE) */
6920 /* Handle #if directive by
6921 1) inserting special `defined' keyword into the hash table
6922 that gets turned into 0 or 1 by special_symbol (thus,
6923 if the luser has a symbol called `defined' already, it won't
6924 work inside the #if directive)
6925 2) rescan the input into a temporary output buffer
6926 3) pass the output buffer to the yacc parser and collect a value
6927 4) clean up the mess left from steps 1 and 2.
6928 5) call conditional_skip to skip til the next #endif (etc.),
6929 or not, depending on the value from step 3. */
6931 static int
6932 do_if (buf, limit, op, keyword)
6933 U_CHAR *buf, *limit;
6934 FILE_BUF *op;
6935 struct directive *keyword;
6937 HOST_WIDE_INT value;
6938 FILE_BUF *ip = &instack[indepth];
6940 value = eval_if_expression (buf, limit - buf);
6941 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6942 return 0;
6945 /* Handle a #elif directive by not changing if_stack either.
6946 see the comment above do_else. */
6948 static int
6949 do_elif (buf, limit, op, keyword)
6950 U_CHAR *buf, *limit;
6951 FILE_BUF *op;
6952 struct directive *keyword;
6954 HOST_WIDE_INT value;
6955 FILE_BUF *ip = &instack[indepth];
6957 if (if_stack == instack[indepth].if_stack) {
6958 error ("`#elif' not within a conditional");
6959 return 0;
6960 } else {
6961 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6962 error ("`#elif' after `#else'");
6963 fprintf (stderr, " (matches line %d", if_stack->lineno);
6964 if (if_stack->fname != NULL && ip->fname != NULL
6965 && strcmp (if_stack->fname, ip->nominal_fname) != 0)
6966 fprintf (stderr, ", file %s", if_stack->fname);
6967 fprintf (stderr, ")\n");
6969 if_stack->type = T_ELIF;
6972 if (if_stack->if_succeeded)
6973 skip_if_group (ip, 0, op);
6974 else {
6975 value = eval_if_expression (buf, limit - buf);
6976 if (value == 0)
6977 skip_if_group (ip, 0, op);
6978 else {
6979 ++if_stack->if_succeeded; /* continue processing input */
6980 output_line_directive (ip, op, 1, same_file);
6983 return 0;
6986 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
6987 result as a C expression and return the value as an int. */
6989 static HOST_WIDE_INT
6990 eval_if_expression (buf, length)
6991 U_CHAR *buf;
6992 int length;
6994 FILE_BUF temp_obuf;
6995 HASHNODE *save_defined;
6996 HOST_WIDE_INT value;
6998 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
6999 NULL_PTR, -1);
7000 pcp_inside_if = 1;
7001 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7002 pcp_inside_if = 0;
7003 delete_macro (save_defined); /* clean up special symbol */
7005 temp_obuf.buf[temp_obuf.length] = '\n';
7006 value = parse_c_expression ((char *) temp_obuf.buf,
7007 warn_undef && !instack[indepth].system_header_p);
7009 free (temp_obuf.buf);
7011 return value;
7014 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7015 or don't skip to the #endif/#else/#elif depending on what directive
7016 is actually being processed. */
7018 static int
7019 do_xifdef (buf, limit, op, keyword)
7020 U_CHAR *buf, *limit;
7021 FILE_BUF *op;
7022 struct directive *keyword;
7024 int skip;
7025 FILE_BUF *ip = &instack[indepth];
7026 U_CHAR *end;
7027 int start_of_file = 0;
7028 U_CHAR *control_macro = 0;
7030 /* Detect a #ifndef at start of file (not counting comments). */
7031 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7032 U_CHAR *p = ip->buf;
7033 while (p != directive_start) {
7034 U_CHAR c = *p++;
7035 if (is_space[c])
7037 /* Make no special provision for backslash-newline here; this is
7038 slower if backslash-newlines are present, but it's correct,
7039 and it's not worth it to tune for the rare backslash-newline. */
7040 else if (c == '/'
7041 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7042 /* Skip this comment. */
7043 int junk = 0;
7044 U_CHAR *save_bufp = ip->bufp;
7045 ip->bufp = p + 1;
7046 p = skip_to_end_of_comment (ip, &junk, 1);
7047 ip->bufp = save_bufp;
7048 } else {
7049 goto fail;
7052 /* If we get here, this conditional is the beginning of the file. */
7053 start_of_file = 1;
7054 fail: ;
7057 /* Discard leading and trailing whitespace. */
7058 SKIP_WHITE_SPACE (buf);
7059 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7061 /* Find the end of the identifier at the beginning. */
7062 for (end = buf; is_idchar[*end]; end++);
7064 if (end == buf) {
7065 skip = (keyword->type == T_IFDEF);
7066 if (! traditional)
7067 pedwarn (end == limit ? "`#%s' with no argument"
7068 : "`#%s' argument starts with punctuation",
7069 keyword->name);
7070 } else {
7071 HASHNODE *hp;
7073 if (! traditional) {
7074 if (isdigit (buf[0]))
7075 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7076 else if (end != limit)
7077 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7080 hp = lookup (buf, end-buf, -1);
7082 if (pcp_outfile) {
7083 /* Output a precondition for this macro. */
7084 if (hp
7085 && (hp->type == T_CONST
7086 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7087 fprintf (pcp_outfile, "#define %s\n", hp->name);
7088 else {
7089 U_CHAR *cp = buf;
7090 fprintf (pcp_outfile, "#undef ");
7091 while (is_idchar[*cp]) /* Ick! */
7092 fputc (*cp++, pcp_outfile);
7093 putc ('\n', pcp_outfile);
7097 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7098 if (start_of_file && !skip) {
7099 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7100 bcopy ((char *) buf, (char *) control_macro, end - buf);
7101 control_macro[end - buf] = 0;
7105 conditional_skip (ip, skip, T_IF, control_macro, op);
7106 return 0;
7109 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7110 If this is a #ifndef starting at the beginning of a file,
7111 CONTROL_MACRO is the macro name tested by the #ifndef.
7112 Otherwise, CONTROL_MACRO is 0. */
7114 static void
7115 conditional_skip (ip, skip, type, control_macro, op)
7116 FILE_BUF *ip;
7117 int skip;
7118 enum node_type type;
7119 U_CHAR *control_macro;
7120 FILE_BUF *op;
7122 IF_STACK_FRAME *temp;
7124 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7125 temp->fname = ip->nominal_fname;
7126 temp->lineno = ip->lineno;
7127 temp->next = if_stack;
7128 temp->control_macro = control_macro;
7129 if_stack = temp;
7131 if_stack->type = type;
7133 if (skip != 0) {
7134 skip_if_group (ip, 0, op);
7135 return;
7136 } else {
7137 ++if_stack->if_succeeded;
7138 output_line_directive (ip, &outbuf, 1, same_file);
7142 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7143 Leaves input ptr at the sharp sign found.
7144 If ANY is nonzero, return at next directive of any sort. */
7146 static void
7147 skip_if_group (ip, any, op)
7148 FILE_BUF *ip;
7149 int any;
7150 FILE_BUF *op;
7152 register U_CHAR *bp = ip->bufp, *cp;
7153 register U_CHAR *endb = ip->buf + ip->length;
7154 struct directive *kt;
7155 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7156 U_CHAR *beg_of_line = bp;
7157 register int ident_length;
7158 U_CHAR *ident, *after_ident;
7159 /* Save info about where the group starts. */
7160 U_CHAR *beg_of_group = bp;
7161 int beg_lineno = ip->lineno;
7163 if (output_conditionals && op != 0) {
7164 char *ptr = "#failed\n";
7165 int len = strlen (ptr);
7167 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7169 *op->bufp++ = '\n';
7170 op->lineno++;
7172 check_expand (op, len);
7173 bcopy (ptr, (char *) op->bufp, len);
7174 op->bufp += len;
7175 op->lineno++;
7176 output_line_directive (ip, op, 1, 0);
7179 while (bp < endb) {
7180 switch (*bp++) {
7181 case '/': /* possible comment */
7182 if (*bp == '\\' && bp[1] == '\n')
7183 newline_fix (bp);
7184 if (*bp == '*'
7185 || (cplusplus_comments && *bp == '/')) {
7186 ip->bufp = ++bp;
7187 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7189 break;
7190 case '\"':
7191 case '\'':
7192 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7193 NULL_PTR, NULL_PTR);
7194 break;
7195 case '\\':
7196 /* Char after backslash loses its special meaning. */
7197 if (bp < endb) {
7198 if (*bp == '\n')
7199 ++ip->lineno; /* But do update the line-count. */
7200 bp++;
7202 break;
7203 case '\n':
7204 ++ip->lineno;
7205 beg_of_line = bp;
7206 break;
7207 case '%':
7208 if (beg_of_line == 0 || traditional)
7209 break;
7210 ip->bufp = bp - 1;
7211 while (bp[0] == '\\' && bp[1] == '\n')
7212 bp += 2;
7213 if (*bp == ':')
7214 goto sharp_token;
7215 break;
7216 case '#':
7217 /* # keyword: a # must be first nonblank char on the line */
7218 if (beg_of_line == 0)
7219 break;
7220 ip->bufp = bp - 1;
7221 sharp_token:
7222 /* Scan from start of line, skipping whitespace, comments
7223 and backslash-newlines, and see if we reach this #.
7224 If not, this # is not special. */
7225 bp = beg_of_line;
7226 /* If -traditional, require # to be at beginning of line. */
7227 if (!traditional) {
7228 while (1) {
7229 if (is_hor_space[*bp])
7230 bp++;
7231 else if (*bp == '\\' && bp[1] == '\n')
7232 bp += 2;
7233 else if (*bp == '/' && bp[1] == '*') {
7234 bp += 2;
7235 while (!(*bp == '*' && bp[1] == '/'))
7236 bp++;
7237 bp += 2;
7239 /* There is no point in trying to deal with C++ // comments here,
7240 because if there is one, then this # must be part of the
7241 comment and we would never reach here. */
7242 else break;
7245 if (bp != ip->bufp) {
7246 bp = ip->bufp + 1; /* Reset bp to after the #. */
7247 break;
7250 bp = ip->bufp + 1; /* Point after the '#' */
7251 if (ip->bufp[0] == '%') {
7252 /* Skip past the ':' again. */
7253 while (*bp == '\\') {
7254 ip->lineno++;
7255 bp += 2;
7257 bp++;
7260 /* Skip whitespace and \-newline. */
7261 while (1) {
7262 if (is_hor_space[*bp])
7263 bp++;
7264 else if (*bp == '\\' && bp[1] == '\n')
7265 bp += 2;
7266 else if (*bp == '/') {
7267 if (bp[1] == '*') {
7268 for (bp += 2; ; bp++) {
7269 if (*bp == '\n')
7270 ip->lineno++;
7271 else if (*bp == '*') {
7272 if (bp[-1] == '/' && warn_comments)
7273 warning ("`/*' within comment");
7274 if (bp[1] == '/')
7275 break;
7278 bp += 2;
7279 } else if (bp[1] == '/' && cplusplus_comments) {
7280 for (bp += 2; ; bp++) {
7281 if (*bp == '\n') {
7282 if (bp[-1] != '\\')
7283 break;
7284 if (warn_comments)
7285 warning ("multiline `//' comment");
7286 ip->lineno++;
7289 } else
7290 break;
7291 } else
7292 break;
7295 cp = bp;
7297 /* Now find end of directive name.
7298 If we encounter a backslash-newline, exchange it with any following
7299 symbol-constituents so that we end up with a contiguous name. */
7301 while (1) {
7302 if (is_idchar[*bp])
7303 bp++;
7304 else {
7305 if (*bp == '\\' && bp[1] == '\n')
7306 name_newline_fix (bp);
7307 if (is_idchar[*bp])
7308 bp++;
7309 else break;
7312 ident_length = bp - cp;
7313 ident = cp;
7314 after_ident = bp;
7316 /* A line of just `#' becomes blank. */
7318 if (ident_length == 0 && *after_ident == '\n') {
7319 continue;
7322 if (ident_length == 0 || !is_idstart[*ident]) {
7323 U_CHAR *p = ident;
7324 while (is_idchar[*p]) {
7325 if (*p < '0' || *p > '9')
7326 break;
7327 p++;
7329 /* Handle # followed by a line number. */
7330 if (p != ident && !is_idchar[*p]) {
7331 if (pedantic)
7332 pedwarn ("`#' followed by integer");
7333 continue;
7336 /* Avoid error for `###' and similar cases unless -pedantic. */
7337 if (p == ident) {
7338 while (*p == '#' || is_hor_space[*p]) p++;
7339 if (*p == '\n') {
7340 if (pedantic && !lang_asm)
7341 pedwarn ("invalid preprocessing directive");
7342 continue;
7346 if (!lang_asm && pedantic)
7347 pedwarn ("invalid preprocessing directive name");
7348 continue;
7351 for (kt = directive_table; kt->length >= 0; kt++) {
7352 IF_STACK_FRAME *temp;
7353 if (ident_length == kt->length
7354 && bcmp (cp, kt->name, kt->length) == 0) {
7355 /* If we are asked to return on next directive, do so now. */
7356 if (any)
7357 goto done;
7359 switch (kt->type) {
7360 case T_IF:
7361 case T_IFDEF:
7362 case T_IFNDEF:
7363 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7364 temp->next = if_stack;
7365 if_stack = temp;
7366 temp->lineno = ip->lineno;
7367 temp->fname = ip->nominal_fname;
7368 temp->type = kt->type;
7369 break;
7370 case T_ELSE:
7371 case T_ENDIF:
7372 if (pedantic && if_stack != save_if_stack)
7373 validate_else (bp, endb);
7374 case T_ELIF:
7375 if (if_stack == instack[indepth].if_stack) {
7376 error ("`#%s' not within a conditional", kt->name);
7377 break;
7379 else if (if_stack == save_if_stack)
7380 goto done; /* found what we came for */
7382 if (kt->type != T_ENDIF) {
7383 if (if_stack->type == T_ELSE)
7384 error ("`#else' or `#elif' after `#else'");
7385 if_stack->type = kt->type;
7386 break;
7389 temp = if_stack;
7390 if_stack = if_stack->next;
7391 free (temp);
7392 break;
7394 default:
7395 break;
7397 break;
7400 /* Don't let erroneous code go by. */
7401 if (kt->length < 0 && !lang_asm && pedantic)
7402 pedwarn ("invalid preprocessing directive name");
7406 ip->bufp = bp;
7407 /* after this returns, rescan will exit because ip->bufp
7408 now points to the end of the buffer.
7409 rescan is responsible for the error message also. */
7411 done:
7412 if (output_conditionals && op != 0) {
7413 char *ptr = "#endfailed\n";
7414 int len = strlen (ptr);
7416 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7418 *op->bufp++ = '\n';
7419 op->lineno++;
7421 check_expand (op, beg_of_line - beg_of_group);
7422 bcopy ((char *) beg_of_group, (char *) op->bufp,
7423 beg_of_line - beg_of_group);
7424 op->bufp += beg_of_line - beg_of_group;
7425 op->lineno += ip->lineno - beg_lineno;
7426 check_expand (op, len);
7427 bcopy (ptr, (char *) op->bufp, len);
7428 op->bufp += len;
7429 op->lineno++;
7433 /* Handle a #else directive. Do this by just continuing processing
7434 without changing if_stack ; this is so that the error message
7435 for missing #endif's etc. will point to the original #if. It
7436 is possible that something different would be better. */
7438 static int
7439 do_else (buf, limit, op, keyword)
7440 U_CHAR *buf, *limit;
7441 FILE_BUF *op;
7442 struct directive *keyword;
7444 FILE_BUF *ip = &instack[indepth];
7446 if (pedantic) {
7447 SKIP_WHITE_SPACE (buf);
7448 if (buf != limit)
7449 pedwarn ("text following `#else' violates ANSI standard");
7452 if (if_stack == instack[indepth].if_stack) {
7453 error ("`#else' not within a conditional");
7454 return 0;
7455 } else {
7456 /* #ifndef can't have its special treatment for containing the whole file
7457 if it has a #else clause. */
7458 if_stack->control_macro = 0;
7460 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7461 error ("`#else' after `#else'");
7462 fprintf (stderr, " (matches line %d", if_stack->lineno);
7463 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7464 fprintf (stderr, ", file %s", if_stack->fname);
7465 fprintf (stderr, ")\n");
7467 if_stack->type = T_ELSE;
7470 if (if_stack->if_succeeded)
7471 skip_if_group (ip, 0, op);
7472 else {
7473 ++if_stack->if_succeeded; /* continue processing input */
7474 output_line_directive (ip, op, 1, same_file);
7476 return 0;
7479 /* Unstack after #endif directive. */
7481 static int
7482 do_endif (buf, limit, op, keyword)
7483 U_CHAR *buf, *limit;
7484 FILE_BUF *op;
7485 struct directive *keyword;
7487 if (pedantic) {
7488 SKIP_WHITE_SPACE (buf);
7489 if (buf != limit)
7490 pedwarn ("text following `#endif' violates ANSI standard");
7493 if (if_stack == instack[indepth].if_stack)
7494 error ("unbalanced `#endif'");
7495 else {
7496 IF_STACK_FRAME *temp = if_stack;
7497 if_stack = if_stack->next;
7498 if (temp->control_macro != 0) {
7499 /* This #endif matched a #ifndef at the start of the file.
7500 See if it is at the end of the file. */
7501 FILE_BUF *ip = &instack[indepth];
7502 U_CHAR *p = ip->bufp;
7503 U_CHAR *ep = ip->buf + ip->length;
7505 while (p != ep) {
7506 U_CHAR c = *p++;
7507 if (!is_space[c]) {
7508 if (c == '/'
7509 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7510 /* Skip this comment. */
7511 int junk = 0;
7512 U_CHAR *save_bufp = ip->bufp;
7513 ip->bufp = p + 1;
7514 p = skip_to_end_of_comment (ip, &junk, 1);
7515 ip->bufp = save_bufp;
7516 } else
7517 goto fail;
7520 /* If we get here, this #endif ends a #ifndef
7521 that contains all of the file (aside from whitespace).
7522 Arrange not to include the file again
7523 if the macro that was tested is defined.
7525 Do not do this for the top-level file in a -include or any
7526 file in a -imacros. */
7527 if (indepth != 0
7528 && ! (indepth == 1 && no_record_file)
7529 && ! (no_record_file && no_output))
7530 record_control_macro (ip->inc, temp->control_macro);
7531 fail: ;
7533 free (temp);
7534 output_line_directive (&instack[indepth], op, 1, same_file);
7536 return 0;
7539 /* When an #else or #endif is found while skipping failed conditional,
7540 if -pedantic was specified, this is called to warn about text after
7541 the directive name. P points to the first char after the directive
7542 name. */
7544 static void
7545 validate_else (p, limit)
7546 register U_CHAR *p;
7547 register U_CHAR *limit;
7549 /* Advance P over whitespace and comments. */
7550 while (1) {
7551 while (*p == '\\' && p[1] == '\n')
7552 p += 2;
7553 if (is_hor_space[*p])
7554 p++;
7555 else if (*p == '/') {
7556 while (p[1] == '\\' && p[2] == '\n')
7557 p += 2;
7558 if (p[1] == '*') {
7559 /* Don't bother warning about unterminated comments
7560 since that will happen later. Just be sure to exit. */
7561 for (p += 2; ; p++) {
7562 if (p == limit)
7563 return;
7564 if (*p == '*') {
7565 while (p[1] == '\\' && p[2] == '\n')
7566 p += 2;
7567 if (p[1] == '/') {
7568 p += 2;
7569 break;
7574 else if (cplusplus_comments && p[1] == '/')
7575 return;
7576 else break;
7577 } else break;
7579 if (*p != '\n')
7580 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7583 /* Skip a comment, assuming the input ptr immediately follows the
7584 initial slash-star. Bump *LINE_COUNTER for each newline.
7585 (The canonical line counter is &ip->lineno.)
7586 Don't use this routine (or the next one) if bumping the line
7587 counter is not sufficient to deal with newlines in the string.
7589 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7590 This feature is useful when processing a comment that is going to
7591 be processed or was processed at another point in the preprocessor,
7592 to avoid a duplicate warning. Likewise for unterminated comment
7593 errors. */
7595 static U_CHAR *
7596 skip_to_end_of_comment (ip, line_counter, nowarn)
7597 register FILE_BUF *ip;
7598 int *line_counter; /* place to remember newlines, or NULL */
7599 int nowarn;
7601 register U_CHAR *limit = ip->buf + ip->length;
7602 register U_CHAR *bp = ip->bufp;
7603 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7604 int start_line = line_counter ? *line_counter : 0;
7606 /* JF this line_counter stuff is a crock to make sure the
7607 comment is only put out once, no matter how many times
7608 the comment is skipped. It almost works */
7609 if (op) {
7610 *op->bufp++ = '/';
7611 *op->bufp++ = bp[-1];
7613 if (cplusplus_comments && bp[-1] == '/') {
7614 for (; bp < limit; bp++) {
7615 if (*bp == '\n') {
7616 if (bp[-1] != '\\')
7617 break;
7618 if (!nowarn && warn_comments)
7619 warning ("multiline `//' comment");
7620 if (line_counter)
7621 ++*line_counter;
7622 if (op)
7623 ++op->lineno;
7625 if (op)
7626 *op->bufp++ = *bp;
7628 ip->bufp = bp;
7629 return bp;
7631 while (bp < limit) {
7632 if (op)
7633 *op->bufp++ = *bp;
7634 switch (*bp++) {
7635 case '\n':
7636 /* If this is the end of the file, we have an unterminated comment.
7637 Don't swallow the newline. We are guaranteed that there will be a
7638 trailing newline and various pieces assume it's there. */
7639 if (bp == limit)
7641 --bp;
7642 --limit;
7643 break;
7645 if (line_counter != NULL)
7646 ++*line_counter;
7647 if (op)
7648 ++op->lineno;
7649 break;
7650 case '*':
7651 if (bp[-2] == '/' && !nowarn && warn_comments)
7652 warning ("`/*' within comment");
7653 if (*bp == '\\' && bp[1] == '\n')
7654 newline_fix (bp);
7655 if (*bp == '/') {
7656 if (op)
7657 *op->bufp++ = '/';
7658 ip->bufp = ++bp;
7659 return bp;
7661 break;
7665 if (!nowarn)
7666 error_with_line (line_for_error (start_line), "unterminated comment");
7667 ip->bufp = bp;
7668 return bp;
7671 /* Skip over a quoted string. BP points to the opening quote.
7672 Returns a pointer after the closing quote. Don't go past LIMIT.
7673 START_LINE is the line number of the starting point (but it need
7674 not be valid if the starting point is inside a macro expansion).
7676 The input stack state is not changed.
7678 If COUNT_NEWLINES is nonzero, it points to an int to increment
7679 for each newline passed.
7681 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7682 if we pass a backslash-newline.
7684 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
7686 static U_CHAR *
7687 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7688 register U_CHAR *bp;
7689 register U_CHAR *limit;
7690 int start_line;
7691 int *count_newlines;
7692 int *backslash_newlines_p;
7693 int *eofp;
7695 register U_CHAR c, match;
7697 match = *bp++;
7698 while (1) {
7699 if (bp >= limit) {
7700 error_with_line (line_for_error (start_line),
7701 "unterminated string or character constant");
7702 error_with_line (multiline_string_line,
7703 "possible real start of unterminated constant");
7704 multiline_string_line = 0;
7705 if (eofp)
7706 *eofp = 1;
7707 break;
7709 c = *bp++;
7710 if (c == '\\') {
7711 while (*bp == '\\' && bp[1] == '\n') {
7712 if (backslash_newlines_p)
7713 *backslash_newlines_p = 1;
7714 if (count_newlines)
7715 ++*count_newlines;
7716 bp += 2;
7718 if (*bp == '\n' && count_newlines) {
7719 if (backslash_newlines_p)
7720 *backslash_newlines_p = 1;
7721 ++*count_newlines;
7723 bp++;
7724 } else if (c == '\n') {
7725 if (traditional) {
7726 /* Unterminated strings and character constants are 'valid'. */
7727 bp--; /* Don't consume the newline. */
7728 if (eofp)
7729 *eofp = 1;
7730 break;
7732 if (match == '\'') {
7733 error_with_line (line_for_error (start_line),
7734 "unterminated string or character constant");
7735 bp--;
7736 if (eofp)
7737 *eofp = 1;
7738 break;
7740 /* If not traditional, then allow newlines inside strings. */
7741 if (count_newlines)
7742 ++*count_newlines;
7743 if (multiline_string_line == 0) {
7744 if (pedantic)
7745 pedwarn_with_line (line_for_error (start_line),
7746 "string constant runs past end of line");
7747 multiline_string_line = start_line;
7749 } else if (c == match)
7750 break;
7752 return bp;
7755 /* Place into DST a quoted string representing the string SRC.
7756 Return the address of DST's terminating null. */
7758 static char *
7759 quote_string (dst, src)
7760 char *dst, *src;
7762 U_CHAR c;
7764 *dst++ = '\"';
7765 for (;;)
7766 switch ((c = *src++))
7768 default:
7769 if (isprint (c))
7770 *dst++ = c;
7771 else
7773 sprintf (dst, "\\%03o", c);
7774 dst += 4;
7776 break;
7778 case '\"':
7779 case '\\':
7780 *dst++ = '\\';
7781 *dst++ = c;
7782 break;
7784 case '\0':
7785 *dst++ = '\"';
7786 *dst = '\0';
7787 return dst;
7791 /* Skip across a group of balanced parens, starting from IP->bufp.
7792 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7794 This does not handle newlines, because it's used for the arg of #if,
7795 where there aren't any newlines. Also, backslash-newline can't appear. */
7797 static U_CHAR *
7798 skip_paren_group (ip)
7799 register FILE_BUF *ip;
7801 U_CHAR *limit = ip->buf + ip->length;
7802 U_CHAR *p = ip->bufp;
7803 int depth = 0;
7804 int lines_dummy = 0;
7806 while (p != limit) {
7807 int c = *p++;
7808 switch (c) {
7809 case '(':
7810 depth++;
7811 break;
7813 case ')':
7814 depth--;
7815 if (depth == 0)
7816 return ip->bufp = p;
7817 break;
7819 case '/':
7820 if (*p == '*') {
7821 ip->bufp = p;
7822 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7823 p = ip->bufp;
7826 case '"':
7827 case '\'':
7829 int eofp = 0;
7830 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7831 if (eofp)
7832 return ip->bufp = p;
7834 break;
7838 ip->bufp = p;
7839 return p;
7842 /* Write out a #line directive, for instance, after an #include file.
7843 If CONDITIONAL is nonzero, we can omit the #line if it would
7844 appear to be a no-op, and we can output a few newlines instead
7845 if we want to increase the line number by a small amount.
7846 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
7848 static void
7849 output_line_directive (ip, op, conditional, file_change)
7850 FILE_BUF *ip, *op;
7851 int conditional;
7852 enum file_change_code file_change;
7854 int len;
7855 char *line_directive_buf, *line_end;
7857 if (no_line_directives
7858 || ip->fname == NULL
7859 || no_output) {
7860 op->lineno = ip->lineno;
7861 return;
7864 if (conditional) {
7865 if (ip->lineno == op->lineno)
7866 return;
7868 /* If the inherited line number is a little too small,
7869 output some newlines instead of a #line directive. */
7870 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7871 check_expand (op, 10);
7872 while (ip->lineno > op->lineno) {
7873 *op->bufp++ = '\n';
7874 op->lineno++;
7876 return;
7880 /* Output a positive line number if possible. */
7881 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
7882 && *ip->bufp == '\n') {
7883 ip->lineno++;
7884 ip->bufp++;
7887 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7888 sprintf (line_directive_buf, "# %d ", ip->lineno);
7889 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7890 ip->nominal_fname);
7891 if (file_change != same_file) {
7892 *line_end++ = ' ';
7893 *line_end++ = file_change == enter_file ? '1' : '2';
7895 /* Tell cc1 if following text comes from a system header file. */
7896 if (ip->system_header_p) {
7897 *line_end++ = ' ';
7898 *line_end++ = '3';
7900 #ifndef NO_IMPLICIT_EXTERN_C
7901 /* Tell cc1plus if following text should be treated as C. */
7902 if (ip->system_header_p == 2 && cplusplus) {
7903 *line_end++ = ' ';
7904 *line_end++ = '4';
7906 #endif
7907 *line_end++ = '\n';
7908 len = line_end - line_directive_buf;
7909 check_expand (op, len + 1);
7910 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7911 *op->bufp++ = '\n';
7912 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7913 op->bufp += len;
7914 op->lineno = ip->lineno;
7917 /* This structure represents one parsed argument in a macro call.
7918 `raw' points to the argument text as written (`raw_length' is its length).
7919 `expanded' points to the argument's macro-expansion
7920 (its length is `expand_length').
7921 `stringified_length' is the length the argument would have
7922 if stringified.
7923 `use_count' is the number of times this macro arg is substituted
7924 into the macro. If the actual use count exceeds 10,
7925 the value stored is 10.
7926 `free1' and `free2', if nonzero, point to blocks to be freed
7927 when the macro argument data is no longer needed. */
7929 struct argdata {
7930 U_CHAR *raw, *expanded;
7931 int raw_length, expand_length;
7932 int stringified_length;
7933 U_CHAR *free1, *free2;
7934 char newlines;
7935 char use_count;
7938 /* Expand a macro call.
7939 HP points to the symbol that is the macro being called.
7940 Put the result of expansion onto the input stack
7941 so that subsequent input by our caller will use it.
7943 If macro wants arguments, caller has already verified that
7944 an argument list follows; arguments come from the input stack. */
7946 static void
7947 macroexpand (hp, op)
7948 HASHNODE *hp;
7949 FILE_BUF *op;
7951 int nargs;
7952 DEFINITION *defn = hp->value.defn;
7953 register U_CHAR *xbuf;
7954 int xbuf_len;
7955 int start_line = instack[indepth].lineno;
7956 int rest_args, rest_zero;
7958 CHECK_DEPTH (return;);
7960 /* it might not actually be a macro. */
7961 if (hp->type != T_MACRO) {
7962 special_symbol (hp, op);
7963 return;
7966 /* This macro is being used inside a #if, which means it must be */
7967 /* recorded as a precondition. */
7968 if (pcp_inside_if && pcp_outfile && defn->predefined)
7969 dump_single_macro (hp, pcp_outfile);
7971 nargs = defn->nargs;
7973 if (nargs >= 0) {
7974 register int i;
7975 struct argdata *args;
7976 char *parse_error = 0;
7978 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7980 for (i = 0; i < nargs; i++) {
7981 args[i].raw = (U_CHAR *) "";
7982 args[i].expanded = 0;
7983 args[i].raw_length = args[i].expand_length
7984 = args[i].stringified_length = 0;
7985 args[i].free1 = args[i].free2 = 0;
7986 args[i].use_count = 0;
7989 /* Parse all the macro args that are supplied. I counts them.
7990 The first NARGS args are stored in ARGS.
7991 The rest are discarded.
7992 If rest_args is set then we assume macarg absorbed the rest of the args.
7994 i = 0;
7995 rest_args = 0;
7996 do {
7997 /* Discard the open-parenthesis or comma before the next arg. */
7998 ++instack[indepth].bufp;
7999 if (rest_args)
8000 continue;
8001 if (i < nargs || (nargs == 0 && i == 0)) {
8002 /* If we are working on last arg which absorbs rest of args... */
8003 if (i == nargs - 1 && defn->rest_args)
8004 rest_args = 1;
8005 parse_error = macarg (&args[i], rest_args);
8007 else
8008 parse_error = macarg (NULL_PTR, 0);
8009 if (parse_error) {
8010 error_with_line (line_for_error (start_line), parse_error);
8011 break;
8013 i++;
8014 } while (*instack[indepth].bufp != ')');
8016 /* If we got one arg but it was just whitespace, call that 0 args. */
8017 if (i == 1) {
8018 register U_CHAR *bp = args[0].raw;
8019 register U_CHAR *lim = bp + args[0].raw_length;
8020 /* cpp.texi says for foo ( ) we provide one argument.
8021 However, if foo wants just 0 arguments, treat this as 0. */
8022 if (nargs == 0)
8023 while (bp != lim && is_space[*bp]) bp++;
8024 if (bp == lim)
8025 i = 0;
8028 /* Don't output an error message if we have already output one for
8029 a parse error above. */
8030 rest_zero = 0;
8031 if (nargs == 0 && i > 0) {
8032 if (! parse_error)
8033 error ("arguments given to macro `%s'", hp->name);
8034 } else if (i < nargs) {
8035 /* traditional C allows foo() if foo wants one argument. */
8036 if (nargs == 1 && i == 0 && traditional)
8038 /* the rest args token is allowed to absorb 0 tokens */
8039 else if (i == nargs - 1 && defn->rest_args)
8040 rest_zero = 1;
8041 else if (parse_error)
8043 else if (i == 0)
8044 error ("macro `%s' used without args", hp->name);
8045 else if (i == 1)
8046 error ("macro `%s' used with just one arg", hp->name);
8047 else
8048 error ("macro `%s' used with only %d args", hp->name, i);
8049 } else if (i > nargs) {
8050 if (! parse_error)
8051 error ("macro `%s' used with too many (%d) args", hp->name, i);
8054 /* Swallow the closeparen. */
8055 ++instack[indepth].bufp;
8057 /* If macro wants zero args, we parsed the arglist for checking only.
8058 Read directly from the macro definition. */
8059 if (nargs == 0) {
8060 xbuf = defn->expansion;
8061 xbuf_len = defn->length;
8062 } else {
8063 register U_CHAR *exp = defn->expansion;
8064 register int offset; /* offset in expansion,
8065 copied a piece at a time */
8066 register int totlen; /* total amount of exp buffer filled so far */
8068 register struct reflist *ap, *last_ap;
8070 /* Macro really takes args. Compute the expansion of this call. */
8072 /* Compute length in characters of the macro's expansion.
8073 Also count number of times each arg is used. */
8074 xbuf_len = defn->length;
8075 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8076 if (ap->stringify)
8077 xbuf_len += args[ap->argno].stringified_length;
8078 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8079 /* Add 4 for two newline-space markers to prevent
8080 token concatenation. */
8081 xbuf_len += args[ap->argno].raw_length + 4;
8082 else {
8083 /* We have an ordinary (expanded) occurrence of the arg.
8084 So compute its expansion, if we have not already. */
8085 if (args[ap->argno].expanded == 0) {
8086 FILE_BUF obuf;
8087 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8088 args[ap->argno].raw + args[ap->argno].raw_length,
8089 1, 0);
8091 args[ap->argno].expanded = obuf.buf;
8092 args[ap->argno].expand_length = obuf.length;
8093 args[ap->argno].free2 = obuf.buf;
8096 /* Add 4 for two newline-space markers to prevent
8097 token concatenation. */
8098 xbuf_len += args[ap->argno].expand_length + 4;
8100 if (args[ap->argno].use_count < 10)
8101 args[ap->argno].use_count++;
8104 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8106 /* Generate in XBUF the complete expansion
8107 with arguments substituted in.
8108 TOTLEN is the total size generated so far.
8109 OFFSET is the index in the definition
8110 of where we are copying from. */
8111 offset = totlen = 0;
8112 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8113 last_ap = ap, ap = ap->next) {
8114 register struct argdata *arg = &args[ap->argno];
8115 int count_before = totlen;
8117 /* Add chars to XBUF. */
8118 for (i = 0; i < ap->nchars; i++, offset++)
8119 xbuf[totlen++] = exp[offset];
8121 /* If followed by an empty rest arg with concatenation,
8122 delete the last run of nonwhite chars. */
8123 if (rest_zero && totlen > count_before
8124 && ((ap->rest_args && ap->raw_before != 0)
8125 || (last_ap != NULL && last_ap->rest_args
8126 && last_ap->raw_after != 0))) {
8127 /* Delete final whitespace. */
8128 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8129 totlen--;
8132 /* Delete the nonwhites before them. */
8133 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8134 totlen--;
8138 if (ap->stringify != 0) {
8139 int arglen = arg->raw_length;
8140 int escaped = 0;
8141 int in_string = 0;
8142 int c;
8143 i = 0;
8144 while (i < arglen
8145 && (c = arg->raw[i], is_space[c]))
8146 i++;
8147 while (i < arglen
8148 && (c = arg->raw[arglen - 1], is_space[c]))
8149 arglen--;
8150 if (!traditional)
8151 xbuf[totlen++] = '\"'; /* insert beginning quote */
8152 for (; i < arglen; i++) {
8153 c = arg->raw[i];
8155 /* Special markers Newline Space
8156 generate nothing for a stringified argument. */
8157 if (c == '\n' && arg->raw[i+1] != '\n') {
8158 i++;
8159 continue;
8162 /* Internal sequences of whitespace are replaced by one space
8163 except within an string or char token. */
8164 if (! in_string
8165 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8166 while (1) {
8167 /* Note that Newline Space does occur within whitespace
8168 sequences; consider it part of the sequence. */
8169 if (c == '\n' && is_space[arg->raw[i+1]])
8170 i += 2;
8171 else if (c != '\n' && is_space[c])
8172 i++;
8173 else break;
8174 c = arg->raw[i];
8176 i--;
8177 c = ' ';
8180 if (escaped)
8181 escaped = 0;
8182 else {
8183 if (c == '\\')
8184 escaped = 1;
8185 if (in_string) {
8186 if (c == in_string)
8187 in_string = 0;
8188 } else if (c == '\"' || c == '\'')
8189 in_string = c;
8192 /* Escape these chars */
8193 if (c == '\"' || (in_string && c == '\\'))
8194 xbuf[totlen++] = '\\';
8195 if (isprint (c))
8196 xbuf[totlen++] = c;
8197 else {
8198 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8199 totlen += 4;
8202 if (!traditional)
8203 xbuf[totlen++] = '\"'; /* insert ending quote */
8204 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8205 U_CHAR *p1 = arg->raw;
8206 U_CHAR *l1 = p1 + arg->raw_length;
8207 if (ap->raw_before != 0) {
8208 while (p1 != l1 && is_space[*p1]) p1++;
8209 while (p1 != l1 && is_idchar[*p1])
8210 xbuf[totlen++] = *p1++;
8211 /* Delete any no-reexpansion marker that follows
8212 an identifier at the beginning of the argument
8213 if the argument is concatenated with what precedes it. */
8214 if (p1[0] == '\n' && p1[1] == '-')
8215 p1 += 2;
8216 } else if (!traditional) {
8217 /* Ordinary expanded use of the argument.
8218 Put in newline-space markers to prevent token pasting. */
8219 xbuf[totlen++] = '\n';
8220 xbuf[totlen++] = ' ';
8222 if (ap->raw_after != 0) {
8223 /* Arg is concatenated after: delete trailing whitespace,
8224 whitespace markers, and no-reexpansion markers. */
8225 while (p1 != l1) {
8226 if (is_space[l1[-1]]) l1--;
8227 else if (l1[-1] == '-') {
8228 U_CHAR *p2 = l1 - 1;
8229 /* If a `-' is preceded by an odd number of newlines then it
8230 and the last newline are a no-reexpansion marker. */
8231 while (p2 != p1 && p2[-1] == '\n') p2--;
8232 if ((l1 - 1 - p2) & 1) {
8233 l1 -= 2;
8235 else break;
8237 else break;
8241 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8242 totlen += l1 - p1;
8243 if (!traditional && ap->raw_after == 0) {
8244 /* Ordinary expanded use of the argument.
8245 Put in newline-space markers to prevent token pasting. */
8246 xbuf[totlen++] = '\n';
8247 xbuf[totlen++] = ' ';
8249 } else {
8250 /* Ordinary expanded use of the argument.
8251 Put in newline-space markers to prevent token pasting. */
8252 if (!traditional) {
8253 xbuf[totlen++] = '\n';
8254 xbuf[totlen++] = ' ';
8256 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8257 arg->expand_length);
8258 totlen += arg->expand_length;
8259 if (!traditional) {
8260 xbuf[totlen++] = '\n';
8261 xbuf[totlen++] = ' ';
8263 /* If a macro argument with newlines is used multiple times,
8264 then only expand the newlines once. This avoids creating output
8265 lines which don't correspond to any input line, which confuses
8266 gdb and gcov. */
8267 if (arg->use_count > 1 && arg->newlines > 0) {
8268 /* Don't bother doing change_newlines for subsequent
8269 uses of arg. */
8270 arg->use_count = 1;
8271 arg->expand_length
8272 = change_newlines (arg->expanded, arg->expand_length);
8276 if (totlen > xbuf_len)
8277 abort ();
8280 /* If there is anything left of the definition after handling
8281 the arg list, copy that in too. */
8283 for (i = offset; i < defn->length; i++) {
8284 /* if we've reached the end of the macro */
8285 if (exp[i] == ')')
8286 rest_zero = 0;
8287 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8288 && last_ap->raw_after != 0))
8289 xbuf[totlen++] = exp[i];
8292 xbuf[totlen] = 0;
8293 xbuf_len = totlen;
8295 for (i = 0; i < nargs; i++) {
8296 if (args[i].free1 != 0)
8297 free (args[i].free1);
8298 if (args[i].free2 != 0)
8299 free (args[i].free2);
8302 } else {
8303 xbuf = defn->expansion;
8304 xbuf_len = defn->length;
8307 /* Now put the expansion on the input stack
8308 so our caller will commence reading from it. */
8310 register FILE_BUF *ip2;
8312 ip2 = &instack[++indepth];
8314 ip2->fname = 0;
8315 ip2->nominal_fname = 0;
8316 ip2->inc = 0;
8317 /* This may not be exactly correct, but will give much better error
8318 messages for nested macro calls than using a line number of zero. */
8319 ip2->lineno = start_line;
8320 ip2->buf = xbuf;
8321 ip2->length = xbuf_len;
8322 ip2->bufp = xbuf;
8323 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8324 ip2->macro = hp;
8325 ip2->if_stack = if_stack;
8326 ip2->system_header_p = 0;
8328 /* Recursive macro use sometimes works traditionally.
8329 #define foo(x,y) bar (x (y,0), y)
8330 foo (foo, baz) */
8332 if (!traditional)
8333 hp->type = T_DISABLED;
8337 /* Parse a macro argument and store the info on it into *ARGPTR.
8338 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8339 Return nonzero to indicate a syntax error. */
8341 static char *
8342 macarg (argptr, rest_args)
8343 register struct argdata *argptr;
8344 int rest_args;
8346 FILE_BUF *ip = &instack[indepth];
8347 int paren = 0;
8348 int newlines = 0;
8349 int comments = 0;
8350 char *result = 0;
8352 /* Try to parse as much of the argument as exists at this
8353 input stack level. */
8354 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8355 &paren, &newlines, &comments, rest_args);
8357 /* If we find the end of the argument at this level,
8358 set up *ARGPTR to point at it in the input stack. */
8359 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8360 && bp != ip->buf + ip->length) {
8361 if (argptr != 0) {
8362 argptr->raw = ip->bufp;
8363 argptr->raw_length = bp - ip->bufp;
8364 argptr->newlines = newlines;
8366 ip->bufp = bp;
8367 } else {
8368 /* This input stack level ends before the macro argument does.
8369 We must pop levels and keep parsing.
8370 Therefore, we must allocate a temporary buffer and copy
8371 the macro argument into it. */
8372 int bufsize = bp - ip->bufp;
8373 int extra = newlines;
8374 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8375 int final_start = 0;
8377 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8378 ip->bufp = bp;
8379 ip->lineno += newlines;
8381 while (bp == ip->buf + ip->length) {
8382 if (instack[indepth].macro == 0) {
8383 result = "unterminated macro call";
8384 break;
8386 ip->macro->type = T_MACRO;
8387 if (ip->free_ptr)
8388 free (ip->free_ptr);
8389 ip = &instack[--indepth];
8390 newlines = 0;
8391 comments = 0;
8392 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8393 &newlines, &comments, rest_args);
8394 final_start = bufsize;
8395 bufsize += bp - ip->bufp;
8396 extra += newlines;
8397 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8398 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8399 bp - ip->bufp);
8400 ip->bufp = bp;
8401 ip->lineno += newlines;
8404 /* Now, if arg is actually wanted, record its raw form,
8405 discarding comments and duplicating newlines in whatever
8406 part of it did not come from a macro expansion.
8407 EXTRA space has been preallocated for duplicating the newlines.
8408 FINAL_START is the index of the start of that part. */
8409 if (argptr != 0) {
8410 argptr->raw = buffer;
8411 argptr->raw_length = bufsize;
8412 argptr->free1 = buffer;
8413 argptr->newlines = newlines;
8414 if ((newlines || comments) && ip->fname != 0)
8415 argptr->raw_length
8416 = final_start +
8417 discard_comments (argptr->raw + final_start,
8418 argptr->raw_length - final_start,
8419 newlines);
8420 argptr->raw[argptr->raw_length] = 0;
8421 if (argptr->raw_length > bufsize + extra)
8422 abort ();
8426 /* If we are not discarding this argument,
8427 macroexpand it and compute its length as stringified.
8428 All this info goes into *ARGPTR. */
8430 if (argptr != 0) {
8431 register U_CHAR *buf, *lim;
8432 register int totlen;
8434 buf = argptr->raw;
8435 lim = buf + argptr->raw_length;
8437 while (buf != lim && is_space[*buf])
8438 buf++;
8439 while (buf != lim && is_space[lim[-1]])
8440 lim--;
8441 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8442 while (buf != lim) {
8443 register U_CHAR c = *buf++;
8444 totlen++;
8445 /* Internal sequences of whitespace are replaced by one space
8446 in most cases, but not always. So count all the whitespace
8447 in case we need to keep it all. */
8448 #if 0
8449 if (is_space[c])
8450 SKIP_ALL_WHITE_SPACE (buf);
8451 else
8452 #endif
8453 if (c == '\"' || c == '\\') /* escape these chars */
8454 totlen++;
8455 else if (!isprint (c))
8456 totlen += 3;
8458 argptr->stringified_length = totlen;
8460 return result;
8463 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8464 counting parens in *DEPTHPTR,
8465 and return if reach LIMIT
8466 or before a `)' that would make *DEPTHPTR negative
8467 or before a comma when *DEPTHPTR is zero.
8468 Single and double quotes are matched and termination
8469 is inhibited within them. Comments also inhibit it.
8470 Value returned is pointer to stopping place.
8472 Increment *NEWLINES each time a newline is passed.
8473 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8474 Set *COMMENTS to 1 if a comment is seen. */
8476 static U_CHAR *
8477 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8478 U_CHAR *start;
8479 register U_CHAR *limit;
8480 int *depthptr, *newlines, *comments;
8481 int rest_args;
8483 register U_CHAR *bp = start;
8485 while (bp < limit) {
8486 switch (*bp) {
8487 case '(':
8488 (*depthptr)++;
8489 break;
8490 case ')':
8491 if (--(*depthptr) < 0)
8492 return bp;
8493 break;
8494 case '\\':
8495 /* Traditionally, backslash makes following char not special. */
8496 if (bp + 1 < limit && traditional)
8498 bp++;
8499 /* But count source lines anyway. */
8500 if (*bp == '\n')
8501 ++*newlines;
8503 break;
8504 case '\n':
8505 ++*newlines;
8506 break;
8507 case '/':
8508 if (bp[1] == '\\' && bp[2] == '\n')
8509 newline_fix (bp + 1);
8510 if (bp[1] == '*') {
8511 *comments = 1;
8512 for (bp += 2; bp < limit; bp++) {
8513 if (*bp == '\n')
8514 ++*newlines;
8515 else if (*bp == '*') {
8516 if (bp[-1] == '/' && warn_comments)
8517 warning ("`/*' within comment");
8518 if (bp[1] == '\\' && bp[2] == '\n')
8519 newline_fix (bp + 1);
8520 if (bp[1] == '/') {
8521 bp++;
8522 break;
8526 } else if (bp[1] == '/' && cplusplus_comments) {
8527 *comments = 1;
8528 for (bp += 2; bp < limit; bp++) {
8529 if (*bp == '\n') {
8530 ++*newlines;
8531 if (bp[-1] != '\\')
8532 break;
8533 if (warn_comments)
8534 warning ("multiline `//' comment");
8538 break;
8539 case '\'':
8540 case '\"':
8542 int quotec;
8543 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8544 if (*bp == '\\') {
8545 bp++;
8546 if (*bp == '\n')
8547 ++*newlines;
8548 while (*bp == '\\' && bp[1] == '\n') {
8549 bp += 2;
8551 } else if (*bp == '\n') {
8552 ++*newlines;
8553 if (quotec == '\'')
8554 break;
8558 break;
8559 case ',':
8560 /* if we've returned to lowest level and we aren't absorbing all args */
8561 if ((*depthptr) == 0 && rest_args == 0)
8562 return bp;
8563 break;
8565 bp++;
8568 return bp;
8571 /* Discard comments and duplicate newlines
8572 in the string of length LENGTH at START,
8573 except inside of string constants.
8574 The string is copied into itself with its beginning staying fixed.
8576 NEWLINES is the number of newlines that must be duplicated.
8577 We assume that that much extra space is available past the end
8578 of the string. */
8580 static int
8581 discard_comments (start, length, newlines)
8582 U_CHAR *start;
8583 int length;
8584 int newlines;
8586 register U_CHAR *ibp;
8587 register U_CHAR *obp;
8588 register U_CHAR *limit;
8589 register int c;
8591 /* If we have newlines to duplicate, copy everything
8592 that many characters up. Then, in the second part,
8593 we will have room to insert the newlines
8594 while copying down.
8595 NEWLINES may actually be too large, because it counts
8596 newlines in string constants, and we don't duplicate those.
8597 But that does no harm. */
8598 if (newlines > 0) {
8599 ibp = start + length;
8600 obp = ibp + newlines;
8601 limit = start;
8602 while (limit != ibp)
8603 *--obp = *--ibp;
8606 ibp = start + newlines;
8607 limit = start + length + newlines;
8608 obp = start;
8610 while (ibp < limit) {
8611 *obp++ = c = *ibp++;
8612 switch (c) {
8613 case '\n':
8614 /* Duplicate the newline. */
8615 *obp++ = '\n';
8616 break;
8618 case '\\':
8619 if (*ibp == '\n') {
8620 obp--;
8621 ibp++;
8623 break;
8625 case '/':
8626 if (*ibp == '\\' && ibp[1] == '\n')
8627 newline_fix (ibp);
8628 /* Delete any comment. */
8629 if (cplusplus_comments && ibp[0] == '/') {
8630 /* Comments are equivalent to spaces. */
8631 obp[-1] = ' ';
8632 ibp++;
8633 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8634 ibp++;
8635 break;
8637 if (ibp[0] != '*' || ibp + 1 >= limit)
8638 break;
8639 /* Comments are equivalent to spaces.
8640 For -traditional, a comment is equivalent to nothing. */
8641 if (traditional)
8642 obp--;
8643 else
8644 obp[-1] = ' ';
8645 ibp++;
8646 while (ibp + 1 < limit) {
8647 if (ibp[0] == '*'
8648 && ibp[1] == '\\' && ibp[2] == '\n')
8649 newline_fix (ibp + 1);
8650 if (ibp[0] == '*' && ibp[1] == '/')
8651 break;
8652 ibp++;
8654 ibp += 2;
8655 break;
8657 case '\'':
8658 case '\"':
8659 /* Notice and skip strings, so that we don't
8660 think that comments start inside them,
8661 and so we don't duplicate newlines in them. */
8663 int quotec = c;
8664 while (ibp < limit) {
8665 *obp++ = c = *ibp++;
8666 if (c == quotec)
8667 break;
8668 if (c == '\n' && quotec == '\'')
8669 break;
8670 if (c == '\\' && ibp < limit) {
8671 while (*ibp == '\\' && ibp[1] == '\n')
8672 ibp += 2;
8673 *obp++ = *ibp++;
8677 break;
8681 return obp - start;
8684 /* Turn newlines to spaces in the string of length LENGTH at START,
8685 except inside of string constants.
8686 The string is copied into itself with its beginning staying fixed. */
8688 static int
8689 change_newlines (start, length)
8690 U_CHAR *start;
8691 int length;
8693 register U_CHAR *ibp;
8694 register U_CHAR *obp;
8695 register U_CHAR *limit;
8696 register int c;
8698 ibp = start;
8699 limit = start + length;
8700 obp = start;
8702 while (ibp < limit) {
8703 *obp++ = c = *ibp++;
8704 switch (c) {
8705 case '\n':
8706 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8707 string. Skip past the newline and its duplicate.
8708 Put a space in the output. */
8709 if (*ibp == '\n')
8711 ibp++;
8712 obp--;
8713 *obp++ = ' ';
8715 break;
8717 case '\'':
8718 case '\"':
8719 /* Notice and skip strings, so that we don't delete newlines in them. */
8721 int quotec = c;
8722 while (ibp < limit) {
8723 *obp++ = c = *ibp++;
8724 if (c == quotec)
8725 break;
8726 if (c == '\n' && quotec == '\'')
8727 break;
8730 break;
8734 return obp - start;
8737 /* my_strerror - return the descriptive text associated with an
8738 `errno' code. */
8740 char *
8741 my_strerror (errnum)
8742 int errnum;
8744 char *result;
8746 #ifndef VMS
8747 #ifndef HAVE_STRERROR
8748 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8749 #else
8750 result = strerror (errnum);
8751 #endif
8752 #else /* VMS */
8753 /* VAXCRTL's strerror() takes an optional second argument, which only
8754 matters when the first argument is EVMSERR. However, it's simplest
8755 just to pass it unconditionally. `vaxc$errno' is declared in
8756 <errno.h>, and maintained by the library in parallel with `errno'.
8757 We assume that caller's `errnum' either matches the last setting of
8758 `errno' by the library or else does not have the value `EVMSERR'. */
8760 result = strerror (errnum, vaxc$errno);
8761 #endif
8763 if (!result)
8764 result = "undocumented I/O error";
8766 return result;
8769 /* error - print error message and increment count of errors. */
8771 void
8772 error (PRINTF_ALIST (msg))
8773 PRINTF_DCL (msg)
8775 va_list args;
8777 VA_START (args, msg);
8778 verror (msg, args);
8779 va_end (args);
8782 static void
8783 verror (msg, args)
8784 char *msg;
8785 va_list args;
8787 int i;
8788 FILE_BUF *ip = NULL;
8790 print_containing_files ();
8792 for (i = indepth; i >= 0; i--)
8793 if (instack[i].fname != NULL) {
8794 ip = &instack[i];
8795 break;
8798 if (ip != NULL)
8799 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8800 vfprintf (stderr, msg, args);
8801 fprintf (stderr, "\n");
8802 errors++;
8805 /* Error including a message from `errno'. */
8807 static void
8808 error_from_errno (name)
8809 char *name;
8811 int i;
8812 FILE_BUF *ip = NULL;
8814 print_containing_files ();
8816 for (i = indepth; i >= 0; i--)
8817 if (instack[i].fname != NULL) {
8818 ip = &instack[i];
8819 break;
8822 if (ip != NULL)
8823 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8825 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8827 errors++;
8830 /* Print error message but don't count it. */
8832 void
8833 warning (PRINTF_ALIST (msg))
8834 PRINTF_DCL (msg)
8836 va_list args;
8838 VA_START (args, msg);
8839 vwarning (msg, args);
8840 va_end (args);
8843 static void
8844 vwarning (msg, args)
8845 char *msg;
8846 va_list args;
8848 int i;
8849 FILE_BUF *ip = NULL;
8851 if (inhibit_warnings)
8852 return;
8854 if (warnings_are_errors)
8855 errors++;
8857 print_containing_files ();
8859 for (i = indepth; i >= 0; i--)
8860 if (instack[i].fname != NULL) {
8861 ip = &instack[i];
8862 break;
8865 if (ip != NULL)
8866 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8867 fprintf (stderr, "warning: ");
8868 vfprintf (stderr, msg, args);
8869 fprintf (stderr, "\n");
8872 static void
8873 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8874 error_with_line (int line, PRINTF_ALIST (msg))
8875 #else
8876 error_with_line (line, PRINTF_ALIST (msg))
8877 int line;
8878 PRINTF_DCL (msg)
8879 #endif
8881 va_list args;
8883 VA_START (args, msg);
8884 verror_with_line (line, msg, args);
8885 va_end (args);
8888 static void
8889 verror_with_line (line, msg, args)
8890 int line;
8891 char *msg;
8892 va_list args;
8894 int i;
8895 FILE_BUF *ip = NULL;
8897 print_containing_files ();
8899 for (i = indepth; i >= 0; i--)
8900 if (instack[i].fname != NULL) {
8901 ip = &instack[i];
8902 break;
8905 if (ip != NULL)
8906 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8907 vfprintf (stderr, msg, args);
8908 fprintf (stderr, "\n");
8909 errors++;
8912 static void
8913 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8914 warning_with_line (int line, PRINTF_ALIST (msg))
8915 #else
8916 warning_with_line (line, PRINTF_ALIST (msg))
8917 int line;
8918 PRINTF_DCL (msg)
8919 #endif
8921 va_list args;
8923 VA_START (args, msg);
8924 vwarning_with_line (line, msg, args);
8925 va_end (args);
8928 static void
8929 vwarning_with_line (line, msg, args)
8930 int line;
8931 char *msg;
8932 va_list args;
8934 int i;
8935 FILE_BUF *ip = NULL;
8937 if (inhibit_warnings)
8938 return;
8940 if (warnings_are_errors)
8941 errors++;
8943 print_containing_files ();
8945 for (i = indepth; i >= 0; i--)
8946 if (instack[i].fname != NULL) {
8947 ip = &instack[i];
8948 break;
8951 if (ip != NULL)
8952 fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
8953 fprintf (stderr, "warning: ");
8954 vfprintf (stderr, msg, args);
8955 fprintf (stderr, "\n");
8958 /* Print an error message and maybe count it. */
8960 void
8961 pedwarn (PRINTF_ALIST (msg))
8962 PRINTF_DCL (msg)
8964 va_list args;
8966 VA_START (args, msg);
8967 if (pedantic_errors)
8968 verror (msg, args);
8969 else
8970 vwarning (msg, args);
8971 va_end (args);
8974 void
8975 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8976 pedwarn_with_line (int line, PRINTF_ALIST (msg))
8977 #else
8978 pedwarn_with_line (line, PRINTF_ALIST (msg))
8979 int line;
8980 PRINTF_DCL (msg)
8981 #endif
8983 va_list args;
8985 VA_START (args, msg);
8986 if (pedantic_errors)
8987 verror_with_line (line, msg, args);
8988 else
8989 vwarning_with_line (line, msg, args);
8990 va_end (args);
8993 /* Report a warning (or an error if pedantic_errors)
8994 giving specified file name and line number, not current. */
8996 static void
8997 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8998 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
8999 #else
9000 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
9001 char *file;
9002 int line;
9003 PRINTF_DCL (msg)
9004 #endif
9006 va_list args;
9008 if (!pedantic_errors && inhibit_warnings)
9009 return;
9010 if (file != NULL)
9011 fprintf (stderr, "%s:%d: ", file, line);
9012 if (pedantic_errors)
9013 errors++;
9014 if (!pedantic_errors)
9015 fprintf (stderr, "warning: ");
9016 VA_START (args, msg);
9017 vfprintf (stderr, msg, args);
9018 va_end (args);
9019 fprintf (stderr, "\n");
9022 /* Print the file names and line numbers of the #include
9023 directives which led to the current file. */
9025 static void
9026 print_containing_files ()
9028 FILE_BUF *ip = NULL;
9029 int i;
9030 int first = 1;
9032 /* If stack of files hasn't changed since we last printed
9033 this info, don't repeat it. */
9034 if (last_error_tick == input_file_stack_tick)
9035 return;
9037 for (i = indepth; i >= 0; i--)
9038 if (instack[i].fname != NULL) {
9039 ip = &instack[i];
9040 break;
9043 /* Give up if we don't find a source file. */
9044 if (ip == NULL)
9045 return;
9047 /* Find the other, outer source files. */
9048 for (i--; i >= 0; i--)
9049 if (instack[i].fname != NULL) {
9050 ip = &instack[i];
9051 if (first) {
9052 first = 0;
9053 fprintf (stderr, "In file included");
9054 } else {
9055 fprintf (stderr, ",\n ");
9058 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9060 if (! first)
9061 fprintf (stderr, ":\n");
9063 /* Record we have printed the status as of this time. */
9064 last_error_tick = input_file_stack_tick;
9067 /* Return the line at which an error occurred.
9068 The error is not necessarily associated with the current spot
9069 in the input stack, so LINE says where. LINE will have been
9070 copied from ip->lineno for the current input level.
9071 If the current level is for a file, we return LINE.
9072 But if the current level is not for a file, LINE is meaningless.
9073 In that case, we return the lineno of the innermost file. */
9075 static int
9076 line_for_error (line)
9077 int line;
9079 int i;
9080 int line1 = line;
9082 for (i = indepth; i >= 0; ) {
9083 if (instack[i].fname != 0)
9084 return line1;
9085 i--;
9086 if (i < 0)
9087 return 0;
9088 line1 = instack[i].lineno;
9090 abort ();
9091 /*NOTREACHED*/
9092 return 0;
9096 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9098 * As things stand, nothing is ever placed in the output buffer to be
9099 * removed again except when it's KNOWN to be part of an identifier,
9100 * so flushing and moving down everything left, instead of expanding,
9101 * should work ok.
9104 /* You might think void was cleaner for the return type,
9105 but that would get type mismatch in check_expand in strict ANSI. */
9107 static int
9108 grow_outbuf (obuf, needed)
9109 register FILE_BUF *obuf;
9110 register int needed;
9112 register U_CHAR *p;
9113 int minsize;
9115 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9116 return 0;
9118 /* Make it at least twice as big as it is now. */
9119 obuf->length *= 2;
9120 /* Make it have at least 150% of the free space we will need. */
9121 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9122 if (minsize > obuf->length)
9123 obuf->length = minsize;
9125 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9126 memory_full ();
9128 obuf->bufp = p + (obuf->bufp - obuf->buf);
9129 obuf->buf = p;
9131 return 0;
9134 /* Symbol table for macro names and special symbols */
9137 * install a name in the main hash table, even if it is already there.
9138 * name stops with first non alphanumeric, except leading '#'.
9139 * caller must check against redefinition if that is desired.
9140 * delete_macro () removes things installed by install () in fifo order.
9141 * this is important because of the `defined' special symbol used
9142 * in #if, and also if pushdef/popdef directives are ever implemented.
9144 * If LEN is >= 0, it is the length of the name.
9145 * Otherwise, compute the length by scanning the entire name.
9147 * If HASH is >= 0, it is the precomputed hash code.
9148 * Otherwise, compute the hash code.
9151 static HASHNODE *
9152 install (name, len, type, value, hash)
9153 U_CHAR *name;
9154 int len;
9155 enum node_type type;
9156 char *value;
9157 int hash;
9159 register HASHNODE *hp;
9160 register int i, bucket;
9161 register U_CHAR *p, *q;
9163 if (len < 0) {
9164 p = name;
9165 while (is_idchar[*p])
9166 p++;
9167 len = p - name;
9170 if (hash < 0)
9171 hash = hashf (name, len, HASHSIZE);
9173 i = sizeof (HASHNODE) + len + 1;
9174 hp = (HASHNODE *) xmalloc (i);
9175 bucket = hash;
9176 hp->bucket_hdr = &hashtab[bucket];
9177 hp->next = hashtab[bucket];
9178 hashtab[bucket] = hp;
9179 hp->prev = NULL;
9180 if (hp->next != NULL)
9181 hp->next->prev = hp;
9182 hp->type = type;
9183 hp->length = len;
9184 hp->value.cpval = value;
9185 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9186 p = hp->name;
9187 q = name;
9188 for (i = 0; i < len; i++)
9189 *p++ = *q++;
9190 hp->name[len] = 0;
9191 return hp;
9195 * find the most recent hash node for name name (ending with first
9196 * non-identifier char) installed by install
9198 * If LEN is >= 0, it is the length of the name.
9199 * Otherwise, compute the length by scanning the entire name.
9201 * If HASH is >= 0, it is the precomputed hash code.
9202 * Otherwise, compute the hash code.
9205 HASHNODE *
9206 lookup (name, len, hash)
9207 U_CHAR *name;
9208 int len;
9209 int hash;
9211 register U_CHAR *bp;
9212 register HASHNODE *bucket;
9214 if (len < 0) {
9215 for (bp = name; is_idchar[*bp]; bp++) ;
9216 len = bp - name;
9219 if (hash < 0)
9220 hash = hashf (name, len, HASHSIZE);
9222 bucket = hashtab[hash];
9223 while (bucket) {
9224 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9225 return bucket;
9226 bucket = bucket->next;
9228 return NULL;
9232 * Delete a hash node. Some weirdness to free junk from macros.
9233 * More such weirdness will have to be added if you define more hash
9234 * types that need it.
9237 /* Note that the DEFINITION of a macro is removed from the hash table
9238 but its storage is not freed. This would be a storage leak
9239 except that it is not reasonable to keep undefining and redefining
9240 large numbers of macros many times.
9241 In any case, this is necessary, because a macro can be #undef'd
9242 in the middle of reading the arguments to a call to it.
9243 If #undef freed the DEFINITION, that would crash. */
9245 static void
9246 delete_macro (hp)
9247 HASHNODE *hp;
9250 if (hp->prev != NULL)
9251 hp->prev->next = hp->next;
9252 if (hp->next != NULL)
9253 hp->next->prev = hp->prev;
9255 /* Make sure that the bucket chain header that the deleted guy was
9256 on points to the right thing afterwards. */
9257 if (hp == *hp->bucket_hdr)
9258 *hp->bucket_hdr = hp->next;
9260 #if 0
9261 if (hp->type == T_MACRO) {
9262 DEFINITION *d = hp->value.defn;
9263 struct reflist *ap, *nextap;
9265 for (ap = d->pattern; ap != NULL; ap = nextap) {
9266 nextap = ap->next;
9267 free (ap);
9269 free (d);
9271 #endif
9272 free (hp);
9276 * return hash function on name. must be compatible with the one
9277 * computed a step at a time, elsewhere
9280 static int
9281 hashf (name, len, hashsize)
9282 register U_CHAR *name;
9283 register int len;
9284 int hashsize;
9286 register int r = 0;
9288 while (len--)
9289 r = HASHSTEP (r, *name++);
9291 return MAKE_POS (r) % hashsize;
9295 /* Dump the definition of a single macro HP to OF. */
9297 static void
9298 dump_single_macro (hp, of)
9299 register HASHNODE *hp;
9300 FILE *of;
9302 register DEFINITION *defn = hp->value.defn;
9303 struct reflist *ap;
9304 int offset;
9305 int concat;
9308 /* Print the definition of the macro HP. */
9310 fprintf (of, "#define %s", hp->name);
9312 if (defn->nargs >= 0) {
9313 int i;
9315 fprintf (of, "(");
9316 for (i = 0; i < defn->nargs; i++) {
9317 dump_arg_n (defn, i, of);
9318 if (i + 1 < defn->nargs)
9319 fprintf (of, ", ");
9321 fprintf (of, ")");
9324 fprintf (of, " ");
9326 offset = 0;
9327 concat = 0;
9328 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9329 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9330 offset += ap->nchars;
9331 if (!traditional) {
9332 if (ap->nchars != 0)
9333 concat = 0;
9334 if (ap->stringify) {
9335 switch (ap->stringify) {
9336 case SHARP_TOKEN: fprintf (of, "#"); break;
9337 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9338 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9339 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9340 default: abort ();
9343 if (ap->raw_before != 0) {
9344 if (concat) {
9345 switch (ap->raw_before) {
9346 case WHITE_SHARP_TOKEN:
9347 case WHITE_PERCENT_COLON_TOKEN:
9348 fprintf (of, " ");
9349 break;
9350 default:
9351 break;
9353 } else {
9354 switch (ap->raw_before) {
9355 case SHARP_TOKEN: fprintf (of, "##"); break;
9356 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9357 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9358 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9359 default: abort ();
9363 concat = 0;
9365 dump_arg_n (defn, ap->argno, of);
9366 if (!traditional && ap->raw_after != 0) {
9367 switch (ap->raw_after) {
9368 case SHARP_TOKEN: fprintf (of, "##"); break;
9369 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9370 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9371 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9372 default: abort ();
9374 concat = 1;
9377 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9378 fprintf (of, "\n");
9381 /* Dump all macro definitions as #defines to stdout. */
9383 static void
9384 dump_all_macros ()
9386 int bucket;
9388 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9389 register HASHNODE *hp;
9391 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9392 if (hp->type == T_MACRO)
9393 dump_single_macro (hp, stdout);
9398 /* Output to OF a substring of a macro definition.
9399 BASE is the beginning of the definition.
9400 Output characters START thru LENGTH.
9401 Unless traditional, discard newlines outside of strings, thus
9402 converting funny-space markers to ordinary spaces. */
9404 static void
9405 dump_defn_1 (base, start, length, of)
9406 U_CHAR *base;
9407 int start;
9408 int length;
9409 FILE *of;
9411 U_CHAR *p = base + start;
9412 U_CHAR *limit = base + start + length;
9414 if (traditional)
9415 fwrite (p, sizeof (*p), length, of);
9416 else {
9417 while (p < limit) {
9418 if (*p == '\"' || *p =='\'') {
9419 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9420 NULL_PTR, NULL_PTR);
9421 fwrite (p, sizeof (*p), p1 - p, of);
9422 p = p1;
9423 } else {
9424 if (*p != '\n')
9425 putc (*p, of);
9426 p++;
9432 /* Print the name of argument number ARGNUM of macro definition DEFN
9433 to OF.
9434 Recall that DEFN->args.argnames contains all the arg names
9435 concatenated in reverse order with comma-space in between. */
9437 static void
9438 dump_arg_n (defn, argnum, of)
9439 DEFINITION *defn;
9440 int argnum;
9441 FILE *of;
9443 register U_CHAR *p = defn->args.argnames;
9444 while (argnum + 1 < defn->nargs) {
9445 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9446 argnum++;
9449 while (*p && *p != ',') {
9450 putc (*p, of);
9451 p++;
9455 /* Initialize syntactic classifications of characters. */
9457 static void
9458 initialize_char_syntax ()
9460 register int i;
9463 * Set up is_idchar and is_idstart tables. These should be
9464 * faster than saying (is_alpha (c) || c == '_'), etc.
9465 * Set up these things before calling any routines tthat
9466 * refer to them.
9468 for (i = 'a'; i <= 'z'; i++) {
9469 is_idchar[i - 'a' + 'A'] = 1;
9470 is_idchar[i] = 1;
9471 is_idstart[i - 'a' + 'A'] = 1;
9472 is_idstart[i] = 1;
9474 for (i = '0'; i <= '9'; i++)
9475 is_idchar[i] = 1;
9476 is_idchar['_'] = 1;
9477 is_idstart['_'] = 1;
9478 is_idchar['$'] = 1;
9479 is_idstart['$'] = 1;
9481 /* horizontal space table */
9482 is_hor_space[' '] = 1;
9483 is_hor_space['\t'] = 1;
9484 is_hor_space['\v'] = 1;
9485 is_hor_space['\f'] = 1;
9486 is_hor_space['\r'] = 1;
9488 is_space[' '] = 1;
9489 is_space['\t'] = 1;
9490 is_space['\v'] = 1;
9491 is_space['\f'] = 1;
9492 is_space['\n'] = 1;
9493 is_space['\r'] = 1;
9495 char_name['\v'] = "vertical tab";
9496 char_name['\f'] = "formfeed";
9497 char_name['\r'] = "carriage return";
9500 /* Initialize the built-in macros. */
9502 static void
9503 initialize_builtins (inp, outp)
9504 FILE_BUF *inp;
9505 FILE_BUF *outp;
9507 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9508 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9509 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9510 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9511 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9512 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9513 #ifndef NO_BUILTIN_SIZE_TYPE
9514 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9515 #endif
9516 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9517 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9518 #endif
9519 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9520 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9521 NULL_PTR, -1);
9522 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9523 NULL_PTR, -1);
9524 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9525 NULL_PTR, -1);
9526 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9527 if (!traditional) {
9528 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9529 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9531 if (objc)
9532 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9533 /* This is supplied using a -D by the compiler driver
9534 so that it is present only when truly compiling with GNU C. */
9535 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9536 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9538 if (debug_output)
9540 char directive[2048];
9541 U_CHAR *udirective = (U_CHAR *) directive;
9542 register struct directive *dp = &directive_table[0];
9543 struct tm *timebuf = timestamp ();
9545 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9546 instack[0].nominal_fname);
9547 output_line_directive (inp, outp, 0, same_file);
9548 pass_thru_directive (udirective, &udirective[strlen (directive)],
9549 outp, dp);
9551 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9552 output_line_directive (inp, outp, 0, same_file);
9553 pass_thru_directive (udirective, &udirective[strlen (directive)],
9554 outp, dp);
9556 #ifndef NO_BUILTIN_SIZE_TYPE
9557 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9558 output_line_directive (inp, outp, 0, same_file);
9559 pass_thru_directive (udirective, &udirective[strlen (directive)],
9560 outp, dp);
9561 #endif
9563 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9564 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9565 output_line_directive (inp, outp, 0, same_file);
9566 pass_thru_directive (udirective, &udirective[strlen (directive)],
9567 outp, dp);
9568 #endif
9570 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9571 output_line_directive (inp, outp, 0, same_file);
9572 pass_thru_directive (udirective, &udirective[strlen (directive)],
9573 outp, dp);
9575 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9576 monthnames[timebuf->tm_mon],
9577 timebuf->tm_mday, timebuf->tm_year + 1900);
9578 output_line_directive (inp, outp, 0, same_file);
9579 pass_thru_directive (udirective, &udirective[strlen (directive)],
9580 outp, dp);
9582 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9583 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9584 output_line_directive (inp, outp, 0, same_file);
9585 pass_thru_directive (udirective, &udirective[strlen (directive)],
9586 outp, dp);
9588 if (!traditional)
9590 sprintf (directive, " __STDC__ 1");
9591 output_line_directive (inp, outp, 0, same_file);
9592 pass_thru_directive (udirective, &udirective[strlen (directive)],
9593 outp, dp);
9595 if (objc)
9597 sprintf (directive, " __OBJC__ 1");
9598 output_line_directive (inp, outp, 0, same_file);
9599 pass_thru_directive (udirective, &udirective[strlen (directive)],
9600 outp, dp);
9606 * process a given definition string, for initialization
9607 * If STR is just an identifier, define it with value 1.
9608 * If STR has anything after the identifier, then it should
9609 * be identifier=definition.
9612 static void
9613 make_definition (str, op)
9614 char *str;
9615 FILE_BUF *op;
9617 FILE_BUF *ip;
9618 struct directive *kt;
9619 U_CHAR *buf, *p;
9621 p = buf = (U_CHAR *) str;
9622 if (!is_idstart[*p]) {
9623 error ("malformed option `-D %s'", str);
9624 return;
9626 while (is_idchar[*++p])
9628 if (*p == '(') {
9629 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9631 if (*p++ != ')')
9632 p = (U_CHAR *) str; /* Error */
9634 if (*p == 0) {
9635 buf = (U_CHAR *) alloca (p - buf + 4);
9636 strcpy ((char *)buf, str);
9637 strcat ((char *)buf, " 1");
9638 } else if (*p != '=') {
9639 error ("malformed option `-D %s'", str);
9640 return;
9641 } else {
9642 U_CHAR *q;
9643 /* Copy the entire option so we can modify it. */
9644 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9645 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9646 /* Change the = to a space. */
9647 buf[p - (U_CHAR *) str] = ' ';
9648 /* Scan for any backslash-newline and remove it. */
9649 p++;
9650 q = &buf[p - (U_CHAR *) str];
9651 while (*p) {
9652 if (*p == '\"' || *p == '\'') {
9653 int unterminated = 0;
9654 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9655 NULL_PTR, NULL_PTR, &unterminated);
9656 if (unterminated)
9657 return;
9658 while (p != p1)
9659 if (*p == '\\' && p[1] == '\n')
9660 p += 2;
9661 else
9662 *q++ = *p++;
9663 } else if (*p == '\\' && p[1] == '\n')
9664 p += 2;
9665 /* Change newline chars into newline-markers. */
9666 else if (*p == '\n')
9668 *q++ = '\n';
9669 *q++ = '\n';
9670 p++;
9672 else
9673 *q++ = *p++;
9675 *q = 0;
9678 ip = &instack[++indepth];
9679 ip->nominal_fname = ip->fname = "*Initialization*";
9681 ip->buf = ip->bufp = buf;
9682 ip->length = strlen ((char *) buf);
9683 ip->lineno = 1;
9684 ip->macro = 0;
9685 ip->free_ptr = 0;
9686 ip->if_stack = if_stack;
9687 ip->system_header_p = 0;
9689 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9692 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9693 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9694 --indepth;
9697 /* JF, this does the work for the -U option */
9699 static void
9700 make_undef (str, op)
9701 char *str;
9702 FILE_BUF *op;
9704 FILE_BUF *ip;
9705 struct directive *kt;
9707 ip = &instack[++indepth];
9708 ip->nominal_fname = ip->fname = "*undef*";
9710 ip->buf = ip->bufp = (U_CHAR *) str;
9711 ip->length = strlen (str);
9712 ip->lineno = 1;
9713 ip->macro = 0;
9714 ip->free_ptr = 0;
9715 ip->if_stack = if_stack;
9716 ip->system_header_p = 0;
9718 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9721 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9722 --indepth;
9725 /* Process the string STR as if it appeared as the body of a #assert.
9726 OPTION is the option name for which STR was the argument. */
9728 static void
9729 make_assertion (option, str)
9730 char *option;
9731 char *str;
9733 FILE_BUF *ip;
9734 struct directive *kt;
9735 U_CHAR *buf, *p, *q;
9737 /* Copy the entire option so we can modify it. */
9738 buf = (U_CHAR *) alloca (strlen (str) + 1);
9739 strcpy ((char *) buf, str);
9740 /* Scan for any backslash-newline and remove it. */
9741 p = q = buf;
9742 while (*p) {
9743 if (*p == '\\' && p[1] == '\n')
9744 p += 2;
9745 else
9746 *q++ = *p++;
9748 *q = 0;
9750 p = buf;
9751 if (!is_idstart[*p]) {
9752 error ("malformed option `%s %s'", option, str);
9753 return;
9755 while (is_idchar[*++p])
9757 SKIP_WHITE_SPACE (p);
9758 if (! (*p == 0 || *p == '(')) {
9759 error ("malformed option `%s %s'", option, str);
9760 return;
9763 ip = &instack[++indepth];
9764 ip->nominal_fname = ip->fname = "*Initialization*";
9766 ip->buf = ip->bufp = buf;
9767 ip->length = strlen ((char *) buf);
9768 ip->lineno = 1;
9769 ip->macro = 0;
9770 ip->free_ptr = 0;
9771 ip->if_stack = if_stack;
9772 ip->system_header_p = 0;
9774 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9777 /* Pass NULL as output ptr to do_define since we KNOW it never does
9778 any output.... */
9779 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9780 --indepth;
9783 #ifndef DIR_SEPARATOR
9784 #define DIR_SEPARATOR '/'
9785 #endif
9787 /* The previous include prefix, if any, is PREV_FILE_NAME.
9788 Translate any pathnames with COMPONENT.
9789 Allocate a new include prefix whose name is the
9790 simplified concatenation of PREFIX and NAME,
9791 with a trailing / added if needed.
9792 But return 0 if the include prefix should be ignored,
9793 e.g. because it is a duplicate of PREV_FILE_NAME. */
9795 static struct file_name_list *
9796 new_include_prefix (prev_file_name, component, prefix, name)
9797 struct file_name_list *prev_file_name;
9798 char *component;
9799 char *prefix;
9800 char *name;
9802 if (name == 0)
9803 fatal ("Directory name missing after command line option");
9805 if (*name == 0)
9806 /* Ignore the empty string. */
9807 return 0;
9809 prefix = update_path (prefix, component);
9810 name = update_path (name, component);
9813 struct file_name_list *dir
9814 = ((struct file_name_list *)
9815 xmalloc (sizeof (struct file_name_list)
9816 + strlen (prefix) + strlen (name) + 2));
9817 size_t len;
9818 strcpy (dir->fname, prefix);
9819 strcat (dir->fname, name);
9820 len = simplify_filename (dir->fname);
9822 /* Convert directory name to a prefix. */
9823 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
9824 if (len == 1 && dir->fname[len - 1] == '.')
9825 len = 0;
9826 else
9827 dir->fname[len++] = DIR_SEPARATOR;
9828 dir->fname[len] = 0;
9831 /* Ignore a directory whose name matches the previous one. */
9832 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9833 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9834 if (!first_bracket_include)
9835 first_bracket_include = prev_file_name;
9836 free (dir);
9837 return 0;
9840 #ifndef VMS
9841 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
9843 /* Add a trailing "." if there is a filename. This increases the number
9844 of systems that can stat directories. We remove it below. */
9845 if (len != 0)
9847 dir->fname[len] = '.';
9848 dir->fname[len + 1] = 0;
9851 /* Ignore a nonexistent directory. */
9852 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9853 if (errno != ENOENT && errno != ENOTDIR)
9854 error_from_errno (dir->fname);
9855 free (dir);
9856 return 0;
9859 if (len != 0)
9860 dir->fname[len] = 0;
9862 /* Ignore a directory whose identity matches the previous one. */
9863 if (prev_file_name
9864 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9865 && prev_file_name->st.st_dev == dir->st.st_dev) {
9866 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9867 if (!first_bracket_include)
9868 first_bracket_include = prev_file_name;
9869 free (dir);
9870 return 0;
9872 #endif /* ! VMS */
9874 dir->next = 0;
9875 dir->c_system_include_path = 0;
9876 dir->got_name_map = 0;
9878 return dir;
9882 /* Append a chain of `struct file_name_list's
9883 to the end of the main include chain.
9884 FIRST is the beginning of the chain to append, and LAST is the end. */
9886 static void
9887 append_include_chain (first, last)
9888 struct file_name_list *first, *last;
9890 struct file_name_list *dir;
9892 if (!first || !last)
9893 return;
9895 if (include == 0)
9896 include = first;
9897 else
9898 last_include->next = first;
9900 if (first_bracket_include == 0)
9901 first_bracket_include = first;
9903 for (dir = first; ; dir = dir->next) {
9904 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9905 if (len > max_include_len)
9906 max_include_len = len;
9907 if (dir == last)
9908 break;
9911 last->next = NULL;
9912 last_include = last;
9915 /* Place into DST a representation of the file named SRC that is suitable
9916 for `make'. Do not null-terminate DST. Return its length. */
9917 static int
9918 quote_string_for_make (dst, src)
9919 char *dst;
9920 char *src;
9922 char *p = src;
9923 int i = 0;
9924 for (;;)
9926 char c = *p++;
9927 switch (c)
9929 case '\0':
9930 case ' ':
9931 case '\t':
9933 /* GNU make uses a weird quoting scheme for white space.
9934 A space or tab preceded by 2N+1 backslashes represents
9935 N backslashes followed by space; a space or tab
9936 preceded by 2N backslashes represents N backslashes at
9937 the end of a file name; and backslashes in other
9938 contexts should not be doubled. */
9939 char *q;
9940 for (q = p - 1; src < q && q[-1] == '\\'; q--)
9942 if (dst)
9943 dst[i] = '\\';
9944 i++;
9947 if (!c)
9948 return i;
9949 if (dst)
9950 dst[i] = '\\';
9951 i++;
9952 goto ordinary_char;
9954 case '$':
9955 if (dst)
9956 dst[i] = c;
9957 i++;
9958 /* Fall through. This can mishandle things like "$(" but
9959 there's no easy fix. */
9960 default:
9961 ordinary_char:
9962 /* This can mishandle characters in the string "\0\n%*?[\\~";
9963 exactly which chars are mishandled depends on the `make' version.
9964 We know of no portable solution for this;
9965 even GNU make 3.76.1 doesn't solve the problem entirely.
9966 (Also, '\0' is mishandled due to our calling conventions.) */
9967 if (dst)
9968 dst[i] = c;
9969 i++;
9970 break;
9976 /* Add output to `deps_buffer' for the -M switch.
9977 STRING points to the text to be output.
9978 SPACER is ':' for targets, ' ' for dependencies. */
9980 static void
9981 deps_output (string, spacer)
9982 char *string;
9983 int spacer;
9985 int size = quote_string_for_make ((char *) 0, string);
9987 if (size == 0)
9988 return;
9990 #ifndef MAX_OUTPUT_COLUMNS
9991 #define MAX_OUTPUT_COLUMNS 72
9992 #endif
9993 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9994 && 1 < deps_column) {
9995 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9996 deps_size += 4;
9997 deps_column = 1;
9998 if (spacer == ' ')
9999 spacer = 0;
10002 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10003 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10004 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10006 if (spacer == ' ') {
10007 deps_buffer[deps_size++] = ' ';
10008 deps_column++;
10010 quote_string_for_make (&deps_buffer[deps_size], string);
10011 deps_size += size;
10012 deps_column += size;
10013 if (spacer == ':') {
10014 deps_buffer[deps_size++] = ':';
10015 deps_column++;
10017 deps_buffer[deps_size] = 0;
10020 static void
10021 fatal (PRINTF_ALIST (msg))
10022 PRINTF_DCL (msg)
10024 va_list args;
10026 fprintf (stderr, "%s: ", progname);
10027 VA_START (args, msg);
10028 vfprintf (stderr, msg, args);
10029 va_end (args);
10030 fprintf (stderr, "\n");
10031 exit (FATAL_EXIT_CODE);
10034 /* More 'friendly' abort that prints the line and file.
10035 config.h can #define abort fancy_abort if you like that sort of thing. */
10037 void
10038 fancy_abort ()
10040 fatal ("Internal gcc abort.");
10043 static void
10044 perror_with_name (name)
10045 char *name;
10047 fprintf (stderr, "%s: ", progname);
10048 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
10049 errors++;
10052 static void
10053 pfatal_with_name (name)
10054 char *name;
10056 perror_with_name (name);
10057 #ifdef VMS
10058 exit (vaxc$errno);
10059 #else
10060 exit (FATAL_EXIT_CODE);
10061 #endif
10064 /* Handler for SIGPIPE. */
10066 static void
10067 pipe_closed (signo)
10068 /* If this is missing, some compilers complain. */
10069 int signo;
10071 fatal ("output pipe has been closed");
10074 static void
10075 memory_full ()
10077 fatal ("Memory exhausted.");
10081 GENERIC_PTR
10082 xmalloc (size)
10083 size_t size;
10085 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10086 if (!ptr)
10087 memory_full ();
10088 return ptr;
10091 static GENERIC_PTR
10092 xrealloc (old, size)
10093 GENERIC_PTR old;
10094 size_t size;
10096 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10097 if (!ptr)
10098 memory_full ();
10099 return ptr;
10102 static GENERIC_PTR
10103 xcalloc (number, size)
10104 size_t number, size;
10106 register size_t total = number * size;
10107 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10108 if (!ptr)
10109 memory_full ();
10110 bzero (ptr, total);
10111 return ptr;
10114 static char *
10115 savestring (input)
10116 char *input;
10118 size_t size = strlen (input);
10119 char *output = xmalloc (size + 1);
10120 strcpy (output, input);
10121 return output;
10124 #ifdef VMS
10126 /* Under VMS we need to fix up the "include" specification filename so
10127 that everything following the 1st slash is changed into its correct
10128 VMS file specification. */
10130 static void
10131 hack_vms_include_specification (fname, vaxc_include)
10132 char *fname;
10133 int vaxc_include;
10135 register char *cp, *cp1, *cp2;
10136 int f, check_filename_before_returning;
10137 char Local[512];
10139 check_filename_before_returning = 0;
10141 cp = base_name (fname);
10144 * Check if we have a vax-c style '#include filename'
10145 * and add the missing .h
10147 if (vaxc_include && !index (cp,'.'))
10148 strcat (cp, ".h");
10150 cp2 = Local; /* initialize */
10152 /* We are trying to do a number of things here. First of all, we are
10153 trying to hammer the filenames into a standard format, such that later
10154 processing can handle them.
10156 If the file name contains something like [dir.], then it recognizes this
10157 as a root, and strips the ".]". Later processing will add whatever is
10158 needed to get things working properly.
10160 If no device is specified, then the first directory name is taken to be
10161 a device name (or a rooted logical). */
10163 /* See if we found that 1st slash */
10164 if (cp == 0) return; /* Nothing to do!!! */
10165 if (*cp != '/') return; /* Nothing to do!!! */
10166 /* Point to the UNIX filename part (which needs to be fixed!) */
10167 cp1 = cp+1;
10168 /* If the directory spec is not rooted, we can just copy
10169 the UNIX filename part and we are done */
10170 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10171 if (cp[-2] != '.') {
10173 * The VMS part ends in a `]', and the preceding character is not a `.'.
10174 * We strip the `]', and then splice the two parts of the name in the
10175 * usual way. Given the default locations for include files in cccp.c,
10176 * we will only use this code if the user specifies alternate locations
10177 * with the /include (-I) switch on the command line. */
10178 cp -= 1; /* Strip "]" */
10179 cp1--; /* backspace */
10180 } else {
10182 * The VMS part has a ".]" at the end, and this will not do. Later
10183 * processing will add a second directory spec, and this would be a syntax
10184 * error. Thus we strip the ".]", and thus merge the directory specs.
10185 * We also backspace cp1, so that it points to a '/'. This inhibits the
10186 * generation of the 000000 root directory spec (which does not belong here
10187 * in this case).
10189 cp -= 2; /* Strip ".]" */
10190 cp1--; }; /* backspace */
10191 } else {
10193 /* We drop in here if there is no VMS style directory specification yet.
10194 * If there is no device specification either, we make the first dir a
10195 * device and try that. If we do not do this, then we will be essentially
10196 * searching the users default directory (as if they did a #include "asdf.h").
10198 * Then all we need to do is to push a '[' into the output string. Later
10199 * processing will fill this in, and close the bracket.
10201 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10202 *cp2++ = '['; /* Open the directory specification */
10205 /* at this point we assume that we have the device spec, and (at least
10206 the opening "[" for a directory specification. We may have directories
10207 specified already */
10209 /* If there are no other slashes then the filename will be
10210 in the "root" directory. Otherwise, we need to add
10211 directory specifications. */
10212 if (index (cp1, '/') == 0) {
10213 /* Just add "000000]" as the directory string */
10214 strcpy (cp2, "000000]");
10215 cp2 += strlen (cp2);
10216 check_filename_before_returning = 1; /* we might need to fool with this later */
10217 } else {
10218 /* As long as there are still subdirectories to add, do them. */
10219 while (index (cp1, '/') != 0) {
10220 /* If this token is "." we can ignore it */
10221 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10222 cp1 += 2;
10223 continue;
10225 /* Add a subdirectory spec. Do not duplicate "." */
10226 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10227 *cp2++ = '.';
10228 /* If this is ".." then the spec becomes "-" */
10229 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10230 /* Add "-" and skip the ".." */
10231 *cp2++ = '-';
10232 cp1 += 3;
10233 continue;
10235 /* Copy the subdirectory */
10236 while (*cp1 != '/') *cp2++= *cp1++;
10237 cp1++; /* Skip the "/" */
10239 /* Close the directory specification */
10240 if (cp2[-1] == '.') /* no trailing periods */
10241 cp2--;
10242 *cp2++ = ']';
10244 /* Now add the filename */
10245 while (*cp1) *cp2++ = *cp1++;
10246 *cp2 = 0;
10247 /* Now append it to the original VMS spec. */
10248 strcpy (cp, Local);
10250 /* If we put a [000000] in the filename, try to open it first. If this fails,
10251 remove the [000000], and return that name. This provides flexibility
10252 to the user in that they can use both rooted and non-rooted logical names
10253 to point to the location of the file. */
10255 if (check_filename_before_returning) {
10256 f = open (fname, O_RDONLY, 0666);
10257 if (f >= 0) {
10258 /* The file name is OK as it is, so return it as is. */
10259 close (f);
10260 return;
10262 /* The filename did not work. Try to remove the [000000] from the name,
10263 and return it. */
10264 cp = index (fname, '[');
10265 cp2 = index (fname, ']') + 1;
10266 strcpy (cp, cp2); /* this gets rid of it */
10268 return;
10270 #endif /* VMS */
10272 #ifdef VMS
10274 /* The following wrapper functions supply additional arguments to the VMS
10275 I/O routines to optimize performance with file handling. The arguments
10276 are:
10277 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10278 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10279 "fop=tef"- Truncate unused portions of file when closing file.
10280 "shr=nil"- Disallow file sharing while file is open. */
10282 static FILE *
10283 VMS_freopen (fname, type, oldfile)
10284 char *fname;
10285 char *type;
10286 FILE *oldfile;
10288 #undef freopen /* Get back the real freopen routine. */
10289 if (strcmp (type, "w") == 0)
10290 return freopen (fname, type, oldfile,
10291 "mbc=16", "deq=64", "fop=tef", "shr=nil");
10292 return freopen (fname, type, oldfile, "mbc=16");
10295 static FILE *
10296 VMS_fopen (fname, type)
10297 char *fname;
10298 char *type;
10300 #undef fopen /* Get back the real fopen routine. */
10301 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10302 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10303 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10304 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10306 if (*type == 'w')
10307 return (*vmslib_fopen) (fname, type, "mbc=32",
10308 "deq=64", "fop=tef", "shr=nil");
10309 else
10310 return (*vmslib_fopen) (fname, type, "mbc=32");
10313 static int
10314 VMS_open (fname, flags, prot)
10315 char *fname;
10316 int flags;
10317 int prot;
10319 #undef open /* Get back the real open routine. */
10320 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10323 /* more VMS hackery */
10324 #include <fab.h>
10325 #include <nam.h>
10327 extern unsigned long SYS$PARSE(), SYS$SEARCH();
10329 /* Work around another library bug. If a file is located via a searchlist,
10330 and if the device it's on is not the same device as the one specified
10331 in the first element of that searchlist, then both stat() and fstat()
10332 will fail to return info about it. `errno' will be set to EVMSERR, and
10333 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10334 We can get around this by fully parsing the filename and then passing
10335 that absolute name to stat().
10337 Without this fix, we can end up failing to find header files, which is
10338 bad enough, but then compounding the problem by reporting the reason for
10339 failure as "normal successful completion." */
10341 #undef fstat /* Get back to the library version. */
10343 static int
10344 VMS_fstat (fd, statbuf)
10345 int fd;
10346 struct stat *statbuf;
10348 int result = fstat (fd, statbuf);
10350 if (result < 0)
10352 FILE *fp;
10353 char nambuf[NAM$C_MAXRSS+1];
10355 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10356 result = VMS_stat (nambuf, statbuf);
10357 /* No fclose(fp) here; that would close(fd) as well. */
10360 return result;
10363 static int
10364 VMS_stat (name, statbuf)
10365 const char *name;
10366 struct stat *statbuf;
10368 int result = stat (name, statbuf);
10370 if (result < 0)
10372 struct FAB fab;
10373 struct NAM nam;
10374 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
10375 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
10377 fab = cc$rms_fab;
10378 fab.fab$l_fna = (char *) name;
10379 fab.fab$b_fns = (unsigned char) strlen (name);
10380 fab.fab$l_nam = (void *) &nam;
10381 nam = cc$rms_nam;
10382 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10383 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10384 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10385 if (SYS$PARSE (&fab) & 1)
10387 if (SYS$SEARCH (&fab) & 1)
10389 res_nam[nam.nam$b_rsl] = '\0';
10390 result = stat (res_nam, statbuf);
10392 /* Clean up searchlist context cached by the system. */
10393 nam.nam$b_nop = NAM$M_SYNCHK;
10394 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10395 (void) SYS$PARSE (&fab);
10399 return result;
10401 #endif /* VMS */