import of gcc-2.8
[official-gcc.git] / gcc / cccp.c
blob776597394f90ce3c6376937e86856c5d5a26d98f
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 # inclued <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 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
134 #define fopen(fname,mode) VMS_fopen (fname,mode)
135 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
136 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
137 static int VMS_fstat (), VMS_stat ();
138 static int VMS_open ();
139 static FILE *VMS_fopen ();
140 static FILE *VMS_freopen ();
141 static void hack_vms_include_specification ();
142 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
143 #define INO_T_HASH(a) 0
144 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
145 #endif /* VMS */
147 /* Windows does not natively support inodes, and neither does MSDOS. */
148 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
149 #define INO_T_EQ(a, b) 0
150 #endif
152 #ifndef O_RDONLY
153 #define O_RDONLY 0
154 #endif
156 #undef MIN
157 #undef MAX
158 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
159 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
161 /* Find the largest host integer type and set its size and type.
162 Watch out: on some crazy hosts `long' is shorter than `int'. */
164 #ifndef HOST_WIDE_INT
165 # if HAVE_INTTYPES_H
166 # include <inttypes.h>
167 # define HOST_WIDE_INT intmax_t
168 # else
169 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
170 # define HOST_WIDE_INT int
171 # else
172 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
173 # define HOST_WIDE_INT long
174 # else
175 # define HOST_WIDE_INT long long
176 # endif
177 # endif
178 # endif
179 #endif
181 #ifndef S_ISREG
182 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
183 #endif
185 #ifndef S_ISDIR
186 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
187 #endif
189 #ifndef INO_T_EQ
190 #define INO_T_EQ(a, b) ((a) == (b))
191 #endif
193 #ifndef INO_T_HASH
194 #define INO_T_HASH(a) (a)
195 #endif
197 #ifndef INCLUDE_LEN_FUDGE
198 #define INCLUDE_LEN_FUDGE 0
199 #endif
201 /* External declarations. */
203 extern char *version_string;
204 extern char *update_path PROTO((char *, char *));
205 #ifndef VMS
206 #ifndef HAVE_STRERROR
207 extern int sys_nerr;
208 extern char *sys_errlist[];
209 #else /* HAVE_STRERROR */
210 char *strerror ();
211 #endif
212 #else /* VMS */
213 char *strerror (int,...);
214 #endif
215 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
216 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
218 #ifndef errno
219 extern int errno;
220 #endif
222 /* Name under which this program was invoked. */
224 static char *progname;
226 /* Nonzero means use extra default include directories for C++. */
228 static int cplusplus;
230 /* Nonzero means handle cplusplus style comments */
232 static int cplusplus_comments;
234 /* Nonzero means handle #import, for objective C. */
236 static int objc;
238 /* Nonzero means this is an assembly file, and allow
239 unknown directives, which could be comments. */
241 static int lang_asm;
243 /* Current maximum length of directory names in the search path
244 for include files. (Altered as we get more of them.) */
246 static int max_include_len;
248 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
250 static int for_lint = 0;
252 /* Nonzero means copy comments into the output file. */
254 static int put_out_comments = 0;
256 /* Nonzero means don't process the ANSI trigraph sequences. */
258 static int no_trigraphs = 0;
260 /* Nonzero means print the names of included files rather than
261 the preprocessed output. 1 means just the #include "...",
262 2 means #include <...> as well. */
264 static int print_deps = 0;
266 /* Nonzero if missing .h files in -M output are assumed to be generated
267 files and not errors. */
269 static int print_deps_missing_files = 0;
271 /* Nonzero means print names of header files (-H). */
273 static int print_include_names = 0;
275 /* Nonzero means don't output line number information. */
277 static int no_line_directives;
279 /* Nonzero means output the text in failing conditionals,
280 inside #failed ... #endfailed. */
282 static int output_conditionals;
284 /* dump_only means inhibit output of the preprocessed text
285 and instead output the definitions of all user-defined
286 macros in a form suitable for use as input to cccp.
287 dump_names means pass #define and the macro name through to output.
288 dump_definitions means pass the whole definition (plus #define) through
291 static enum {dump_none, dump_only, dump_names, dump_definitions}
292 dump_macros = dump_none;
294 /* Nonzero means pass all #define and #undef directives which we actually
295 process through to the output stream. This feature is used primarily
296 to allow cc1 to record the #defines and #undefs for the sake of
297 debuggers which understand about preprocessor macros, but it may
298 also be useful with -E to figure out how symbols are defined, and
299 where they are defined. */
300 static int debug_output = 0;
302 /* Nonzero means pass #include lines through to the output,
303 even if they are ifdefed out. */
304 static int dump_includes;
306 /* Nonzero indicates special processing used by the pcp program. The
307 special effects of this mode are:
309 Inhibit all macro expansion, except those inside #if directives.
311 Process #define directives normally, and output their contents
312 to the output file.
314 Output preconditions to pcp_outfile indicating all the relevant
315 preconditions for use of this file in a later cpp run.
317 static FILE *pcp_outfile;
319 /* Nonzero means we are inside an IF during a -pcp run. In this mode
320 macro expansion is done, and preconditions are output for all macro
321 uses requiring them. */
322 static int pcp_inside_if;
324 /* Nonzero means never to include precompiled files.
325 This is 1 since there's no way now to make precompiled files,
326 so it's not worth testing for them. */
327 static int no_precomp = 1;
329 /* Nonzero means give all the error messages the ANSI standard requires. */
331 int pedantic;
333 /* Nonzero means try to make failure to fit ANSI C an error. */
335 static int pedantic_errors;
337 /* Nonzero means don't print warning messages. -w. */
339 static int inhibit_warnings = 0;
341 /* Nonzero means warn if slash-star appears in a slash-star comment,
342 or if newline-backslash appears in a slash-slash comment. */
344 static int warn_comments;
346 /* Nonzero means warn if a macro argument is (or would be)
347 stringified with -traditional. */
349 static int warn_stringify;
351 /* Nonzero means warn if there are any trigraphs. */
353 static int warn_trigraphs;
355 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
357 static int warn_undef;
359 /* Nonzero means warn if #import is used. */
361 static int warn_import = 1;
363 /* Nonzero means turn warnings into errors. */
365 static int warnings_are_errors;
367 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
369 int traditional;
371 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
373 int c89;
375 /* Nonzero causes output not to be done,
376 but directives such as #define that have side effects
377 are still obeyed. */
379 static int no_output;
381 /* Nonzero means we should look for header.gcc files that remap file names. */
382 static int remap;
384 /* Nonzero means this file was included with a -imacros or -include
385 command line and should not be recorded as an include file. */
387 static int no_record_file;
389 /* Nonzero means that we have finished processing the command line options.
390 This flag is used to decide whether or not to issue certain errors
391 and/or warnings. */
393 static int done_initializing = 0;
395 /* Line where a newline was first seen in a string constant. */
397 static int multiline_string_line = 0;
399 /* I/O buffer structure.
400 The `fname' field is nonzero for source files and #include files
401 and for the dummy text used for -D and -U.
402 It is zero for rescanning results of macro expansion
403 and for expanding macro arguments. */
404 #define INPUT_STACK_MAX 400
405 static struct file_buf {
406 char *fname;
407 /* Filename specified with #line directive. */
408 char *nominal_fname;
409 /* Include file description. */
410 struct include_file *inc;
411 /* Record where in the search path this file was found.
412 For #include_next. */
413 struct file_name_list *dir;
414 int lineno;
415 int length;
416 U_CHAR *buf;
417 U_CHAR *bufp;
418 /* Macro that this level is the expansion of.
419 Included so that we can reenable the macro
420 at the end of this level. */
421 struct hashnode *macro;
422 /* Value of if_stack at start of this file.
423 Used to prohibit unmatched #endif (etc) in an include file. */
424 struct if_stack *if_stack;
425 /* Object to be freed at end of input at this level. */
426 U_CHAR *free_ptr;
427 /* True if this is a system header file; see is_system_include. */
428 char system_header_p;
429 } instack[INPUT_STACK_MAX];
431 static int last_error_tick; /* Incremented each time we print it. */
432 static int input_file_stack_tick; /* Incremented when the status changes. */
434 /* Current nesting level of input sources.
435 `instack[indepth]' is the level currently being read. */
436 static int indepth = -1;
437 #define CHECK_DEPTH(code) \
438 if (indepth >= (INPUT_STACK_MAX - 1)) \
440 error_with_line (line_for_error (instack[indepth].lineno), \
441 "macro or `#include' recursion too deep"); \
442 code; \
445 /* Current depth in #include directives that use <...>. */
446 static int system_include_depth = 0;
448 typedef struct file_buf FILE_BUF;
450 /* The output buffer. Its LENGTH field is the amount of room allocated
451 for the buffer, not the number of chars actually present. To get
452 that, subtract outbuf.buf from outbuf.bufp. */
454 #define OUTBUF_SIZE 10 /* initial size of output buffer */
455 static FILE_BUF outbuf;
457 /* Grow output buffer OBUF points at
458 so it can hold at least NEEDED more chars. */
460 #define check_expand(OBUF, NEEDED) \
461 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
462 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
464 struct file_name_list
466 struct file_name_list *next;
467 /* If the following is 1, it is a C-language system include
468 directory. */
469 int c_system_include_path;
470 /* Mapping of file names for this directory. */
471 struct file_name_map *name_map;
472 /* Non-zero if name_map is valid. */
473 int got_name_map;
474 /* The include directory status. */
475 struct stat st;
476 /* The include prefix: "" denotes the working directory,
477 otherwise fname must end in '/'.
478 The actual size is dynamically allocated. */
479 char fname[1];
482 /* #include "file" looks in source file dir, then stack. */
483 /* #include <file> just looks in the stack. */
484 /* -I directories are added to the end, then the defaults are added. */
485 /* The */
486 static struct default_include {
487 char *fname; /* The name of the directory. */
488 char *component; /* The component containing the directory */
489 int cplusplus; /* Only look here if we're compiling C++. */
490 int cxx_aware; /* Includes in this directory don't need to
491 be wrapped in extern "C" when compiling
492 C++. */
493 } include_defaults_array[]
494 #ifdef INCLUDE_DEFAULTS
495 = INCLUDE_DEFAULTS;
496 #else
498 /* Pick up GNU C++ specific include files. */
499 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
500 { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
501 #ifdef CROSS_COMPILE
502 /* This is the dir for fixincludes. Put it just before
503 the files that we fix. */
504 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
505 /* For cross-compilation, this dir name is generated
506 automatically in Makefile.in. */
507 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
508 #ifdef TOOL_INCLUDE_DIR
509 /* This is another place that the target system's headers might be. */
510 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
511 #endif
512 #else /* not CROSS_COMPILE */
513 #ifdef LOCAL_INCLUDE_DIR
514 /* This should be /usr/local/include and should come before
515 the fixincludes-fixed header files. */
516 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
517 #endif
518 #ifdef TOOL_INCLUDE_DIR
519 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
520 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
521 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
522 #endif
523 /* This is the dir for fixincludes. Put it just before
524 the files that we fix. */
525 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
526 /* Some systems have an extra dir of include files. */
527 #ifdef SYSTEM_INCLUDE_DIR
528 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
529 #endif
530 #ifndef STANDARD_INCLUDE_COMPONENT
531 #define STANDARD_INCLUDE_COMPONENT 0
532 #endif
533 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
534 #endif /* not CROSS_COMPILE */
535 { 0, 0, 0, 0 }
537 #endif /* no INCLUDE_DEFAULTS */
539 /* The code looks at the defaults through this pointer, rather than through
540 the constant structure above. This pointer gets changed if an environment
541 variable specifies other defaults. */
542 static struct default_include *include_defaults = include_defaults_array;
544 static struct file_name_list *include = 0; /* First dir to search */
545 /* First dir to search for <file> */
546 /* This is the first element to use for #include <...>.
547 If it is 0, use the entire chain for such includes. */
548 static struct file_name_list *first_bracket_include = 0;
549 /* This is the first element in the chain that corresponds to
550 a directory of system header files. */
551 static struct file_name_list *first_system_include = 0;
552 static struct file_name_list *last_include = 0; /* Last in chain */
554 /* Chain of include directories to put at the end of the other chain. */
555 static struct file_name_list *after_include = 0;
556 static struct file_name_list *last_after_include = 0; /* Last in chain */
558 /* Chain to put at the start of the system include files. */
559 static struct file_name_list *before_system = 0;
560 static struct file_name_list *last_before_system = 0; /* Last in chain */
562 /* Directory prefix that should replace `/usr' in the standard
563 include file directories. */
564 static char *include_prefix;
566 /* Maintain and search list of included files. */
568 struct include_file {
569 struct include_file *next; /* for include_hashtab */
570 struct include_file *next_ino; /* for include_ino_hashtab */
571 char *fname;
572 /* If the following is the empty string, it means #pragma once
573 was seen in this include file, or #import was applied to the file.
574 Otherwise, if it is nonzero, it is a macro name.
575 Don't include the file again if that macro is defined. */
576 U_CHAR *control_macro;
577 /* Nonzero if the dependency on this include file has been output. */
578 int deps_output;
579 struct stat st;
582 /* Hash tables of files already included with #include or #import.
583 include_hashtab is by full name; include_ino_hashtab is by inode number. */
585 #define INCLUDE_HASHSIZE 61
586 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
587 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
589 /* Global list of strings read in from precompiled files. This list
590 is kept in the order the strings are read in, with new strings being
591 added at the end through stringlist_tailp. We use this list to output
592 the strings at the end of the run.
594 static STRINGDEF *stringlist;
595 static STRINGDEF **stringlist_tailp = &stringlist;
598 /* Structure returned by create_definition */
599 typedef struct macrodef MACRODEF;
600 struct macrodef
602 struct definition *defn;
603 U_CHAR *symnam;
604 int symlen;
607 enum sharp_token_type {
608 NO_SHARP_TOKEN = 0, /* token not present */
610 SHARP_TOKEN = '#', /* token spelled with # only */
611 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
613 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
614 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
617 /* Structure allocated for every #define. For a simple replacement
618 such as
619 #define foo bar ,
620 nargs = -1, the `pattern' list is null, and the expansion is just
621 the replacement text. Nargs = 0 means a functionlike macro with no args,
622 e.g.,
623 #define getchar() getc (stdin) .
624 When there are args, the expansion is the replacement text with the
625 args squashed out, and the reflist is a list describing how to
626 build the output from the input: e.g., "3 chars, then the 1st arg,
627 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
628 The chars here come from the expansion. Whatever is left of the
629 expansion after the last arg-occurrence is copied after that arg.
630 Note that the reflist can be arbitrarily long---
631 its length depends on the number of times the arguments appear in
632 the replacement text, not how many args there are. Example:
633 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
634 pattern list
635 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
636 where (x, y) means (nchars, argno). */
638 typedef struct definition DEFINITION;
639 struct definition {
640 int nargs;
641 int length; /* length of expansion string */
642 int predefined; /* True if the macro was builtin or */
643 /* came from the command line */
644 U_CHAR *expansion;
645 int line; /* Line number of definition */
646 char *file; /* File of definition */
647 char rest_args; /* Nonzero if last arg. absorbs the rest */
648 struct reflist {
649 struct reflist *next;
651 enum sharp_token_type stringify; /* set if a # operator before arg */
652 enum sharp_token_type raw_before; /* set if a ## operator before arg */
653 enum sharp_token_type raw_after; /* set if a ## operator after arg */
655 char rest_args; /* Nonzero if this arg. absorbs the rest */
656 int nchars; /* Number of literal chars to copy before
657 this arg occurrence. */
658 int argno; /* Number of arg to substitute (origin-0) */
659 } *pattern;
660 union {
661 /* Names of macro args, concatenated in reverse order
662 with comma-space between them.
663 The only use of this is that we warn on redefinition
664 if this differs between the old and new definitions. */
665 U_CHAR *argnames;
666 } args;
669 /* different kinds of things that can appear in the value field
670 of a hash node. Actually, this may be useless now. */
671 union hashval {
672 char *cpval;
673 DEFINITION *defn;
674 KEYDEF *keydef;
678 * special extension string that can be added to the last macro argument to
679 * allow it to absorb the "rest" of the arguments when expanded. Ex:
680 * #define wow(a, b...) process (b, a, b)
681 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
682 * { wow (one, two); } -> { process (two, one, two); }
683 * if this "rest_arg" is used with the concat token '##' and if it is not
684 * supplied then the token attached to with ## will not be outputted. Ex:
685 * #define wow (a, b...) process (b ## , a, ## b)
686 * { wow (1, 2); } -> { process (2, 1, 2); }
687 * { wow (one); } -> { process (one); {
689 static char rest_extension[] = "...";
690 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
692 /* The structure of a node in the hash table. The hash table
693 has entries for all tokens defined by #define directives (type T_MACRO),
694 plus some special tokens like __LINE__ (these each have their own
695 type, and the appropriate code is run when that type of node is seen.
696 It does not contain control words like "#define", which are recognized
697 by a separate piece of code. */
699 /* different flavors of hash nodes --- also used in keyword table */
700 enum node_type {
701 T_DEFINE = 1, /* the `#define' keyword */
702 T_INCLUDE, /* the `#include' keyword */
703 T_INCLUDE_NEXT, /* the `#include_next' keyword */
704 T_IMPORT, /* the `#import' keyword */
705 T_IFDEF, /* the `#ifdef' keyword */
706 T_IFNDEF, /* the `#ifndef' keyword */
707 T_IF, /* the `#if' keyword */
708 T_ELSE, /* `#else' */
709 T_PRAGMA, /* `#pragma' */
710 T_ELIF, /* `#elif' */
711 T_UNDEF, /* `#undef' */
712 T_LINE, /* `#line' */
713 T_ERROR, /* `#error' */
714 T_WARNING, /* `#warning' */
715 T_ENDIF, /* `#endif' */
716 T_SCCS, /* `#sccs', used on system V. */
717 T_IDENT, /* `#ident', used on system V. */
718 T_ASSERT, /* `#assert', taken from system V. */
719 T_UNASSERT, /* `#unassert', taken from system V. */
720 T_SPECLINE, /* special symbol `__LINE__' */
721 T_DATE, /* `__DATE__' */
722 T_FILE, /* `__FILE__' */
723 T_BASE_FILE, /* `__BASE_FILE__' */
724 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
725 T_VERSION, /* `__VERSION__' */
726 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
727 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
728 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
729 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
730 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
731 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
732 T_TIME, /* `__TIME__' */
733 T_CONST, /* Constant value, used by `__STDC__' */
734 T_MACRO, /* macro defined by `#define' */
735 T_DISABLED, /* macro temporarily turned off for rescan */
736 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
737 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
738 T_UNUSED /* Used for something not defined. */
741 struct hashnode {
742 struct hashnode *next; /* double links for easy deletion */
743 struct hashnode *prev;
744 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
745 chain is kept, in case the node is the head
746 of the chain and gets deleted. */
747 enum node_type type; /* type of special token */
748 int length; /* length of token, for quick comparison */
749 U_CHAR *name; /* the actual name */
750 union hashval value; /* pointer to expansion, or whatever */
753 typedef struct hashnode HASHNODE;
755 /* Some definitions for the hash table. The hash function MUST be
756 computed as shown in hashf () below. That is because the rescan
757 loop computes the hash value `on the fly' for most tokens,
758 in order to avoid the overhead of a lot of procedure calls to
759 the hashf () function. Hashf () only exists for the sake of
760 politeness, for use when speed isn't so important. */
762 #define HASHSIZE 1403
763 static HASHNODE *hashtab[HASHSIZE];
764 #define HASHSTEP(old, c) ((old << 2) + c)
765 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
767 /* Symbols to predefine. */
769 #ifdef CPP_PREDEFINES
770 static char *predefs = CPP_PREDEFINES;
771 #else
772 static char *predefs = "";
773 #endif
775 /* We let tm.h override the types used here, to handle trivial differences
776 such as the choice of unsigned int or long unsigned int for size_t.
777 When machines start needing nontrivial differences in the size type,
778 it would be best to do something here to figure out automatically
779 from other information what type to use. */
781 /* The string value for __SIZE_TYPE__. */
783 #ifndef SIZE_TYPE
784 #define SIZE_TYPE "long unsigned int"
785 #endif
787 /* The string value for __PTRDIFF_TYPE__. */
789 #ifndef PTRDIFF_TYPE
790 #define PTRDIFF_TYPE "long int"
791 #endif
793 /* The string value for __WCHAR_TYPE__. */
795 #ifndef WCHAR_TYPE
796 #define WCHAR_TYPE "int"
797 #endif
798 char * wchar_type = WCHAR_TYPE;
799 #undef WCHAR_TYPE
801 /* The string value for __USER_LABEL_PREFIX__ */
803 #ifndef USER_LABEL_PREFIX
804 #define USER_LABEL_PREFIX ""
805 #endif
807 /* The string value for __REGISTER_PREFIX__ */
809 #ifndef REGISTER_PREFIX
810 #define REGISTER_PREFIX ""
811 #endif
813 /* The string value for __IMMEDIATE_PREFIX__ */
815 #ifndef IMMEDIATE_PREFIX
816 #define IMMEDIATE_PREFIX ""
817 #endif
819 /* In the definition of a #assert name, this structure forms
820 a list of the individual values asserted.
821 Each value is itself a list of "tokens".
822 These are strings that are compared by name. */
824 struct tokenlist_list {
825 struct tokenlist_list *next;
826 struct arglist *tokens;
829 struct assertion_hashnode {
830 struct assertion_hashnode *next; /* double links for easy deletion */
831 struct assertion_hashnode *prev;
832 /* also, a back pointer to this node's hash
833 chain is kept, in case the node is the head
834 of the chain and gets deleted. */
835 struct assertion_hashnode **bucket_hdr;
836 int length; /* length of token, for quick comparison */
837 U_CHAR *name; /* the actual name */
838 /* List of token-sequences. */
839 struct tokenlist_list *value;
842 typedef struct assertion_hashnode ASSERTION_HASHNODE;
844 /* Some definitions for the hash table. The hash function MUST be
845 computed as shown in hashf below. That is because the rescan
846 loop computes the hash value `on the fly' for most tokens,
847 in order to avoid the overhead of a lot of procedure calls to
848 the hashf function. hashf only exists for the sake of
849 politeness, for use when speed isn't so important. */
851 #define ASSERTION_HASHSIZE 37
852 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
854 /* Nonzero means inhibit macroexpansion of what seem to be
855 assertion tests, in rescan. For #if. */
856 static int assertions_flag;
858 /* `struct directive' defines one #-directive, including how to handle it. */
860 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
862 struct directive {
863 int length; /* Length of name */
864 int (*func) DO_PROTO; /* Function to handle directive */
865 char *name; /* Name of directive */
866 enum node_type type; /* Code which describes which directive. */
869 #define IS_INCLUDE_DIRECTIVE_TYPE(t) (T_INCLUDE <= (t) && (t) <= T_IMPORT)
871 /* These functions are declared to return int instead of void since they
872 are going to be placed in the table and some old compilers have trouble with
873 pointers to functions returning void. */
875 static int do_assert DO_PROTO;
876 static int do_define DO_PROTO;
877 static int do_elif DO_PROTO;
878 static int do_else DO_PROTO;
879 static int do_endif DO_PROTO;
880 static int do_error DO_PROTO;
881 static int do_ident DO_PROTO;
882 static int do_if DO_PROTO;
883 static int do_include DO_PROTO;
884 static int do_line DO_PROTO;
885 static int do_pragma DO_PROTO;
886 #ifdef SCCS_DIRECTIVE
887 static int do_sccs DO_PROTO;
888 #endif
889 static int do_unassert DO_PROTO;
890 static int do_undef DO_PROTO;
891 static int do_warning DO_PROTO;
892 static int do_xifdef DO_PROTO;
894 /* Here is the actual list of #-directives, most-often-used first. */
896 static struct directive directive_table[] = {
897 { 6, do_define, "define", T_DEFINE},
898 { 2, do_if, "if", T_IF},
899 { 5, do_xifdef, "ifdef", T_IFDEF},
900 { 6, do_xifdef, "ifndef", T_IFNDEF},
901 { 5, do_endif, "endif", T_ENDIF},
902 { 4, do_else, "else", T_ELSE},
903 { 4, do_elif, "elif", T_ELIF},
904 { 4, do_line, "line", T_LINE},
905 { 7, do_include, "include", T_INCLUDE},
906 { 12, do_include, "include_next", T_INCLUDE_NEXT},
907 { 6, do_include, "import", T_IMPORT},
908 { 5, do_undef, "undef", T_UNDEF},
909 { 5, do_error, "error", T_ERROR},
910 { 7, do_warning, "warning", T_WARNING},
911 #ifdef SCCS_DIRECTIVE
912 { 4, do_sccs, "sccs", T_SCCS},
913 #endif
914 { 6, do_pragma, "pragma", T_PRAGMA},
915 { 5, do_ident, "ident", T_IDENT},
916 { 6, do_assert, "assert", T_ASSERT},
917 { 8, do_unassert, "unassert", T_UNASSERT},
918 { -1, 0, "", T_UNUSED},
921 /* When a directive handler is called,
922 this points to the # (or the : of the %:) that started the directive. */
923 U_CHAR *directive_start;
925 /* table to tell if char can be part of a C identifier. */
926 U_CHAR is_idchar[256];
927 /* table to tell if char can be first char of a c identifier. */
928 U_CHAR is_idstart[256];
929 /* table to tell if c is horizontal space. */
930 static U_CHAR is_hor_space[256];
931 /* table to tell if c is horizontal or vertical space. */
932 U_CHAR is_space[256];
933 /* names of some characters */
934 static char *char_name[256];
936 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
937 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
939 static int errors = 0; /* Error counter for exit code */
941 /* Name of output file, for error messages. */
942 static char *out_fname;
945 /* Stack of conditionals currently in progress
946 (including both successful and failing conditionals). */
948 struct if_stack {
949 struct if_stack *next; /* for chaining to the next stack frame */
950 char *fname; /* copied from input when frame is made */
951 int lineno; /* similarly */
952 int if_succeeded; /* true if a leg of this if-group
953 has been passed through rescan */
954 U_CHAR *control_macro; /* For #ifndef at start of file,
955 this is the macro name tested. */
956 enum node_type type; /* type of last directive seen in this group */
958 typedef struct if_stack IF_STACK_FRAME;
959 static IF_STACK_FRAME *if_stack = NULL;
961 /* Buffer of -M output. */
962 static char *deps_buffer;
964 /* Number of bytes allocated in above. */
965 static int deps_allocated_size;
967 /* Number of bytes used. */
968 static int deps_size;
970 /* Number of bytes since the last newline. */
971 static int deps_column;
973 /* Nonzero means -I- has been seen,
974 so don't look for #include "foo" the source-file directory. */
975 static int ignore_srcdir;
977 static int safe_read PROTO((int, char *, int));
978 static void safe_write PROTO((int, char *, int));
980 int main PROTO((int, char **));
982 static void path_include PROTO((char *));
984 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
986 static void trigraph_pcp PROTO((FILE_BUF *));
988 static void newline_fix PROTO((U_CHAR *));
989 static void name_newline_fix PROTO((U_CHAR *));
991 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
993 static void rescan PROTO((FILE_BUF *, int));
995 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
997 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
999 static struct tm *timestamp PROTO((void));
1000 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1002 static int is_system_include PROTO((char *));
1003 static char *base_name PROTO((char *));
1004 static int absolute_filename PROTO((char *));
1005 static size_t simplify_filename PROTO((char *));
1007 static char *read_filename_string PROTO((int, FILE *));
1008 static struct file_name_map *read_name_map PROTO((char *));
1009 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
1010 static char *remap_include_file PROTO((char *, struct file_name_list *));
1011 static int lookup_ino_include PROTO((struct include_file *));
1013 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
1014 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
1016 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
1017 static int check_preconditions PROTO((char *));
1018 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1019 static void pcstring_used PROTO((HASHNODE *));
1020 static void write_output PROTO((void));
1021 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1023 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1025 static int check_macro_name PROTO((U_CHAR *, char *));
1026 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1027 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1029 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1031 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1032 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1034 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1035 static void free_token_list PROTO((struct arglist *));
1037 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1038 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1039 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1041 static void do_once PROTO((void));
1043 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1044 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1045 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1046 static void validate_else PROTO((U_CHAR *, U_CHAR *));
1048 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1049 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1050 static char *quote_string PROTO((char *, char *));
1051 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1053 /* Last arg to output_line_directive. */
1054 enum file_change_code {same_file, enter_file, leave_file};
1055 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1057 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1059 struct argdata;
1060 static char *macarg PROTO((struct argdata *, int));
1062 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1064 static int discard_comments PROTO((U_CHAR *, int, int));
1066 static int change_newlines PROTO((U_CHAR *, int));
1068 char *my_strerror PROTO((int));
1069 void error PRINTF_PROTO_1((char *, ...));
1070 static void verror PROTO((char *, va_list));
1071 static void error_from_errno PROTO((char *));
1072 void warning PRINTF_PROTO_1((char *, ...));
1073 static void vwarning PROTO((char *, va_list));
1074 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1075 static void verror_with_line PROTO((int, char *, va_list));
1076 static void vwarning_with_line PROTO((int, char *, va_list));
1077 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1078 void pedwarn PRINTF_PROTO_1((char *, ...));
1079 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1080 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1082 static void print_containing_files PROTO((void));
1084 static int line_for_error PROTO((int));
1085 static int grow_outbuf PROTO((FILE_BUF *, int));
1087 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1088 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1089 static void delete_macro PROTO((HASHNODE *));
1090 static int hashf PROTO((U_CHAR *, int, int));
1092 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1093 static void dump_all_macros PROTO((void));
1094 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1095 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1097 static void initialize_char_syntax PROTO((void));
1098 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1100 static void make_definition PROTO((char *, FILE_BUF *));
1101 static void make_undef PROTO((char *, FILE_BUF *));
1103 static void make_assertion PROTO((char *, char *));
1105 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1106 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1108 static int quote_string_for_make PROTO((char *, char *));
1109 static void deps_output PROTO((char *, int));
1111 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1112 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1113 static void perror_with_name PROTO((char *));
1114 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1115 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1117 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1118 GENERIC_PTR xmalloc PROTO((size_t));
1119 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1120 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1121 static char *savestring PROTO((char *));
1123 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1124 retrying if necessary. If MAX_READ_LEN is defined, read at most
1125 that bytes at a time. Return a negative value if an error occurs,
1126 otherwise return the actual number of bytes read,
1127 which must be LEN unless end-of-file was reached. */
1129 static int
1130 safe_read (desc, ptr, len)
1131 int desc;
1132 char *ptr;
1133 int len;
1135 int left, rcount, nchars;
1137 left = len;
1138 while (left > 0) {
1139 rcount = left;
1140 #ifdef MAX_READ_LEN
1141 if (rcount > MAX_READ_LEN)
1142 rcount = MAX_READ_LEN;
1143 #endif
1144 nchars = read (desc, ptr, rcount);
1145 if (nchars < 0)
1147 #ifdef EINTR
1148 if (errno == EINTR)
1149 continue;
1150 #endif
1151 return nchars;
1153 if (nchars == 0)
1154 break;
1155 ptr += nchars;
1156 left -= nchars;
1158 return len - left;
1161 /* Write LEN bytes at PTR to descriptor DESC,
1162 retrying if necessary, and treating any real error as fatal.
1163 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1165 static void
1166 safe_write (desc, ptr, len)
1167 int desc;
1168 char *ptr;
1169 int len;
1171 int wcount, written;
1173 while (len > 0) {
1174 wcount = len;
1175 #ifdef MAX_WRITE_LEN
1176 if (wcount > MAX_WRITE_LEN)
1177 wcount = MAX_WRITE_LEN;
1178 #endif
1179 written = write (desc, ptr, wcount);
1180 if (written < 0)
1182 #ifdef EINTR
1183 if (errno == EINTR)
1184 continue;
1185 #endif
1186 pfatal_with_name (out_fname);
1188 ptr += written;
1189 len -= written;
1194 main (argc, argv)
1195 int argc;
1196 char **argv;
1198 struct stat st;
1199 char *in_fname;
1200 char *cp;
1201 int f, i;
1202 FILE_BUF *fp;
1203 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1204 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1205 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1206 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1207 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1209 /* Record the option used with each element of pend_assertions.
1210 This is preparation for supporting more than one option for making
1211 an assertion. */
1212 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1213 int inhibit_predefs = 0;
1214 int no_standard_includes = 0;
1215 int no_standard_cplusplus_includes = 0;
1216 int missing_newline = 0;
1218 /* Non-0 means don't output the preprocessed program. */
1219 int inhibit_output = 0;
1220 /* Non-0 means -v, so print the full set of include dirs. */
1221 int verbose = 0;
1223 /* File name which deps are being written to.
1224 This is 0 if deps are being written to stdout. */
1225 char *deps_file = 0;
1226 /* Fopen file mode to open deps_file with. */
1227 char *deps_mode = "a";
1228 /* Stream on which to print the dependency information. */
1229 FILE *deps_stream = 0;
1230 /* Target-name to write with the dependency information. */
1231 char *deps_target = 0;
1233 #ifdef RLIMIT_STACK
1234 /* Get rid of any avoidable limit on stack size. */
1236 struct rlimit rlim;
1238 /* Set the stack limit huge so that alloca (particularly stringtab
1239 in dbxread.c) does not fail. */
1240 getrlimit (RLIMIT_STACK, &rlim);
1241 rlim.rlim_cur = rlim.rlim_max;
1242 setrlimit (RLIMIT_STACK, &rlim);
1244 #endif /* RLIMIT_STACK defined */
1246 #ifdef SIGPIPE
1247 signal (SIGPIPE, pipe_closed);
1248 #endif
1250 progname = base_name (argv[0]);
1252 #ifdef VMS
1254 /* Remove extension from PROGNAME. */
1255 char *p;
1256 char *s = progname = savestring (progname);
1258 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1259 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1260 && (p[1] == 'e' || p[1] == 'E')
1261 && (p[2] == 'x' || p[2] == 'X')
1262 && (p[3] == 'e' || p[3] == 'E')
1263 && !p[4])
1264 *p = '\0';
1266 #endif
1268 in_fname = NULL;
1269 out_fname = NULL;
1271 /* Initialize is_idchar. */
1272 initialize_char_syntax ();
1274 no_line_directives = 0;
1275 no_trigraphs = 1;
1276 dump_macros = dump_none;
1277 no_output = 0;
1278 cplusplus = 0;
1279 cplusplus_comments = 1;
1281 bzero ((char *) pend_files, argc * sizeof (char *));
1282 bzero ((char *) pend_defs, argc * sizeof (char *));
1283 bzero ((char *) pend_undefs, argc * sizeof (char *));
1284 bzero ((char *) pend_assertions, argc * sizeof (char *));
1285 bzero ((char *) pend_includes, argc * sizeof (char *));
1287 /* Process switches and find input file name. */
1289 for (i = 1; i < argc; i++) {
1290 if (argv[i][0] != '-') {
1291 if (out_fname != NULL)
1292 fatal ("Usage: %s [switches] input output", argv[0]);
1293 else if (in_fname != NULL)
1294 out_fname = argv[i];
1295 else
1296 in_fname = argv[i];
1297 } else {
1298 switch (argv[i][1]) {
1300 case 'i':
1301 if (!strcmp (argv[i], "-include")) {
1302 if (i + 1 == argc)
1303 fatal ("Filename missing after `-include' option");
1304 else
1305 simplify_filename (pend_includes[i] = argv[++i]);
1307 if (!strcmp (argv[i], "-imacros")) {
1308 if (i + 1 == argc)
1309 fatal ("Filename missing after `-imacros' option");
1310 else
1311 simplify_filename (pend_files[i] = argv[++i]);
1313 if (!strcmp (argv[i], "-iprefix")) {
1314 if (i + 1 == argc)
1315 fatal ("Filename missing after `-iprefix' option");
1316 else
1317 include_prefix = argv[++i];
1319 if (!strcmp (argv[i], "-ifoutput")) {
1320 output_conditionals = 1;
1322 if (!strcmp (argv[i], "-isystem")) {
1323 struct file_name_list *dirtmp;
1325 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1326 "", argv[++i])))
1327 break;
1328 dirtmp->c_system_include_path = 1;
1330 if (before_system == 0)
1331 before_system = dirtmp;
1332 else
1333 last_before_system->next = dirtmp;
1334 last_before_system = dirtmp; /* Tail follows the last one */
1336 /* Add directory to end of path for includes,
1337 with the default prefix at the front of its name. */
1338 if (!strcmp (argv[i], "-iwithprefix")) {
1339 struct file_name_list *dirtmp;
1340 char *prefix;
1342 if (include_prefix != 0)
1343 prefix = include_prefix;
1344 else {
1345 prefix = savestring (GCC_INCLUDE_DIR);
1346 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1347 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1348 prefix[strlen (prefix) - 7] = 0;
1351 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1352 prefix, argv[++i])))
1353 break;
1355 if (after_include == 0)
1356 after_include = dirtmp;
1357 else
1358 last_after_include->next = dirtmp;
1359 last_after_include = dirtmp; /* Tail follows the last one */
1361 /* Add directory to main path for includes,
1362 with the default prefix at the front of its name. */
1363 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1364 struct file_name_list *dirtmp;
1365 char *prefix;
1367 if (include_prefix != 0)
1368 prefix = include_prefix;
1369 else {
1370 prefix = savestring (GCC_INCLUDE_DIR);
1371 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1372 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1373 prefix[strlen (prefix) - 7] = 0;
1376 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1377 append_include_chain (dirtmp, dirtmp);
1379 /* Add directory to end of path for includes. */
1380 if (!strcmp (argv[i], "-idirafter")) {
1381 struct file_name_list *dirtmp;
1383 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1384 "", argv[++i])))
1385 break;
1387 if (after_include == 0)
1388 after_include = dirtmp;
1389 else
1390 last_after_include->next = dirtmp;
1391 last_after_include = dirtmp; /* Tail follows the last one */
1393 break;
1395 case 'o':
1396 if (out_fname != NULL)
1397 fatal ("Output filename specified twice");
1398 if (i + 1 == argc)
1399 fatal ("Filename missing after -o option");
1400 out_fname = argv[++i];
1401 if (!strcmp (out_fname, "-"))
1402 out_fname = "";
1403 break;
1405 case 'p':
1406 if (!strcmp (argv[i], "-pedantic"))
1407 pedantic = 1;
1408 else if (!strcmp (argv[i], "-pedantic-errors")) {
1409 pedantic = 1;
1410 pedantic_errors = 1;
1411 } else if (!strcmp (argv[i], "-pcp")) {
1412 char *pcp_fname;
1413 if (i + 1 == argc)
1414 fatal ("Filename missing after -pcp option");
1415 pcp_fname = argv[++i];
1416 pcp_outfile
1417 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1418 ? fopen (pcp_fname, "w")
1419 : stdout);
1420 if (pcp_outfile == 0)
1421 pfatal_with_name (pcp_fname);
1422 no_precomp = 1;
1424 break;
1426 case 't':
1427 if (!strcmp (argv[i], "-traditional")) {
1428 traditional = 1;
1429 cplusplus_comments = 0;
1430 } else if (!strcmp (argv[i], "-trigraphs")) {
1431 no_trigraphs = 0;
1433 break;
1435 case 'l':
1436 if (! strcmp (argv[i], "-lang-c"))
1437 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1438 if (! strcmp (argv[i], "-lang-c89"))
1439 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1440 if (! strcmp (argv[i], "-lang-c++"))
1441 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1442 if (! strcmp (argv[i], "-lang-objc"))
1443 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1444 if (! strcmp (argv[i], "-lang-objc++"))
1445 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1446 if (! strcmp (argv[i], "-lang-asm"))
1447 lang_asm = 1;
1448 if (! strcmp (argv[i], "-lint"))
1449 for_lint = 1;
1450 break;
1452 case '+':
1453 cplusplus = 1, cplusplus_comments = 1;
1454 break;
1456 case 'w':
1457 inhibit_warnings = 1;
1458 break;
1460 case 'W':
1461 if (!strcmp (argv[i], "-Wtrigraphs"))
1462 warn_trigraphs = 1;
1463 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1464 warn_trigraphs = 0;
1465 else if (!strcmp (argv[i], "-Wcomment"))
1466 warn_comments = 1;
1467 else if (!strcmp (argv[i], "-Wno-comment"))
1468 warn_comments = 0;
1469 else if (!strcmp (argv[i], "-Wcomments"))
1470 warn_comments = 1;
1471 else if (!strcmp (argv[i], "-Wno-comments"))
1472 warn_comments = 0;
1473 else if (!strcmp (argv[i], "-Wtraditional"))
1474 warn_stringify = 1;
1475 else if (!strcmp (argv[i], "-Wno-traditional"))
1476 warn_stringify = 0;
1477 else if (!strcmp (argv[i], "-Wundef"))
1478 warn_undef = 1;
1479 else if (!strcmp (argv[i], "-Wno-undef"))
1480 warn_undef = 0;
1481 else if (!strcmp (argv[i], "-Wimport"))
1482 warn_import = 1;
1483 else if (!strcmp (argv[i], "-Wno-import"))
1484 warn_import = 0;
1485 else if (!strcmp (argv[i], "-Werror"))
1486 warnings_are_errors = 1;
1487 else if (!strcmp (argv[i], "-Wno-error"))
1488 warnings_are_errors = 0;
1489 else if (!strcmp (argv[i], "-Wall"))
1491 warn_trigraphs = 1;
1492 warn_comments = 1;
1494 break;
1496 case 'M':
1497 /* The style of the choices here is a bit mixed.
1498 The chosen scheme is a hybrid of keeping all options in one string
1499 and specifying each option in a separate argument:
1500 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1501 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1502 -M[M][G][D file]. This is awkward to handle in specs, and is not
1503 as extensible. */
1504 /* ??? -MG must be specified in addition to one of -M or -MM.
1505 This can be relaxed in the future without breaking anything.
1506 The converse isn't true. */
1508 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1509 if (!strcmp (argv[i], "-MG"))
1511 print_deps_missing_files = 1;
1512 break;
1514 if (!strcmp (argv[i], "-M"))
1515 print_deps = 2;
1516 else if (!strcmp (argv[i], "-MM"))
1517 print_deps = 1;
1518 else if (!strcmp (argv[i], "-MD"))
1519 print_deps = 2;
1520 else if (!strcmp (argv[i], "-MMD"))
1521 print_deps = 1;
1522 /* For -MD and -MMD options, write deps on file named by next arg. */
1523 if (!strcmp (argv[i], "-MD")
1524 || !strcmp (argv[i], "-MMD")) {
1525 if (i + 1 == argc)
1526 fatal ("Filename missing after %s option", argv[i]);
1527 i++;
1528 deps_file = argv[i];
1529 deps_mode = "w";
1530 } else {
1531 /* For -M and -MM, write deps on standard output
1532 and suppress the usual output. */
1533 deps_stream = stdout;
1534 inhibit_output = 1;
1536 break;
1538 case 'd':
1540 char *p = argv[i] + 2;
1541 char c;
1542 while ((c = *p++)) {
1543 /* Arg to -d specifies what parts of macros to dump */
1544 switch (c) {
1545 case 'M':
1546 dump_macros = dump_only;
1547 no_output = 1;
1548 break;
1549 case 'N':
1550 dump_macros = dump_names;
1551 break;
1552 case 'D':
1553 dump_macros = dump_definitions;
1554 break;
1555 case 'I':
1556 dump_includes = 1;
1557 break;
1561 break;
1563 case 'g':
1564 if (argv[i][2] == '3')
1565 debug_output = 1;
1566 break;
1568 case 'v':
1569 fprintf (stderr, "GNU CPP version %s", version_string);
1570 #ifdef TARGET_VERSION
1571 TARGET_VERSION;
1572 #endif
1573 fprintf (stderr, "\n");
1574 verbose = 1;
1575 break;
1577 case 'H':
1578 print_include_names = 1;
1579 break;
1581 case 'D':
1582 if (argv[i][2] != 0)
1583 pend_defs[i] = argv[i] + 2;
1584 else if (i + 1 == argc)
1585 fatal ("Macro name missing after -D option");
1586 else
1587 i++, pend_defs[i] = argv[i];
1588 break;
1590 case 'A':
1592 char *p;
1594 if (argv[i][2] != 0)
1595 p = argv[i] + 2;
1596 else if (i + 1 == argc)
1597 fatal ("Assertion missing after -A option");
1598 else
1599 p = argv[++i];
1601 if (!strcmp (p, "-")) {
1602 /* -A- eliminates all predefined macros and assertions.
1603 Let's include also any that were specified earlier
1604 on the command line. That way we can get rid of any
1605 that were passed automatically in from GCC. */
1606 int j;
1607 inhibit_predefs = 1;
1608 for (j = 0; j < i; j++)
1609 pend_defs[j] = pend_assertions[j] = 0;
1610 } else {
1611 pend_assertions[i] = p;
1612 pend_assertion_options[i] = "-A";
1615 break;
1617 case 'U': /* JF #undef something */
1618 if (argv[i][2] != 0)
1619 pend_undefs[i] = argv[i] + 2;
1620 else if (i + 1 == argc)
1621 fatal ("Macro name missing after -U option");
1622 else
1623 pend_undefs[i] = argv[i+1], i++;
1624 break;
1626 case 'C':
1627 put_out_comments = 1;
1628 break;
1630 case 'E': /* -E comes from cc -E; ignore it. */
1631 break;
1633 case 'P':
1634 no_line_directives = 1;
1635 break;
1637 case '$': /* Don't include $ in identifiers. */
1638 is_idchar['$'] = is_idstart['$'] = 0;
1639 break;
1641 case 'I': /* Add directory to path for includes. */
1643 struct file_name_list *dirtmp;
1645 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1646 ignore_srcdir = 1;
1647 /* Don't use any preceding -I directories for #include <...>. */
1648 first_bracket_include = 0;
1650 else {
1651 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1652 argv[i][2] ? argv[i] + 2 : argv[++i]);
1653 append_include_chain (dirtmp, dirtmp);
1656 break;
1658 case 'n':
1659 if (!strcmp (argv[i], "-nostdinc"))
1660 /* -nostdinc causes no default include directories.
1661 You must specify all include-file directories with -I. */
1662 no_standard_includes = 1;
1663 else if (!strcmp (argv[i], "-nostdinc++"))
1664 /* -nostdinc++ causes no default C++-specific include directories. */
1665 no_standard_cplusplus_includes = 1;
1666 else if (!strcmp (argv[i], "-noprecomp"))
1667 no_precomp = 1;
1668 break;
1670 case 'r':
1671 if (!strcmp (argv[i], "-remap"))
1672 remap = 1;
1673 break;
1675 case 'u':
1676 /* Sun compiler passes undocumented switch "-undef".
1677 Let's assume it means to inhibit the predefined symbols. */
1678 inhibit_predefs = 1;
1679 break;
1681 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1682 if (in_fname == NULL) {
1683 in_fname = "";
1684 break;
1685 } else if (out_fname == NULL) {
1686 out_fname = "";
1687 break;
1688 } /* else fall through into error */
1690 default:
1691 fatal ("Invalid option `%s'", argv[i]);
1696 /* Add dirs from CPATH after dirs from -I. */
1697 /* There seems to be confusion about what CPATH should do,
1698 so for the moment it is not documented. */
1699 /* Some people say that CPATH should replace the standard include dirs,
1700 but that seems pointless: it comes before them, so it overrides them
1701 anyway. */
1702 cp = getenv ("CPATH");
1703 if (cp && ! no_standard_includes)
1704 path_include (cp);
1706 /* Initialize output buffer */
1708 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1709 outbuf.bufp = outbuf.buf;
1710 outbuf.length = OUTBUF_SIZE;
1712 /* Do partial setup of input buffer for the sake of generating
1713 early #line directives (when -g is in effect). */
1715 fp = &instack[++indepth];
1716 if (in_fname == NULL)
1717 in_fname = "";
1718 fp->nominal_fname = fp->fname = in_fname;
1719 fp->lineno = 0;
1721 /* In C++, wchar_t is a distinct basic type, and we can expect
1722 __wchar_t to be defined by cc1plus. */
1723 if (cplusplus)
1724 wchar_type = "__wchar_t";
1726 /* Install __LINE__, etc. Must follow initialize_char_syntax
1727 and option processing. */
1728 initialize_builtins (fp, &outbuf);
1730 /* Do standard #defines and assertions
1731 that identify system and machine type. */
1733 if (!inhibit_predefs) {
1734 char *p = (char *) alloca (strlen (predefs) + 1);
1735 strcpy (p, predefs);
1736 while (*p) {
1737 char *q;
1738 while (*p == ' ' || *p == '\t')
1739 p++;
1740 /* Handle -D options. */
1741 if (p[0] == '-' && p[1] == 'D') {
1742 q = &p[2];
1743 while (*p && *p != ' ' && *p != '\t')
1744 p++;
1745 if (*p != 0)
1746 *p++= 0;
1747 if (debug_output)
1748 output_line_directive (fp, &outbuf, 0, same_file);
1749 make_definition (q, &outbuf);
1750 while (*p == ' ' || *p == '\t')
1751 p++;
1752 } else if (p[0] == '-' && p[1] == 'A') {
1753 /* Handle -A options (assertions). */
1754 char *assertion;
1755 char *past_name;
1756 char *value;
1757 char *past_value;
1758 char *termination;
1759 int save_char;
1761 assertion = &p[2];
1762 past_name = assertion;
1763 /* Locate end of name. */
1764 while (*past_name && *past_name != ' '
1765 && *past_name != '\t' && *past_name != '(')
1766 past_name++;
1767 /* Locate `(' at start of value. */
1768 value = past_name;
1769 while (*value && (*value == ' ' || *value == '\t'))
1770 value++;
1771 if (*value++ != '(')
1772 abort ();
1773 while (*value && (*value == ' ' || *value == '\t'))
1774 value++;
1775 past_value = value;
1776 /* Locate end of value. */
1777 while (*past_value && *past_value != ' '
1778 && *past_value != '\t' && *past_value != ')')
1779 past_value++;
1780 termination = past_value;
1781 while (*termination && (*termination == ' ' || *termination == '\t'))
1782 termination++;
1783 if (*termination++ != ')')
1784 abort ();
1785 if (*termination && *termination != ' ' && *termination != '\t')
1786 abort ();
1787 /* Temporarily null-terminate the value. */
1788 save_char = *termination;
1789 *termination = '\0';
1790 /* Install the assertion. */
1791 make_assertion ("-A", assertion);
1792 *termination = (char) save_char;
1793 p = termination;
1794 while (*p == ' ' || *p == '\t')
1795 p++;
1796 } else {
1797 abort ();
1802 /* Now handle the command line options. */
1804 /* Do -U's, -D's and -A's in the order they were seen. */
1805 for (i = 1; i < argc; i++) {
1806 if (pend_undefs[i]) {
1807 if (debug_output)
1808 output_line_directive (fp, &outbuf, 0, same_file);
1809 make_undef (pend_undefs[i], &outbuf);
1811 if (pend_defs[i]) {
1812 if (debug_output)
1813 output_line_directive (fp, &outbuf, 0, same_file);
1814 make_definition (pend_defs[i], &outbuf);
1816 if (pend_assertions[i])
1817 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1820 done_initializing = 1;
1822 { /* Read the appropriate environment variable and if it exists
1823 replace include_defaults with the listed path. */
1824 char *epath = 0;
1825 switch ((objc << 1) + cplusplus)
1827 case 0:
1828 epath = getenv ("C_INCLUDE_PATH");
1829 break;
1830 case 1:
1831 epath = getenv ("CPLUS_INCLUDE_PATH");
1832 break;
1833 case 2:
1834 epath = getenv ("OBJC_INCLUDE_PATH");
1835 break;
1836 case 3:
1837 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1838 break;
1840 /* If the environment var for this language is set,
1841 add to the default list of include directories. */
1842 if (epath) {
1843 int num_dirs;
1844 char *startp, *endp;
1846 for (num_dirs = 1, startp = epath; *startp; startp++)
1847 if (*startp == PATH_SEPARATOR)
1848 num_dirs++;
1849 include_defaults
1850 = (struct default_include *) xmalloc ((num_dirs
1851 * sizeof (struct default_include))
1852 + sizeof (include_defaults_array));
1853 startp = endp = epath;
1854 num_dirs = 0;
1855 while (1) {
1856 char c = *endp++;
1857 if (c == PATH_SEPARATOR || !c) {
1858 endp[-1] = 0;
1859 include_defaults[num_dirs].fname
1860 = startp == endp ? "." : savestring (startp);
1861 endp[-1] = c;
1862 include_defaults[num_dirs].component = 0;
1863 include_defaults[num_dirs].cplusplus = cplusplus;
1864 include_defaults[num_dirs].cxx_aware = 1;
1865 num_dirs++;
1866 if (!c)
1867 break;
1868 startp = endp;
1871 /* Put the usual defaults back in at the end. */
1872 bcopy ((char *) include_defaults_array,
1873 (char *) &include_defaults[num_dirs],
1874 sizeof (include_defaults_array));
1878 append_include_chain (before_system, last_before_system);
1879 first_system_include = before_system;
1881 /* Unless -fnostdinc,
1882 tack on the standard include file dirs to the specified list */
1883 if (!no_standard_includes) {
1884 struct default_include *p = include_defaults;
1885 char *specd_prefix = include_prefix;
1886 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1887 int default_len = 0;
1888 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1889 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1890 default_len = strlen (default_prefix) - 7;
1891 default_prefix[default_len] = 0;
1893 /* Search "translated" versions of GNU directories.
1894 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1895 if (specd_prefix != 0 && default_len != 0)
1896 for (p = include_defaults; p->fname; p++) {
1897 /* Some standard dirs are only for C++. */
1898 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1899 /* Does this dir start with the prefix? */
1900 if (!strncmp (p->fname, default_prefix, default_len)) {
1901 /* Yes; change prefix and add to search list. */
1902 struct file_name_list *new
1903 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1904 p->fname + default_len);
1905 if (new) {
1906 new->c_system_include_path = !p->cxx_aware;
1907 append_include_chain (new, new);
1908 if (first_system_include == 0)
1909 first_system_include = new;
1914 /* Search ordinary names for GNU include directories. */
1915 for (p = include_defaults; p->fname; p++) {
1916 /* Some standard dirs are only for C++. */
1917 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1918 struct file_name_list *new
1919 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1920 if (new) {
1921 new->c_system_include_path = !p->cxx_aware;
1922 append_include_chain (new, new);
1923 if (first_system_include == 0)
1924 first_system_include = new;
1930 /* Tack the after_include chain at the end of the include chain. */
1931 append_include_chain (after_include, last_after_include);
1932 if (first_system_include == 0)
1933 first_system_include = after_include;
1935 /* With -v, print the list of dirs to search. */
1936 if (verbose) {
1937 struct file_name_list *p;
1938 fprintf (stderr, "#include \"...\" search starts here:\n");
1939 for (p = include; p; p = p->next) {
1940 if (p == first_bracket_include)
1941 fprintf (stderr, "#include <...> search starts here:\n");
1942 if (!p->fname[0])
1943 fprintf (stderr, " .\n");
1944 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1945 fprintf (stderr, " %s\n", p->fname);
1946 else
1947 /* Omit trailing '/'. */
1948 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1950 fprintf (stderr, "End of search list.\n");
1953 /* -MG doesn't select the form of output and must be specified with one of
1954 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1955 inhibit compilation. */
1956 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1957 fatal ("-MG must be specified with one of -M or -MM");
1959 /* Either of two environment variables can specify output of deps.
1960 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1961 where OUTPUT_FILE is the file to write deps info to
1962 and DEPS_TARGET is the target to mention in the deps. */
1964 if (print_deps == 0
1965 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1966 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1967 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1968 char *s;
1969 char *output_file;
1971 if (spec == 0) {
1972 spec = getenv ("SUNPRO_DEPENDENCIES");
1973 print_deps = 2;
1975 else
1976 print_deps = 1;
1978 s = spec;
1979 /* Find the space before the DEPS_TARGET, if there is one. */
1980 /* This should use index. (mrs) */
1981 while (*s != 0 && *s != ' ') s++;
1982 if (*s != 0) {
1983 deps_target = s + 1;
1984 output_file = xmalloc (s - spec + 1);
1985 bcopy (spec, output_file, s - spec);
1986 output_file[s - spec] = 0;
1988 else {
1989 deps_target = 0;
1990 output_file = spec;
1993 deps_file = output_file;
1994 deps_mode = "a";
1997 /* For -M, print the expected object file name
1998 as the target of this Make-rule. */
1999 if (print_deps) {
2000 deps_allocated_size = 200;
2001 deps_buffer = xmalloc (deps_allocated_size);
2002 deps_buffer[0] = 0;
2003 deps_size = 0;
2004 deps_column = 0;
2006 if (deps_target) {
2007 deps_output (deps_target, ':');
2008 } else if (*in_fname == 0) {
2009 deps_output ("-", ':');
2010 } else {
2011 char *p, *q;
2012 int len;
2014 q = base_name (in_fname);
2016 /* Copy remainder to mungable area. */
2017 p = (char *) alloca (strlen(q) + 8);
2018 strcpy (p, q);
2020 /* Output P, but remove known suffixes. */
2021 len = strlen (p);
2022 q = p + len;
2023 if (len >= 2
2024 && p[len - 2] == '.'
2025 && index("cCsSm", p[len - 1]))
2026 q = p + (len - 2);
2027 else if (len >= 3
2028 && p[len - 3] == '.'
2029 && p[len - 2] == 'c'
2030 && p[len - 1] == 'c')
2031 q = p + (len - 3);
2032 else if (len >= 4
2033 && p[len - 4] == '.'
2034 && p[len - 3] == 'c'
2035 && p[len - 2] == 'x'
2036 && p[len - 1] == 'x')
2037 q = p + (len - 4);
2038 else if (len >= 4
2039 && p[len - 4] == '.'
2040 && p[len - 3] == 'c'
2041 && p[len - 2] == 'p'
2042 && p[len - 1] == 'p')
2043 q = p + (len - 4);
2045 /* Supply our own suffix. */
2046 strcpy (q, OBJECT_SUFFIX);
2048 deps_output (p, ':');
2049 deps_output (in_fname, ' ');
2053 /* Scan the -imacros files before the main input.
2054 Much like #including them, but with no_output set
2055 so that only their macro definitions matter. */
2057 no_output++; no_record_file++;
2058 for (i = 1; i < argc; i++)
2059 if (pend_files[i]) {
2060 struct include_file *inc;
2061 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2062 if (fd < 0) {
2063 perror_with_name (pend_files[i]);
2064 return FATAL_EXIT_CODE;
2066 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2068 no_output--; no_record_file--;
2070 /* Copy the entire contents of the main input file into
2071 the stacked input buffer previously allocated for it. */
2073 /* JF check for stdin */
2074 if (in_fname == NULL || *in_fname == 0) {
2075 in_fname = "";
2076 f = 0;
2077 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2078 goto perror;
2080 if (fstat (f, &st) != 0)
2081 pfatal_with_name (in_fname);
2082 fp->nominal_fname = fp->fname = in_fname;
2083 fp->lineno = 1;
2084 fp->system_header_p = 0;
2085 /* JF all this is mine about reading pipes and ttys */
2086 if (! S_ISREG (st.st_mode)) {
2087 /* Read input from a file that is not a normal disk file.
2088 We cannot preallocate a buffer with the correct size,
2089 so we must read in the file a piece at the time and make it bigger. */
2090 int size;
2091 int bsize;
2092 int cnt;
2094 if (S_ISDIR (st.st_mode))
2095 fatal ("Input file `%s' is a directory", in_fname);
2097 bsize = 2000;
2098 size = 0;
2099 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2100 for (;;) {
2101 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2102 if (cnt < 0) goto perror; /* error! */
2103 size += cnt;
2104 if (size != bsize) break; /* End of file */
2105 bsize *= 2;
2106 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2108 fp->length = size;
2109 } else {
2110 /* Read a file whose size we can determine in advance.
2111 For the sake of VMS, st.st_size is just an upper bound. */
2112 size_t s = (size_t) st.st_size;
2113 if (s != st.st_size || s + 2 < s)
2114 memory_full ();
2115 fp->buf = (U_CHAR *) xmalloc (s + 2);
2116 fp->length = safe_read (f, (char *) fp->buf, s);
2117 if (fp->length < 0) goto perror;
2119 fp->bufp = fp->buf;
2120 fp->if_stack = if_stack;
2122 /* Make sure data ends with a newline. And put a null after it. */
2124 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2125 /* Backslash-newline at end is not good enough. */
2126 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2127 fp->buf[fp->length++] = '\n';
2128 missing_newline = 1;
2130 fp->buf[fp->length] = '\0';
2132 /* Unless inhibited, convert trigraphs in the input. */
2134 if (!no_trigraphs)
2135 trigraph_pcp (fp);
2137 /* Now that we know the input file is valid, open the output. */
2139 if (!out_fname || !strcmp (out_fname, ""))
2140 out_fname = "stdout";
2141 else if (! freopen (out_fname, "w", stdout))
2142 pfatal_with_name (out_fname);
2144 output_line_directive (fp, &outbuf, 0, same_file);
2146 /* Scan the -include files before the main input. */
2148 no_record_file++;
2149 for (i = 1; i < argc; i++)
2150 if (pend_includes[i]) {
2151 struct include_file *inc;
2152 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2153 if (fd < 0) {
2154 perror_with_name (pend_includes[i]);
2155 return FATAL_EXIT_CODE;
2157 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2159 no_record_file--;
2161 /* Scan the input, processing macros and directives. */
2163 rescan (&outbuf, 0);
2165 if (missing_newline)
2166 fp->lineno--;
2168 if (pedantic && missing_newline)
2169 pedwarn ("file does not end in newline");
2171 /* Now we have processed the entire input
2172 Write whichever kind of output has been requested. */
2174 if (dump_macros == dump_only)
2175 dump_all_macros ();
2176 else if (! inhibit_output) {
2177 write_output ();
2180 if (print_deps) {
2181 /* Don't actually write the deps file if compilation has failed. */
2182 if (errors == 0) {
2183 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2184 pfatal_with_name (deps_file);
2185 fputs (deps_buffer, deps_stream);
2186 putc ('\n', deps_stream);
2187 if (deps_file) {
2188 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2189 fatal ("I/O error on output");
2194 if (pcp_outfile && pcp_outfile != stdout
2195 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2196 fatal ("I/O error on `-pcp' output");
2198 if (ferror (stdout) || fclose (stdout) != 0)
2199 fatal ("I/O error on output");
2201 if (errors)
2202 exit (FATAL_EXIT_CODE);
2203 exit (SUCCESS_EXIT_CODE);
2205 perror:
2206 pfatal_with_name (in_fname);
2207 return 0;
2210 /* Given a colon-separated list of file names PATH,
2211 add all the names to the search path for include files. */
2213 static void
2214 path_include (path)
2215 char *path;
2217 char *p;
2219 p = path;
2221 if (*p)
2222 while (1) {
2223 char *q = p;
2224 char c;
2225 struct file_name_list *dirtmp;
2227 /* Find the end of this name. */
2228 while ((c = *q++) != PATH_SEPARATOR && c)
2229 continue;
2231 q[-1] = 0;
2232 dirtmp = new_include_prefix (last_include, NULL_PTR,
2233 "", p == q ? "." : p);
2234 q[-1] = c;
2235 append_include_chain (dirtmp, dirtmp);
2237 /* Advance past this name. */
2238 p = q;
2239 if (! c)
2240 break;
2244 /* Return the address of the first character in S that equals C.
2245 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2246 Return 0 if there is no such character. Assume that C itself is not '\0'.
2247 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2248 but unfortunately memchr isn't autoconfigured yet. */
2250 static U_CHAR *
2251 index0 (s, c, n)
2252 U_CHAR *s;
2253 int c;
2254 size_t n;
2256 char *p = (char *) s;
2257 for (;;) {
2258 char *q = index (p, c);
2259 if (q)
2260 return (U_CHAR *) q;
2261 else {
2262 size_t l = strlen (p);
2263 if (l == n)
2264 return 0;
2265 l++;
2266 p += l;
2267 n -= l;
2272 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2273 before main CCCP processing. Name `pcp' is also in honor of the
2274 drugs the trigraph designers must have been on.
2276 Using an extra pass through the buffer takes a little extra time,
2277 but is infinitely less hairy than trying to handle trigraphs inside
2278 strings, etc. everywhere, and also makes sure that trigraphs are
2279 only translated in the top level of processing. */
2281 static void
2282 trigraph_pcp (buf)
2283 FILE_BUF *buf;
2285 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2286 int len;
2288 fptr = bptr = sptr = buf->buf;
2289 lptr = fptr + buf->length;
2290 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2291 if (*++sptr != '?')
2292 continue;
2293 switch (*++sptr) {
2294 case '=':
2295 c = '#';
2296 break;
2297 case '(':
2298 c = '[';
2299 break;
2300 case '/':
2301 c = '\\';
2302 break;
2303 case ')':
2304 c = ']';
2305 break;
2306 case '\'':
2307 c = '^';
2308 break;
2309 case '<':
2310 c = '{';
2311 break;
2312 case '!':
2313 c = '|';
2314 break;
2315 case '>':
2316 c = '}';
2317 break;
2318 case '-':
2319 c = '~';
2320 break;
2321 case '?':
2322 sptr--;
2323 continue;
2324 default:
2325 continue;
2327 len = sptr - fptr - 2;
2329 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2330 C, this will be memmove (). */
2331 if (bptr != fptr && len > 0)
2332 bcopy ((char *) fptr, (char *) bptr, len);
2334 bptr += len;
2335 *bptr++ = c;
2336 fptr = ++sptr;
2338 len = buf->length - (fptr - buf->buf);
2339 if (bptr != fptr && len > 0)
2340 bcopy ((char *) fptr, (char *) bptr, len);
2341 buf->length -= fptr - bptr;
2342 buf->buf[buf->length] = '\0';
2343 if (warn_trigraphs && fptr != bptr)
2344 warning_with_line (0, "%lu trigraph(s) encountered",
2345 (unsigned long) (fptr - bptr) / 2);
2348 /* Move all backslash-newline pairs out of embarrassing places.
2349 Exchange all such pairs following BP
2350 with any potentially-embarrassing characters that follow them.
2351 Potentially-embarrassing characters are / and *
2352 (because a backslash-newline inside a comment delimiter
2353 would cause it not to be recognized). */
2355 static void
2356 newline_fix (bp)
2357 U_CHAR *bp;
2359 register U_CHAR *p = bp;
2361 /* First count the backslash-newline pairs here. */
2363 while (p[0] == '\\' && p[1] == '\n')
2364 p += 2;
2366 /* What follows the backslash-newlines is not embarrassing. */
2368 if (*p != '/' && *p != '*')
2369 return;
2371 /* Copy all potentially embarrassing characters
2372 that follow the backslash-newline pairs
2373 down to where the pairs originally started. */
2375 while (*p == '*' || *p == '/')
2376 *bp++ = *p++;
2378 /* Now write the same number of pairs after the embarrassing chars. */
2379 while (bp < p) {
2380 *bp++ = '\\';
2381 *bp++ = '\n';
2385 /* Like newline_fix but for use within a directive-name.
2386 Move any backslash-newlines up past any following symbol constituents. */
2388 static void
2389 name_newline_fix (bp)
2390 U_CHAR *bp;
2392 register U_CHAR *p = bp;
2394 /* First count the backslash-newline pairs here. */
2395 while (p[0] == '\\' && p[1] == '\n')
2396 p += 2;
2398 /* What follows the backslash-newlines is not embarrassing. */
2400 if (!is_idchar[*p])
2401 return;
2403 /* Copy all potentially embarrassing characters
2404 that follow the backslash-newline pairs
2405 down to where the pairs originally started. */
2407 while (is_idchar[*p])
2408 *bp++ = *p++;
2410 /* Now write the same number of pairs after the embarrassing chars. */
2411 while (bp < p) {
2412 *bp++ = '\\';
2413 *bp++ = '\n';
2417 /* Look for lint commands in comments.
2419 When we come in here, ibp points into a comment. Limit is as one expects.
2420 scan within the comment -- it should start, after lwsp, with a lint command.
2421 If so that command is returned as a (constant) string.
2423 Upon return, any arg will be pointed to with argstart and will be
2424 arglen long. Note that we don't parse that arg since it will just
2425 be printed out again. */
2427 static char *
2428 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2429 register U_CHAR *ibp;
2430 register U_CHAR *limit;
2431 U_CHAR **argstart; /* point to command arg */
2432 int *arglen, *cmdlen; /* how long they are */
2434 HOST_WIDE_INT linsize;
2435 register U_CHAR *numptr; /* temp for arg parsing */
2437 *arglen = 0;
2439 SKIP_WHITE_SPACE (ibp);
2441 if (ibp >= limit) return NULL;
2443 linsize = limit - ibp;
2445 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2446 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2447 *cmdlen = 10;
2448 return "NOTREACHED";
2450 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2451 *cmdlen = 8;
2452 return "ARGSUSED";
2454 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2455 *cmdlen = 11;
2456 return "LINTLIBRARY";
2458 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2459 *cmdlen = 7;
2460 ibp += 7; linsize -= 7;
2461 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2463 /* OK, read a number */
2464 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2465 numptr++);
2466 *arglen = numptr - *argstart;
2467 return "VARARGS";
2469 return NULL;
2473 * The main loop of the program.
2475 * Read characters from the input stack, transferring them to the
2476 * output buffer OP.
2478 * Macros are expanded and push levels on the input stack.
2479 * At the end of such a level it is popped off and we keep reading.
2480 * At the end of any other kind of level, we return.
2481 * #-directives are handled, except within macros.
2483 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2484 * and insert them when appropriate. This is set while scanning macro
2485 * arguments before substitution. It is zero when scanning for final output.
2486 * There are three types of Newline markers:
2487 * * Newline - follows a macro name that was not expanded
2488 * because it appeared inside an expansion of the same macro.
2489 * This marker prevents future expansion of that identifier.
2490 * When the input is rescanned into the final output, these are deleted.
2491 * These are also deleted by ## concatenation.
2492 * * Newline Space (or Newline and any other whitespace character)
2493 * stands for a place that tokens must be separated or whitespace
2494 * is otherwise desirable, but where the ANSI standard specifies there
2495 * is no whitespace. This marker turns into a Space (or whichever other
2496 * whitespace char appears in the marker) in the final output,
2497 * but it turns into nothing in an argument that is stringified with #.
2498 * Such stringified arguments are the only place where the ANSI standard
2499 * specifies with precision that whitespace may not appear.
2501 * During this function, IP->bufp is kept cached in IBP for speed of access.
2502 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2503 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2504 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2505 * explicitly, and before RECACHE, since RECACHE uses OBP.
2508 static void
2509 rescan (op, output_marks)
2510 FILE_BUF *op;
2511 int output_marks;
2513 /* Character being scanned in main loop. */
2514 register U_CHAR c;
2516 /* Length of pending accumulated identifier. */
2517 register int ident_length = 0;
2519 /* Hash code of pending accumulated identifier. */
2520 register int hash = 0;
2522 /* Current input level (&instack[indepth]). */
2523 FILE_BUF *ip;
2525 /* Pointer for scanning input. */
2526 register U_CHAR *ibp;
2528 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2529 register U_CHAR *limit;
2531 /* Pointer for storing output. */
2532 register U_CHAR *obp;
2534 /* REDO_CHAR is nonzero if we are processing an identifier
2535 after backing up over the terminating character.
2536 Sometimes we process an identifier without backing up over
2537 the terminating character, if the terminating character
2538 is not special. Backing up is done so that the terminating character
2539 will be dispatched on again once the identifier is dealt with. */
2540 int redo_char = 0;
2542 /* 1 if within an identifier inside of which a concatenation
2543 marker (Newline -) has been seen. */
2544 int concatenated = 0;
2546 /* While scanning a comment or a string constant,
2547 this records the line it started on, for error messages. */
2548 int start_line;
2550 /* Record position of last `real' newline. */
2551 U_CHAR *beg_of_line;
2553 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2555 #define POPMACRO \
2556 do { ip->macro->type = T_MACRO; \
2557 if (ip->free_ptr) free (ip->free_ptr); \
2558 --indepth; } while (0)
2560 /* Reload `rescan's local variables that describe the current
2561 level of the input stack. */
2563 #define RECACHE \
2564 do { ip = &instack[indepth]; \
2565 ibp = ip->bufp; \
2566 limit = ip->buf + ip->length; \
2567 op->bufp = obp; \
2568 check_expand (op, limit - ibp); \
2569 beg_of_line = 0; \
2570 obp = op->bufp; } while (0)
2572 if (no_output && instack[indepth].fname != 0)
2573 skip_if_group (&instack[indepth], 1, NULL);
2575 obp = op->bufp;
2576 RECACHE;
2578 beg_of_line = ibp;
2580 /* Our caller must always put a null after the end of
2581 the input at each input stack level. */
2582 if (*limit != 0)
2583 abort ();
2585 while (1) {
2586 c = *ibp++;
2587 *obp++ = c;
2589 switch (c) {
2590 case '\\':
2591 if (*ibp == '\n' && !ip->macro) {
2592 /* At the top level, always merge lines ending with backslash-newline,
2593 even in middle of identifier. But do not merge lines in a macro,
2594 since backslash might be followed by a newline-space marker. */
2595 ++ibp;
2596 ++ip->lineno;
2597 --obp; /* remove backslash from obuf */
2598 break;
2600 /* If ANSI, backslash is just another character outside a string. */
2601 if (!traditional)
2602 goto randomchar;
2603 /* Otherwise, backslash suppresses specialness of following char,
2604 so copy it here to prevent the switch from seeing it.
2605 But first get any pending identifier processed. */
2606 if (ident_length > 0)
2607 goto specialchar;
2608 if (ibp < limit)
2609 *obp++ = *ibp++;
2610 break;
2612 case '%':
2613 if (ident_length || ip->macro || traditional)
2614 goto randomchar;
2615 while (*ibp == '\\' && ibp[1] == '\n') {
2616 ibp += 2;
2617 ++ip->lineno;
2619 if (*ibp != ':')
2620 break;
2621 /* Treat this %: digraph as if it were #. */
2622 /* Fall through. */
2624 case '#':
2625 if (assertions_flag) {
2626 if (ident_length)
2627 goto specialchar;
2628 /* Copy #foo (bar lose) without macro expansion. */
2629 obp[-1] = '#'; /* In case it was '%'. */
2630 SKIP_WHITE_SPACE (ibp);
2631 while (is_idchar[*ibp])
2632 *obp++ = *ibp++;
2633 SKIP_WHITE_SPACE (ibp);
2634 if (*ibp == '(') {
2635 ip->bufp = ibp;
2636 skip_paren_group (ip);
2637 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2638 obp += ip->bufp - ibp;
2639 ibp = ip->bufp;
2641 break;
2644 /* If this is expanding a macro definition, don't recognize
2645 preprocessing directives. */
2646 if (ip->macro != 0)
2647 goto randomchar;
2648 /* If this is expand_into_temp_buffer,
2649 don't recognize them either. Warn about them
2650 only after an actual newline at this level,
2651 not at the beginning of the input level. */
2652 if (! ip->fname) {
2653 if (ip->buf != beg_of_line)
2654 warning ("preprocessing directive not recognized within macro arg");
2655 goto randomchar;
2657 if (ident_length)
2658 goto specialchar;
2661 /* # keyword: a # must be first nonblank char on the line */
2662 if (beg_of_line == 0)
2663 goto randomchar;
2665 U_CHAR *bp;
2667 /* Scan from start of line, skipping whitespace, comments
2668 and backslash-newlines, and see if we reach this #.
2669 If not, this # is not special. */
2670 bp = beg_of_line;
2671 /* If -traditional, require # to be at beginning of line. */
2672 if (!traditional) {
2673 while (1) {
2674 if (is_hor_space[*bp])
2675 bp++;
2676 else if (*bp == '\\' && bp[1] == '\n')
2677 bp += 2;
2678 else if (*bp == '/' && bp[1] == '*') {
2679 bp += 2;
2680 while (!(*bp == '*' && bp[1] == '/'))
2681 bp++;
2682 bp += 2;
2684 /* There is no point in trying to deal with C++ // comments here,
2685 because if there is one, then this # must be part of the
2686 comment and we would never reach here. */
2687 else break;
2689 if (c == '%') {
2690 if (bp[0] != '%')
2691 break;
2692 while (bp[1] == '\\' && bp[2] == '\n')
2693 bp += 2;
2694 if (bp + 1 != ibp)
2695 break;
2696 /* %: appears at start of line; skip past the ':' too. */
2697 bp++;
2698 ibp++;
2701 if (bp + 1 != ibp)
2702 goto randomchar;
2705 /* This # can start a directive. */
2707 --obp; /* Don't copy the '#' */
2709 ip->bufp = ibp;
2710 op->bufp = obp;
2711 if (! handle_directive (ip, op)) {
2712 #ifdef USE_C_ALLOCA
2713 alloca (0);
2714 #endif
2715 /* Not a known directive: treat it as ordinary text.
2716 IP, OP, IBP, etc. have not been changed. */
2717 if (no_output && instack[indepth].fname) {
2718 /* If not generating expanded output,
2719 what we do with ordinary text is skip it.
2720 Discard everything until next # directive. */
2721 skip_if_group (&instack[indepth], 1, 0);
2722 RECACHE;
2723 beg_of_line = ibp;
2724 break;
2726 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2727 /* Don't expand an identifier that could be a macro directive.
2728 (Section 3.8.3 of the ANSI C standard) */
2729 SKIP_WHITE_SPACE (ibp);
2730 if (is_idstart[*ibp])
2732 *obp++ = *ibp++;
2733 while (is_idchar[*ibp])
2734 *obp++ = *ibp++;
2736 goto randomchar;
2738 #ifdef USE_C_ALLOCA
2739 alloca (0);
2740 #endif
2741 /* A # directive has been successfully processed. */
2742 /* If not generating expanded output, ignore everything until
2743 next # directive. */
2744 if (no_output && instack[indepth].fname)
2745 skip_if_group (&instack[indepth], 1, 0);
2746 obp = op->bufp;
2747 RECACHE;
2748 beg_of_line = ibp;
2749 break;
2751 case '\"': /* skip quoted string */
2752 case '\'':
2753 /* A single quoted string is treated like a double -- some
2754 programs (e.g., troff) are perverse this way */
2756 /* Handle any pending identifier;
2757 but the L in L'...' or L"..." is not an identifier. */
2758 if (ident_length
2759 && ! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2760 goto specialchar;
2762 start_line = ip->lineno;
2764 /* Skip ahead to a matching quote. */
2766 while (1) {
2767 if (ibp >= limit) {
2768 if (ip->macro != 0) {
2769 /* try harder: this string crosses a macro expansion boundary.
2770 This can happen naturally if -traditional.
2771 Otherwise, only -D can make a macro with an unmatched quote. */
2772 POPMACRO;
2773 RECACHE;
2774 continue;
2776 if (!traditional) {
2777 error_with_line (line_for_error (start_line),
2778 "unterminated string or character constant");
2779 error_with_line (multiline_string_line,
2780 "possible real start of unterminated constant");
2781 multiline_string_line = 0;
2783 break;
2785 *obp++ = *ibp;
2786 switch (*ibp++) {
2787 case '\n':
2788 ++ip->lineno;
2789 ++op->lineno;
2790 /* Traditionally, end of line ends a string constant with no error.
2791 So exit the loop and record the new line. */
2792 if (traditional) {
2793 beg_of_line = ibp;
2794 goto while2end;
2796 if (c == '\'') {
2797 error_with_line (line_for_error (start_line),
2798 "unterminated character constant");
2799 goto while2end;
2801 if (multiline_string_line == 0) {
2802 if (pedantic)
2803 pedwarn_with_line (line_for_error (start_line),
2804 "string constant runs past end of line");
2805 multiline_string_line = ip->lineno - 1;
2807 break;
2809 case '\\':
2810 if (ibp >= limit)
2811 break;
2812 if (*ibp == '\n') {
2813 /* Backslash newline is replaced by nothing at all,
2814 but keep the line counts correct. */
2815 --obp;
2816 ++ibp;
2817 ++ip->lineno;
2818 } else {
2819 /* ANSI stupidly requires that in \\ the second \
2820 is *not* prevented from combining with a newline. */
2821 while (*ibp == '\\' && ibp[1] == '\n') {
2822 ibp += 2;
2823 ++ip->lineno;
2825 *obp++ = *ibp++;
2827 break;
2829 case '\"':
2830 case '\'':
2831 if (ibp[-1] == c)
2832 goto while2end;
2833 break;
2836 while2end:
2837 break;
2839 case '/':
2840 if (*ibp == '\\' && ibp[1] == '\n')
2841 newline_fix (ibp);
2843 if (*ibp != '*'
2844 && !(cplusplus_comments && *ibp == '/'))
2845 goto randomchar;
2846 if (ip->macro != 0)
2847 goto randomchar;
2848 if (ident_length)
2849 goto specialchar;
2851 if (*ibp == '/') {
2852 /* C++ style comment... */
2853 start_line = ip->lineno;
2855 /* Comments are equivalent to spaces. */
2856 if (! put_out_comments)
2857 obp[-1] = ' ';
2860 U_CHAR *before_bp = ibp;
2862 while (++ibp < limit) {
2863 if (*ibp == '\n') {
2864 if (ibp[-1] != '\\') {
2865 if (put_out_comments) {
2866 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2867 obp += ibp - before_bp;
2869 break;
2871 if (warn_comments)
2872 warning ("multiline `//' comment");
2873 ++ip->lineno;
2874 /* Copy the newline into the output buffer, in order to
2875 avoid the pain of a #line every time a multiline comment
2876 is seen. */
2877 if (!put_out_comments)
2878 *obp++ = '\n';
2879 ++op->lineno;
2882 break;
2886 /* Ordinary C comment. Skip it, optionally copying it to output. */
2888 start_line = ip->lineno;
2890 ++ibp; /* Skip the star. */
2892 /* If this cpp is for lint, we peek inside the comments: */
2893 if (for_lint) {
2894 U_CHAR *argbp;
2895 int cmdlen, arglen;
2896 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2898 if (lintcmd != NULL) {
2899 op->bufp = obp;
2900 check_expand (op, cmdlen + arglen + 14);
2901 obp = op->bufp;
2902 /* I believe it is always safe to emit this newline: */
2903 obp[-1] = '\n';
2904 bcopy ("#pragma lint ", (char *) obp, 13);
2905 obp += 13;
2906 bcopy (lintcmd, (char *) obp, cmdlen);
2907 obp += cmdlen;
2909 if (arglen != 0) {
2910 *(obp++) = ' ';
2911 bcopy (argbp, (char *) obp, arglen);
2912 obp += arglen;
2915 /* OK, now bring us back to the state we were in before we entered
2916 this branch. We need #line because the #pragma's newline always
2917 messes up the line count. */
2918 op->bufp = obp;
2919 output_line_directive (ip, op, 0, same_file);
2920 check_expand (op, limit - ibp + 2);
2921 obp = op->bufp;
2922 *(obp++) = '/';
2926 /* Comments are equivalent to spaces.
2927 Note that we already output the slash; we might not want it.
2928 For -traditional, a comment is equivalent to nothing. */
2929 if (! put_out_comments) {
2930 if (traditional)
2931 obp--;
2932 else
2933 obp[-1] = ' ';
2935 else
2936 *obp++ = '*';
2939 U_CHAR *before_bp = ibp;
2941 for (;;) {
2942 switch (*ibp++) {
2943 case '*':
2944 if (ibp[-2] == '/' && warn_comments)
2945 warning ("`/*' within comment");
2946 if (*ibp == '\\' && ibp[1] == '\n')
2947 newline_fix (ibp);
2948 if (*ibp == '/')
2949 goto comment_end;
2950 break;
2952 case '\n':
2953 ++ip->lineno;
2954 /* Copy the newline into the output buffer, in order to
2955 avoid the pain of a #line every time a multiline comment
2956 is seen. */
2957 if (!put_out_comments)
2958 *obp++ = '\n';
2959 ++op->lineno;
2960 break;
2962 case 0:
2963 if (limit < ibp) {
2964 error_with_line (line_for_error (start_line),
2965 "unterminated comment");
2966 goto limit_reached;
2968 break;
2971 comment_end:
2973 ibp++;
2974 if (put_out_comments) {
2975 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2976 obp += ibp - before_bp;
2979 break;
2981 case '$':
2982 if (! is_idchar['$'])
2983 goto randomchar;
2984 if (pedantic)
2985 pedwarn ("`$' in identifier");
2986 goto letter;
2988 case '0': case '1': case '2': case '3': case '4':
2989 case '5': case '6': case '7': case '8': case '9':
2990 /* If digit is not part of identifier, it starts a number,
2991 which means that following letters are not an identifier.
2992 "0x5" does not refer to an identifier "x5".
2993 So copy all alphanumerics that follow without accumulating
2994 as an identifier. Periods also, for sake of "3.e7". */
2996 if (ident_length == 0) {
2997 for (;;) {
2998 while (ibp[0] == '\\' && ibp[1] == '\n') {
2999 ++ip->lineno;
3000 ibp += 2;
3002 c = *ibp++;
3003 if (!is_idchar[c] && c != '.') {
3004 --ibp;
3005 break;
3007 *obp++ = c;
3008 /* A sign can be part of a preprocessing number
3009 if it follows an `e' or `p'. */
3010 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3011 while (ibp[0] == '\\' && ibp[1] == '\n') {
3012 ++ip->lineno;
3013 ibp += 2;
3015 if (*ibp == '+' || *ibp == '-') {
3016 *obp++ = *ibp++;
3017 /* But traditional C does not let the token go past the sign,
3018 and C89 does not allow `p'. */
3019 if (traditional || (c89 && (c == 'p' || c == 'P')))
3020 break;
3024 break;
3026 /* fall through */
3028 case '_':
3029 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3030 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3031 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3032 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3033 case 'y': case 'z':
3034 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3035 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3036 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3037 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3038 case 'Y': case 'Z':
3039 letter:
3040 ident_length++;
3041 /* Compute step of hash function, to avoid a proc call on every token */
3042 hash = HASHSTEP (hash, c);
3043 break;
3045 case '\n':
3046 if (ip->fname == 0 && *ibp == '-') {
3047 /* Newline - inhibits expansion of preceding token.
3048 If expanding a macro arg, we keep the newline -.
3049 In final output, it is deleted.
3050 We recognize Newline - in macro bodies and macro args. */
3051 if (! concatenated) {
3052 ident_length = 0;
3053 hash = 0;
3055 ibp++;
3056 if (!output_marks) {
3057 obp--;
3058 } else {
3059 /* If expanding a macro arg, keep the newline -. */
3060 *obp++ = '-';
3062 break;
3065 /* If reprocessing a macro expansion, newline is a special marker. */
3066 else if (ip->macro != 0) {
3067 /* Newline White is a "funny space" to separate tokens that are
3068 supposed to be separate but without space between.
3069 Here White means any whitespace character.
3070 Newline - marks a recursive macro use that is not
3071 supposed to be expandable. */
3073 if (is_space[*ibp]) {
3074 /* Newline Space does not prevent expansion of preceding token
3075 so expand the preceding token and then come back. */
3076 if (ident_length > 0)
3077 goto specialchar;
3079 /* If generating final output, newline space makes a space. */
3080 if (!output_marks) {
3081 obp[-1] = *ibp++;
3082 /* And Newline Newline makes a newline, so count it. */
3083 if (obp[-1] == '\n')
3084 op->lineno++;
3085 } else {
3086 /* If expanding a macro arg, keep the newline space.
3087 If the arg gets stringified, newline space makes nothing. */
3088 *obp++ = *ibp++;
3090 } else abort (); /* Newline followed by something random? */
3091 break;
3094 /* If there is a pending identifier, handle it and come back here. */
3095 if (ident_length > 0)
3096 goto specialchar;
3098 beg_of_line = ibp;
3100 /* Update the line counts and output a #line if necessary. */
3101 ++ip->lineno;
3102 ++op->lineno;
3103 if (ip->lineno != op->lineno) {
3104 op->bufp = obp;
3105 output_line_directive (ip, op, 1, same_file);
3106 check_expand (op, limit - ibp);
3107 obp = op->bufp;
3109 break;
3111 /* Come here either after (1) a null character that is part of the input
3112 or (2) at the end of the input, because there is a null there. */
3113 case 0:
3114 if (ibp <= limit)
3115 /* Our input really contains a null character. */
3116 goto randomchar;
3118 limit_reached:
3119 /* At end of a macro-expansion level, pop it and read next level. */
3120 if (ip->macro != 0) {
3121 obp--;
3122 ibp--;
3123 /* If traditional, and we have an identifier that ends here,
3124 process it now, so we get the right error for recursion. */
3125 if (traditional && ident_length
3126 && ! is_idchar[*instack[indepth - 1].bufp]) {
3127 redo_char = 1;
3128 goto randomchar;
3130 POPMACRO;
3131 RECACHE;
3132 break;
3135 /* If we don't have a pending identifier,
3136 return at end of input. */
3137 if (ident_length == 0) {
3138 obp--;
3139 ibp--;
3140 op->bufp = obp;
3141 ip->bufp = ibp;
3142 goto ending;
3145 /* If we do have a pending identifier, just consider this null
3146 a special character and arrange to dispatch on it again.
3147 The second time, IDENT_LENGTH will be zero so we will return. */
3149 /* Fall through */
3151 specialchar:
3153 /* Handle the case of a character such as /, ', " or null
3154 seen following an identifier. Back over it so that
3155 after the identifier is processed the special char
3156 will be dispatched on again. */
3158 ibp--;
3159 obp--;
3160 redo_char = 1;
3162 default:
3164 randomchar:
3166 if (ident_length > 0) {
3167 register HASHNODE *hp;
3169 /* We have just seen an identifier end. If it's a macro, expand it.
3171 IDENT_LENGTH is the length of the identifier
3172 and HASH is its hash code.
3174 The identifier has already been copied to the output,
3175 so if it is a macro we must remove it.
3177 If REDO_CHAR is 0, the char that terminated the identifier
3178 has been skipped in the output and the input.
3179 OBP-IDENT_LENGTH-1 points to the identifier.
3180 If the identifier is a macro, we must back over the terminator.
3182 If REDO_CHAR is 1, the terminating char has already been
3183 backed over. OBP-IDENT_LENGTH points to the identifier. */
3185 if (!pcp_outfile || pcp_inside_if) {
3186 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3187 hp = hp->next) {
3189 if (hp->length == ident_length) {
3190 int obufp_before_macroname;
3191 int op_lineno_before_macroname;
3192 register int i = ident_length;
3193 register U_CHAR *p = hp->name;
3194 register U_CHAR *q = obp - i;
3195 int disabled;
3197 if (! redo_char)
3198 q--;
3200 do { /* All this to avoid a strncmp () */
3201 if (*p++ != *q++)
3202 goto hashcollision;
3203 } while (--i);
3205 /* We found a use of a macro name.
3206 see if the context shows it is a macro call. */
3208 /* Back up over terminating character if not already done. */
3209 if (! redo_char) {
3210 ibp--;
3211 obp--;
3214 /* Save this as a displacement from the beginning of the output
3215 buffer. We can not save this as a position in the output
3216 buffer, because it may get realloc'ed by RECACHE. */
3217 obufp_before_macroname = (obp - op->buf) - ident_length;
3218 op_lineno_before_macroname = op->lineno;
3220 if (hp->type == T_PCSTRING) {
3221 pcstring_used (hp); /* Mark the definition of this key
3222 as needed, ensuring that it
3223 will be output. */
3224 break; /* Exit loop, since the key cannot have a
3225 definition any longer. */
3228 /* Record whether the macro is disabled. */
3229 disabled = hp->type == T_DISABLED;
3231 /* This looks like a macro ref, but if the macro was disabled,
3232 just copy its name and put in a marker if requested. */
3234 if (disabled) {
3235 #if 0
3236 /* This error check caught useful cases such as
3237 #define foo(x,y) bar (x (y,0), y)
3238 foo (foo, baz) */
3239 if (traditional)
3240 error ("recursive use of macro `%s'", hp->name);
3241 #endif
3243 if (output_marks) {
3244 check_expand (op, limit - ibp + 2);
3245 *obp++ = '\n';
3246 *obp++ = '-';
3248 break;
3251 /* If macro wants an arglist, verify that a '(' follows.
3252 first skip all whitespace, copying it to the output
3253 after the macro name. Then, if there is no '(',
3254 decide this is not a macro call and leave things that way. */
3255 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3256 && hp->value.defn->nargs >= 0)
3258 U_CHAR *old_ibp = ibp;
3259 U_CHAR *old_obp = obp;
3260 int old_iln = ip->lineno;
3261 int old_oln = op->lineno;
3263 while (1) {
3264 /* Scan forward over whitespace, copying it to the output. */
3265 if (ibp == limit && ip->macro != 0) {
3266 POPMACRO;
3267 RECACHE;
3268 old_ibp = ibp;
3269 old_obp = obp;
3270 old_iln = ip->lineno;
3271 old_oln = op->lineno;
3273 /* A comment: copy it unchanged or discard it. */
3274 else if (*ibp == '/' && ibp[1] == '*') {
3275 if (put_out_comments) {
3276 *obp++ = '/';
3277 *obp++ = '*';
3278 } else if (! traditional) {
3279 *obp++ = ' ';
3281 ibp += 2;
3282 while (ibp + 1 != limit
3283 && !(ibp[0] == '*' && ibp[1] == '/')) {
3284 /* We need not worry about newline-marks,
3285 since they are never found in comments. */
3286 if (*ibp == '\n') {
3287 /* Newline in a file. Count it. */
3288 ++ip->lineno;
3289 ++op->lineno;
3291 if (put_out_comments)
3292 *obp++ = *ibp++;
3293 else
3294 ibp++;
3296 ibp += 2;
3297 if (put_out_comments) {
3298 *obp++ = '*';
3299 *obp++ = '/';
3302 else if (is_space[*ibp]) {
3303 *obp++ = *ibp++;
3304 if (ibp[-1] == '\n') {
3305 if (ip->macro == 0) {
3306 /* Newline in a file. Count it. */
3307 ++ip->lineno;
3308 ++op->lineno;
3309 } else if (!output_marks) {
3310 /* A newline mark, and we don't want marks
3311 in the output. If it is newline-hyphen,
3312 discard it entirely. Otherwise, it is
3313 newline-whitechar, so keep the whitechar. */
3314 obp--;
3315 if (*ibp == '-')
3316 ibp++;
3317 else {
3318 if (*ibp == '\n')
3319 ++op->lineno;
3320 *obp++ = *ibp++;
3322 } else {
3323 /* A newline mark; copy both chars to the output. */
3324 *obp++ = *ibp++;
3328 else break;
3330 if (*ibp != '(') {
3331 /* It isn't a macro call.
3332 Put back the space that we just skipped. */
3333 ibp = old_ibp;
3334 obp = old_obp;
3335 ip->lineno = old_iln;
3336 op->lineno = old_oln;
3337 /* Exit the for loop. */
3338 break;
3342 /* This is now known to be a macro call.
3343 Discard the macro name from the output,
3344 along with any following whitespace just copied,
3345 but preserve newlines if not outputting marks since this
3346 is more likely to do the right thing with line numbers. */
3347 obp = op->buf + obufp_before_macroname;
3348 if (output_marks)
3349 op->lineno = op_lineno_before_macroname;
3350 else {
3351 int newlines = op->lineno - op_lineno_before_macroname;
3352 while (0 < newlines--)
3353 *obp++ = '\n';
3356 /* Prevent accidental token-pasting with a character
3357 before the macro call. */
3358 if (!traditional && obp != op->buf) {
3359 switch (obp[-1]) {
3360 case '!': case '%': case '&': case '*':
3361 case '+': case '-': case '.': case '/':
3362 case ':': case '<': case '=': case '>':
3363 case '^': case '|':
3364 /* If we are expanding a macro arg, make a newline marker
3365 to separate the tokens. If we are making real output,
3366 a plain space will do. */
3367 if (output_marks)
3368 *obp++ = '\n';
3369 *obp++ = ' ';
3373 /* Expand the macro, reading arguments as needed,
3374 and push the expansion on the input stack. */
3375 ip->bufp = ibp;
3376 op->bufp = obp;
3377 macroexpand (hp, op);
3379 /* Reexamine input stack, since macroexpand has pushed
3380 a new level on it. */
3381 obp = op->bufp;
3382 RECACHE;
3383 break;
3385 hashcollision:
3387 } /* End hash-table-search loop */
3389 ident_length = hash = 0; /* Stop collecting identifier */
3390 redo_char = 0;
3391 concatenated = 0;
3392 } /* End if (ident_length > 0) */
3393 } /* End switch */
3394 } /* End per-char loop */
3396 /* Come here to return -- but first give an error message
3397 if there was an unterminated successful conditional. */
3398 ending:
3399 if (if_stack != ip->if_stack)
3401 char *str;
3403 switch (if_stack->type)
3405 case T_IF:
3406 str = "if";
3407 break;
3408 case T_IFDEF:
3409 str = "ifdef";
3410 break;
3411 case T_IFNDEF:
3412 str = "ifndef";
3413 break;
3414 case T_ELSE:
3415 str = "else";
3416 break;
3417 case T_ELIF:
3418 str = "elif";
3419 break;
3420 default:
3421 abort ();
3424 error_with_line (line_for_error (if_stack->lineno),
3425 "unterminated `#%s' conditional", str);
3427 if_stack = ip->if_stack;
3431 * Rescan a string into a temporary buffer and return the result
3432 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3434 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3435 * and insert such markers when appropriate. See `rescan' for details.
3436 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3437 * before substitution; it is 0 for other uses.
3439 static FILE_BUF
3440 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3441 U_CHAR *buf, *limit;
3442 int output_marks, assertions;
3444 register FILE_BUF *ip;
3445 FILE_BUF obuf;
3446 int length = limit - buf;
3447 U_CHAR *buf1;
3448 int odepth = indepth;
3449 int save_assertions_flag = assertions_flag;
3451 assertions_flag = assertions;
3453 if (length < 0)
3454 abort ();
3456 /* Set up the input on the input stack. */
3458 buf1 = (U_CHAR *) alloca (length + 1);
3460 register U_CHAR *p1 = buf;
3461 register U_CHAR *p2 = buf1;
3463 while (p1 != limit)
3464 *p2++ = *p1++;
3466 buf1[length] = 0;
3468 /* Set up to receive the output. */
3470 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3471 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3472 obuf.fname = 0;
3473 obuf.macro = 0;
3474 obuf.free_ptr = 0;
3476 CHECK_DEPTH ({return obuf;});
3478 ++indepth;
3480 ip = &instack[indepth];
3481 ip->fname = 0;
3482 ip->nominal_fname = 0;
3483 ip->inc = 0;
3484 ip->system_header_p = 0;
3485 ip->macro = 0;
3486 ip->free_ptr = 0;
3487 ip->length = length;
3488 ip->buf = ip->bufp = buf1;
3489 ip->if_stack = if_stack;
3491 ip->lineno = obuf.lineno = 1;
3493 /* Scan the input, create the output. */
3494 rescan (&obuf, output_marks);
3496 /* Pop input stack to original state. */
3497 --indepth;
3499 if (indepth != odepth)
3500 abort ();
3502 /* Record the output. */
3503 obuf.length = obuf.bufp - obuf.buf;
3505 assertions_flag = save_assertions_flag;
3506 return obuf;
3510 * Process a # directive. Expects IP->bufp to point after the '#', as in
3511 * `#define foo bar'. Passes to the directive handler
3512 * (do_define, do_include, etc.): the addresses of the 1st and
3513 * last chars of the directive (starting immediately after the #
3514 * keyword), plus op and the keyword table pointer. If the directive
3515 * contains comments it is copied into a temporary buffer sans comments
3516 * and the temporary buffer is passed to the directive handler instead.
3517 * Likewise for backslash-newlines.
3519 * Returns nonzero if this was a known # directive.
3520 * Otherwise, returns zero, without advancing the input pointer.
3523 static int
3524 handle_directive (ip, op)
3525 FILE_BUF *ip, *op;
3527 register U_CHAR *bp, *cp;
3528 register struct directive *kt;
3529 register int ident_length;
3530 U_CHAR *resume_p;
3532 /* Nonzero means we must copy the entire directive
3533 to get rid of comments or backslash-newlines. */
3534 int copy_directive = 0;
3536 U_CHAR *ident, *after_ident;
3538 bp = ip->bufp;
3540 /* Record where the directive started. do_xifdef needs this. */
3541 directive_start = bp - 1;
3543 /* Skip whitespace and \-newline. */
3544 while (1) {
3545 if (is_hor_space[*bp]) {
3546 if (*bp != ' ' && *bp != '\t' && pedantic)
3547 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3548 bp++;
3549 } else if (*bp == '/' && (bp[1] == '*'
3550 || (cplusplus_comments && bp[1] == '/'))) {
3551 ip->bufp = bp + 2;
3552 skip_to_end_of_comment (ip, &ip->lineno, 0);
3553 bp = ip->bufp;
3554 } else if (*bp == '\\' && bp[1] == '\n') {
3555 bp += 2; ip->lineno++;
3556 } else break;
3559 /* Now find end of directive name.
3560 If we encounter a backslash-newline, exchange it with any following
3561 symbol-constituents so that we end up with a contiguous name. */
3563 cp = bp;
3564 while (1) {
3565 if (is_idchar[*cp])
3566 cp++;
3567 else {
3568 if (*cp == '\\' && cp[1] == '\n')
3569 name_newline_fix (cp);
3570 if (is_idchar[*cp])
3571 cp++;
3572 else break;
3575 ident_length = cp - bp;
3576 ident = bp;
3577 after_ident = cp;
3579 /* A line of just `#' becomes blank. */
3581 if (ident_length == 0 && *after_ident == '\n') {
3582 ip->bufp = after_ident;
3583 return 1;
3586 if (ident_length == 0 || !is_idstart[*ident]) {
3587 U_CHAR *p = ident;
3588 while (is_idchar[*p]) {
3589 if (*p < '0' || *p > '9')
3590 break;
3591 p++;
3593 /* Handle # followed by a line number. */
3594 if (p != ident && !is_idchar[*p]) {
3595 static struct directive line_directive_table[] = {
3596 { 4, do_line, "line", T_LINE},
3598 if (pedantic)
3599 pedwarn ("`#' followed by integer");
3600 after_ident = ident;
3601 kt = line_directive_table;
3602 goto old_linenum;
3605 /* Avoid error for `###' and similar cases unless -pedantic. */
3606 if (p == ident) {
3607 while (*p == '#' || is_hor_space[*p]) p++;
3608 if (*p == '\n') {
3609 if (pedantic && !lang_asm)
3610 warning ("invalid preprocessing directive");
3611 return 0;
3615 if (!lang_asm)
3616 error ("invalid preprocessing directive name");
3618 return 0;
3622 * Decode the keyword and call the appropriate expansion
3623 * routine, after moving the input pointer up to the next line.
3625 for (kt = directive_table; kt->length > 0; kt++) {
3626 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3627 register U_CHAR *buf;
3628 register U_CHAR *limit;
3629 int unterminated;
3630 int junk;
3631 int *already_output;
3633 /* Nonzero means do not delete comments within the directive.
3634 #define needs this when -traditional. */
3635 int keep_comments;
3637 old_linenum:
3639 limit = ip->buf + ip->length;
3640 unterminated = 0;
3641 already_output = 0;
3642 keep_comments = traditional && kt->type == T_DEFINE;
3643 /* #import is defined only in Objective C, or when on the NeXT. */
3644 if (kt->type == T_IMPORT
3645 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3646 break;
3648 /* Find the end of this directive (first newline not backslashed
3649 and not in a string or comment).
3650 Set COPY_DIRECTIVE if the directive must be copied
3651 (it contains a backslash-newline or a comment). */
3653 buf = bp = after_ident;
3654 while (bp < limit) {
3655 register U_CHAR c = *bp++;
3656 switch (c) {
3657 case '\\':
3658 if (bp < limit) {
3659 if (*bp == '\n') {
3660 ip->lineno++;
3661 copy_directive = 1;
3662 bp++;
3663 } else if (traditional)
3664 bp++;
3666 break;
3668 case '\'':
3669 case '\"':
3670 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3671 /* Don't bother calling the directive if we already got an error
3672 message due to unterminated string. Skip everything and pretend
3673 we called the directive. */
3674 if (unterminated) {
3675 if (traditional) {
3676 /* Traditional preprocessing permits unterminated strings. */
3677 ip->bufp = bp;
3678 goto endloop1;
3680 ip->bufp = bp;
3681 return 1;
3683 break;
3685 /* <...> is special for #include. */
3686 case '<':
3687 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3688 break;
3689 while (bp < limit && *bp != '>' && *bp != '\n') {
3690 if (*bp == '\\' && bp[1] == '\n') {
3691 ip->lineno++;
3692 copy_directive = 1;
3693 bp++;
3695 bp++;
3697 break;
3699 case '/':
3700 if (*bp == '\\' && bp[1] == '\n')
3701 newline_fix (bp);
3702 if (*bp == '*'
3703 || (cplusplus_comments && *bp == '/')) {
3704 U_CHAR *obp = bp - 1;
3705 ip->bufp = bp + 1;
3706 skip_to_end_of_comment (ip, &ip->lineno, 0);
3707 bp = ip->bufp;
3708 /* No need to copy the directive because of a comment at the end;
3709 just don't include the comment in the directive. */
3710 if (!put_out_comments) {
3711 U_CHAR *p;
3712 for (p = bp; *p == ' ' || *p == '\t'; p++)
3713 continue;
3714 if (*p == '\n') {
3715 bp = obp;
3716 goto endloop1;
3719 /* Don't remove the comments if -traditional. */
3720 if (! keep_comments)
3721 copy_directive++;
3723 break;
3725 case '\f':
3726 case '\r':
3727 case '\v':
3728 if (pedantic)
3729 pedwarn ("%s in preprocessing directive", char_name[c]);
3730 break;
3732 case '\n':
3733 --bp; /* Point to the newline */
3734 ip->bufp = bp;
3735 goto endloop1;
3738 ip->bufp = bp;
3740 endloop1:
3741 resume_p = ip->bufp;
3742 /* BP is the end of the directive.
3743 RESUME_P is the next interesting data after the directive.
3744 A comment may come between. */
3746 /* If a directive should be copied through, and -C was given,
3747 pass it through before removing comments. */
3748 if (!no_output && put_out_comments
3749 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
3750 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3751 : kt->type == T_PRAGMA)) {
3752 int len;
3754 /* Output directive name. */
3755 check_expand (op, kt->length + 2);
3756 /* Make sure # is at the start of a line */
3757 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3758 op->lineno++;
3759 *op->bufp++ = '\n';
3761 *op->bufp++ = '#';
3762 bcopy (kt->name, op->bufp, kt->length);
3763 op->bufp += kt->length;
3765 /* Output arguments. */
3766 len = (bp - buf);
3767 check_expand (op, len);
3768 bcopy (buf, (char *) op->bufp, len);
3769 op->bufp += len;
3770 /* Take account of any (escaped) newlines just output. */
3771 while (--len >= 0)
3772 if (buf[len] == '\n')
3773 op->lineno++;
3775 already_output = &junk;
3776 } /* Don't we need a newline or #line? */
3778 if (copy_directive) {
3779 register U_CHAR *xp = buf;
3780 /* Need to copy entire directive into temp buffer before dispatching */
3782 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3783 some slop */
3784 buf = cp;
3786 /* Copy to the new buffer, deleting comments
3787 and backslash-newlines (and whitespace surrounding the latter). */
3789 while (xp < bp) {
3790 register U_CHAR c = *xp++;
3791 *cp++ = c;
3793 switch (c) {
3794 case '\n':
3795 abort (); /* A bare newline should never part of the line. */
3796 break;
3798 /* <...> is special for #include. */
3799 case '<':
3800 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3801 break;
3802 while (xp < bp && c != '>') {
3803 c = *xp++;
3804 if (c == '\\' && xp < bp && *xp == '\n')
3805 xp++;
3806 else
3807 *cp++ = c;
3809 break;
3811 case '\\':
3812 if (*xp == '\n') {
3813 xp++;
3814 cp--;
3815 if (cp != buf && is_hor_space[cp[-1]]) {
3816 while (cp - 1 != buf && is_hor_space[cp[-2]])
3817 cp--;
3818 SKIP_WHITE_SPACE (xp);
3819 } else if (is_hor_space[*xp]) {
3820 *cp++ = *xp++;
3821 SKIP_WHITE_SPACE (xp);
3823 } else if (traditional && xp < bp) {
3824 *cp++ = *xp++;
3826 break;
3828 case '\'':
3829 case '\"':
3831 register U_CHAR *bp1
3832 = skip_quoted_string (xp - 1, bp, ip->lineno,
3833 NULL_PTR, NULL_PTR, NULL_PTR);
3834 while (xp != bp1)
3835 if (*xp == '\\') {
3836 if (*++xp != '\n')
3837 *cp++ = '\\';
3838 else
3839 xp++;
3840 } else
3841 *cp++ = *xp++;
3843 break;
3845 case '/':
3846 if (*xp == '*'
3847 || (cplusplus_comments && *xp == '/')) {
3848 ip->bufp = xp + 1;
3849 /* If we already copied the directive through,
3850 already_output != 0 prevents outputting comment now. */
3851 skip_to_end_of_comment (ip, already_output, 0);
3852 if (keep_comments)
3853 while (xp != ip->bufp)
3854 *cp++ = *xp++;
3855 /* Delete or replace the slash. */
3856 else if (traditional)
3857 cp--;
3858 else
3859 cp[-1] = ' ';
3860 xp = ip->bufp;
3865 /* Null-terminate the copy. */
3867 *cp = 0;
3868 } else
3869 cp = bp;
3871 ip->bufp = resume_p;
3873 /* Some directives should be written out for cc1 to process,
3874 just as if they were not defined. And sometimes we're copying
3875 directives through. */
3877 if (!no_output && already_output == 0
3878 && (kt->type == T_DEFINE ? dump_names <= dump_macros
3879 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3880 : kt->type == T_PRAGMA)) {
3881 int len;
3883 /* Output directive name. */
3884 check_expand (op, kt->length + 1);
3885 *op->bufp++ = '#';
3886 bcopy (kt->name, (char *) op->bufp, kt->length);
3887 op->bufp += kt->length;
3889 if (kt->type == T_DEFINE && dump_macros == dump_names) {
3890 /* Output `#define name' only. */
3891 U_CHAR *xp = buf;
3892 U_CHAR *yp;
3893 SKIP_WHITE_SPACE (xp);
3894 yp = xp;
3895 while (is_idchar[*xp]) xp++;
3896 len = (xp - yp);
3897 check_expand (op, len + 1);
3898 *op->bufp++ = ' ';
3899 bcopy (yp, (char *) op->bufp, len);
3900 } else {
3901 /* Output entire directive. */
3902 len = (cp - buf);
3903 check_expand (op, len);
3904 bcopy (buf, (char *) op->bufp, len);
3906 op->bufp += len;
3907 } /* Don't we need a newline or #line? */
3909 /* Call the appropriate directive handler. buf now points to
3910 either the appropriate place in the input buffer, or to
3911 the temp buffer if it was necessary to make one. cp
3912 points to the first char after the contents of the (possibly
3913 copied) directive, in either case. */
3914 (*kt->func) (buf, cp, op, kt);
3915 check_expand (op, ip->length - (ip->bufp - ip->buf));
3917 return 1;
3921 /* It is deliberate that we don't warn about undefined directives.
3922 That is the responsibility of cc1. */
3923 return 0;
3926 static struct tm *
3927 timestamp ()
3929 static struct tm *timebuf;
3930 if (!timebuf) {
3931 time_t t = time ((time_t *) 0);
3932 timebuf = localtime (&t);
3934 return timebuf;
3937 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3938 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3942 * expand things like __FILE__. Place the expansion into the output
3943 * buffer *without* rescanning.
3946 static void
3947 special_symbol (hp, op)
3948 HASHNODE *hp;
3949 FILE_BUF *op;
3951 char *buf;
3952 int i, len;
3953 int true_indepth;
3954 FILE_BUF *ip = NULL;
3955 struct tm *timebuf;
3957 int paren = 0; /* For special `defined' keyword */
3959 if (pcp_outfile && pcp_inside_if
3960 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
3961 error ("Predefined macro `%s' used inside `#if' during precompilation",
3962 hp->name);
3964 for (i = indepth; i >= 0; i--)
3965 if (instack[i].fname != NULL) {
3966 ip = &instack[i];
3967 break;
3969 if (ip == NULL) {
3970 error ("cccp error: not in any file?!");
3971 return; /* the show must go on */
3974 switch (hp->type) {
3975 case T_FILE:
3976 case T_BASE_FILE:
3978 char *string;
3979 if (hp->type == T_FILE)
3980 string = ip->nominal_fname;
3981 else
3982 string = instack[0].nominal_fname;
3984 if (string)
3986 buf = (char *) alloca (3 + 4 * strlen (string));
3987 quote_string (buf, string);
3989 else
3990 buf = "\"\"";
3992 break;
3995 case T_INCLUDE_LEVEL:
3996 true_indepth = 0;
3997 for (i = indepth; i >= 0; i--)
3998 if (instack[i].fname != NULL)
3999 true_indepth++;
4001 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4002 sprintf (buf, "%d", true_indepth - 1);
4003 break;
4005 case T_VERSION:
4006 buf = (char *) alloca (3 + strlen (version_string));
4007 sprintf (buf, "\"%s\"", version_string);
4008 break;
4010 #ifndef NO_BUILTIN_SIZE_TYPE
4011 case T_SIZE_TYPE:
4012 buf = SIZE_TYPE;
4013 break;
4014 #endif
4016 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4017 case T_PTRDIFF_TYPE:
4018 buf = PTRDIFF_TYPE;
4019 break;
4020 #endif
4022 case T_WCHAR_TYPE:
4023 buf = wchar_type;
4024 break;
4026 case T_USER_LABEL_PREFIX_TYPE:
4027 buf = USER_LABEL_PREFIX;
4028 break;
4030 case T_REGISTER_PREFIX_TYPE:
4031 buf = REGISTER_PREFIX;
4032 break;
4034 case T_IMMEDIATE_PREFIX_TYPE:
4035 buf = IMMEDIATE_PREFIX;
4036 break;
4038 case T_CONST:
4039 buf = hp->value.cpval;
4040 #ifdef STDC_0_IN_SYSTEM_HEADERS
4041 if (ip->system_header_p
4042 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4043 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4044 buf = "0";
4045 #endif
4046 if (pcp_inside_if && pcp_outfile)
4047 /* Output a precondition for this macro use */
4048 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4049 break;
4051 case T_SPECLINE:
4052 buf = (char *) alloca (10);
4053 sprintf (buf, "%d", ip->lineno);
4054 break;
4056 case T_DATE:
4057 case T_TIME:
4058 buf = (char *) alloca (20);
4059 timebuf = timestamp ();
4060 if (hp->type == T_DATE)
4061 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4062 timebuf->tm_mday, timebuf->tm_year + 1900);
4063 else
4064 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4065 timebuf->tm_sec);
4066 break;
4068 case T_SPEC_DEFINED:
4069 buf = " 0 "; /* Assume symbol is not defined */
4070 ip = &instack[indepth];
4071 SKIP_WHITE_SPACE (ip->bufp);
4072 if (*ip->bufp == '(') {
4073 paren++;
4074 ip->bufp++; /* Skip over the paren */
4075 SKIP_WHITE_SPACE (ip->bufp);
4078 if (!is_idstart[*ip->bufp])
4079 goto oops;
4080 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4081 goto oops;
4082 if ((hp = lookup (ip->bufp, -1, -1))) {
4083 if (pcp_outfile && pcp_inside_if
4084 && (hp->type == T_CONST
4085 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4086 /* Output a precondition for this macro use. */
4087 fprintf (pcp_outfile, "#define %s\n", hp->name);
4088 buf = " 1 ";
4090 else
4091 if (pcp_outfile && pcp_inside_if) {
4092 /* Output a precondition for this macro use */
4093 U_CHAR *cp = ip->bufp;
4094 fprintf (pcp_outfile, "#undef ");
4095 while (is_idchar[*cp]) /* Ick! */
4096 fputc (*cp++, pcp_outfile);
4097 putc ('\n', pcp_outfile);
4099 while (is_idchar[*ip->bufp])
4100 ++ip->bufp;
4101 SKIP_WHITE_SPACE (ip->bufp);
4102 if (paren) {
4103 if (*ip->bufp != ')')
4104 goto oops;
4105 ++ip->bufp;
4107 break;
4109 oops:
4111 error ("`defined' without an identifier");
4112 break;
4114 default:
4115 error ("cccp error: invalid special hash type"); /* time for gdb */
4116 abort ();
4118 len = strlen (buf);
4119 check_expand (op, len);
4120 bcopy (buf, (char *) op->bufp, len);
4121 op->bufp += len;
4123 return;
4127 /* Routines to handle #directives */
4129 /* Handle #include and #import.
4130 This function expects to see "fname" or <fname> on the input. */
4132 static int
4133 do_include (buf, limit, op, keyword)
4134 U_CHAR *buf, *limit;
4135 FILE_BUF *op;
4136 struct directive *keyword;
4138 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4139 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4140 static int import_warning = 0;
4141 char *fname; /* Dynamically allocated fname buffer */
4142 char *pcftry;
4143 char *pcfname;
4144 char *fbeg, *fend; /* Beginning and end of fname */
4145 U_CHAR *fin;
4147 struct file_name_list *search_start = include; /* Chain of dirs to search */
4148 struct file_name_list *dsp; /* First in chain, if #include "..." */
4149 struct file_name_list *searchptr = 0;
4150 size_t flen;
4152 int f = -3; /* file number */
4153 struct include_file *inc = 0;
4155 int retried = 0; /* Have already tried macro
4156 expanding the include line*/
4157 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4158 #ifdef VMS
4159 int vaxc_include = 0; /* 1 for token without punctuation */
4160 #endif
4161 int pcf = -1;
4162 char *pcfbuf;
4163 char *pcfbuflimit;
4164 int pcfnum;
4166 if (pedantic && !instack[indepth].system_header_p)
4168 if (importing)
4169 pedwarn ("ANSI C does not allow `#import'");
4170 if (skip_dirs)
4171 pedwarn ("ANSI C does not allow `#include_next'");
4174 if (importing && warn_import && !inhibit_warnings
4175 && !instack[indepth].system_header_p && !import_warning) {
4176 import_warning = 1;
4177 warning ("using `#import' is not recommended");
4178 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4179 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4180 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4181 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4182 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4183 fprintf (stderr, " ... <real contents of file> ...\n");
4184 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4185 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4186 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4187 fprintf (stderr, "when it is equipped with such a conditional.\n");
4190 get_filename:
4192 fin = buf;
4193 SKIP_WHITE_SPACE (fin);
4194 /* Discard trailing whitespace so we can easily see
4195 if we have parsed all the significant chars we were given. */
4196 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4197 fbeg = fend = (char *) alloca (limit - fin);
4199 switch (*fin++) {
4200 case '\"':
4202 FILE_BUF *fp;
4203 /* Copy the operand text, concatenating the strings. */
4205 while (fin != limit) {
4206 while (fin != limit && *fin != '\"')
4207 *fend++ = *fin++;
4208 fin++;
4209 if (fin == limit)
4210 break;
4211 /* If not at the end, there had better be another string. */
4212 /* Skip just horiz space, and don't go past limit. */
4213 while (fin != limit && is_hor_space[*fin]) fin++;
4214 if (fin != limit && *fin == '\"')
4215 fin++;
4216 else
4217 goto fail;
4221 /* We have "filename". Figure out directory this source
4222 file is coming from and put it on the front of the list. */
4224 /* If -I- was specified, don't search current dir, only spec'd ones. */
4225 if (ignore_srcdir) break;
4227 for (fp = &instack[indepth]; fp >= instack; fp--)
4229 int n;
4230 char *nam;
4232 if ((nam = fp->nominal_fname) != NULL) {
4233 /* Found a named file. Figure out dir of the file,
4234 and put it in front of the search list. */
4235 dsp = ((struct file_name_list *)
4236 alloca (sizeof (struct file_name_list) + strlen (nam)));
4237 strcpy (dsp->fname, nam);
4238 simplify_filename (dsp->fname);
4239 nam = base_name (dsp->fname);
4240 *nam = 0;
4241 /* But for efficiency's sake, do not insert the dir
4242 if it matches the search list's first dir. */
4243 dsp->next = search_start;
4244 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4245 search_start = dsp;
4246 n = nam - dsp->fname;
4247 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4248 max_include_len = n + INCLUDE_LEN_FUDGE;
4250 dsp[0].got_name_map = 0;
4251 break;
4254 break;
4257 case '<':
4258 while (fin != limit && *fin != '>')
4259 *fend++ = *fin++;
4260 if (*fin == '>' && fin + 1 == limit) {
4261 angle_brackets = 1;
4262 /* If -I-, start with the first -I dir after the -I-. */
4263 search_start = first_bracket_include;
4264 break;
4266 goto fail;
4268 default:
4269 #ifdef VMS
4271 * Support '#include xyz' like VAX-C to allow for easy use of all the
4272 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4273 * code from case '<' is repeated here) and generates a warning.
4274 * (Note: macro expansion of `xyz' takes precedence.)
4276 if (retried && isalpha(*(U_CHAR *) (--fbeg))) {
4277 while (fin != limit && (!isspace(*fin)))
4278 *fend++ = *fin++;
4279 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4280 vaxc_include = 1;
4281 if (fin == limit) {
4282 angle_brackets = 1;
4283 /* If -I-, start with the first -I dir after the -I-. */
4284 search_start = first_bracket_include;
4285 break;
4288 #endif
4290 fail:
4291 if (retried) {
4292 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4293 return 0;
4294 } else {
4295 /* Expand buffer and then remove any newline markers.
4296 We can't just tell expand_to_temp_buffer to omit the markers,
4297 since it would put extra spaces in include file names. */
4298 FILE_BUF trybuf;
4299 U_CHAR *src;
4300 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4301 src = trybuf.buf;
4302 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4303 limit = buf;
4304 while (src != trybuf.bufp) {
4305 switch ((*limit++ = *src++)) {
4306 case '\n':
4307 limit--;
4308 src++;
4309 break;
4311 case '\'':
4312 case '\"':
4314 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4315 NULL_PTR, NULL_PTR, NULL_PTR);
4316 while (src != src1)
4317 *limit++ = *src++;
4319 break;
4322 *limit = 0;
4323 free (trybuf.buf);
4324 retried++;
4325 goto get_filename;
4329 /* For #include_next, skip in the search path
4330 past the dir in which the containing file was found. */
4331 if (skip_dirs) {
4332 FILE_BUF *fp;
4333 for (fp = &instack[indepth]; fp >= instack; fp--)
4334 if (fp->fname != NULL) {
4335 /* fp->dir is null if the containing file was specified
4336 with an absolute file name. In that case, don't skip anything. */
4337 if (fp->dir)
4338 search_start = fp->dir->next;
4339 break;
4343 *fend = 0;
4344 flen = simplify_filename (fbeg);
4346 if (flen == 0)
4348 error ("empty file name in `#%s'", keyword->name);
4349 return 0;
4352 /* Allocate this permanently, because it gets stored in the definitions
4353 of macros. */
4354 fname = xmalloc (max_include_len + flen + 1);
4355 /* + 1 above for terminating null. */
4357 system_include_depth += angle_brackets;
4359 /* If specified file name is absolute, just open it. */
4361 if (absolute_filename (fbeg)) {
4362 strcpy (fname, fbeg);
4363 f = open_include_file (fname, NULL_PTR, importing, &inc);
4364 } else {
4366 struct bypass_dir {
4367 struct bypass_dir *next;
4368 char *fname;
4369 struct file_name_list *searchptr;
4370 } **bypass_slot = 0;
4372 /* Search directory path, trying to open the file.
4373 Copy each filename tried into FNAME. */
4375 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4377 if (searchptr == first_bracket_include) {
4378 /* Go to bypass directory if we know we've seen this file before. */
4379 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4380 struct bypass_dir *p;
4381 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4382 INCLUDE_HASHSIZE)];
4383 for (p = *bypass_slot; p; p = p->next)
4384 if (!strcmp (fbeg, p->fname)) {
4385 searchptr = p->searchptr;
4386 bypass_slot = 0;
4387 break;
4391 strcpy (fname, searchptr->fname);
4392 strcat (fname, fbeg);
4393 #ifdef VMS
4394 /* Change this 1/2 Unix 1/2 VMS file specification into a
4395 full VMS file specification */
4396 if (searchptr->fname[0]) {
4397 /* Fix up the filename */
4398 hack_vms_include_specification (fname, vaxc_include);
4399 } else {
4400 /* This is a normal VMS filespec, so use it unchanged. */
4401 strcpy (fname, fbeg);
4402 /* if it's '#include filename', add the missing .h */
4403 if (vaxc_include && index(fname,'.')==NULL) {
4404 strcat (fname, ".h");
4407 #endif /* VMS */
4408 f = open_include_file (fname, searchptr, importing, &inc);
4409 if (f != -1) {
4410 if (bypass_slot && searchptr != first_bracket_include) {
4411 /* This is the first time we found this include file,
4412 and we found it after first_bracket_include.
4413 Record its location so that we can bypass to here next time. */
4414 struct bypass_dir *p
4415 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4416 p->next = *bypass_slot;
4417 p->fname = fname + strlen (searchptr->fname);
4418 p->searchptr = searchptr;
4419 *bypass_slot = p;
4421 break;
4423 #ifdef VMS
4424 /* Our VMS hacks can produce invalid filespecs, so don't worry
4425 about errors other than EACCES. */
4426 if (errno == EACCES)
4427 break;
4428 #else
4429 if (errno != ENOENT && errno != ENOTDIR)
4430 break;
4431 #endif
4436 if (f < 0) {
4438 if (f == -2) {
4439 /* The file was already included. */
4441 /* If generating dependencies and -MG was specified, we assume missing
4442 files are leaf files, living in the same directory as the source file
4443 or other similar place; these missing files may be generated from
4444 other files and may not exist yet (eg: y.tab.h). */
4445 } else if (print_deps_missing_files
4446 && (system_include_depth != 0) < print_deps)
4448 /* If it was requested as a system header file,
4449 then assume it belongs in the first place to look for such. */
4450 if (angle_brackets)
4452 if (search_start) {
4453 char *p = (char *) alloca (strlen (search_start->fname)
4454 + strlen (fbeg) + 1);
4455 strcpy (p, search_start->fname);
4456 strcat (p, fbeg);
4457 deps_output (p, ' ');
4460 else
4462 /* Otherwise, omit the directory, as if the file existed
4463 in the directory with the source. */
4464 deps_output (fbeg, ' ');
4467 /* If -M was specified, and this header file won't be added to the
4468 dependency list, then don't count this as an error, because we can
4469 still produce correct output. Otherwise, we can't produce correct
4470 output, because there may be dependencies we need inside the missing
4471 file, and we don't know what directory this missing file exists in. */
4472 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4473 warning ("No include path in which to find %s", fbeg);
4474 else if (f != -3)
4475 error_from_errno (fbeg);
4476 else
4477 error ("No include path in which to find %s", fbeg);
4479 } else {
4481 /* Actually process the file. */
4483 pcftry = (char *) alloca (strlen (fname) + 30);
4484 pcfbuf = 0;
4485 pcfnum = 0;
4487 if (!no_precomp)
4489 do {
4490 sprintf (pcftry, "%s%d", fname, pcfnum++);
4492 pcf = open (pcftry, O_RDONLY, 0666);
4493 if (pcf != -1)
4495 struct stat s;
4497 if (fstat (pcf, &s) != 0)
4498 pfatal_with_name (pcftry);
4499 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4500 || inc->st.st_dev != s.st_dev)
4502 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4503 /* Don't need it any more. */
4504 close (pcf);
4506 else
4508 /* Don't need it at all. */
4509 close (pcf);
4510 break;
4513 } while (pcf != -1 && !pcfbuf);
4516 /* Actually process the file */
4517 if (pcfbuf) {
4518 pcfname = xmalloc (strlen (pcftry) + 1);
4519 strcpy (pcfname, pcftry);
4520 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4521 (U_CHAR *) fname, op);
4523 else
4524 finclude (f, inc, op, is_system_include (fname), searchptr);
4527 system_include_depth -= angle_brackets;
4529 return 0;
4532 /* Return nonzero if the given FILENAME is an absolute pathname which
4533 designates a file within one of the known "system" include file
4534 directories. We assume here that if the given FILENAME looks like
4535 it is the name of a file which resides either directly in a "system"
4536 include file directory, or within any subdirectory thereof, then the
4537 given file must be a "system" include file. This function tells us
4538 if we should suppress pedantic errors/warnings for the given FILENAME.
4540 The value is 2 if the file is a C-language system header file
4541 for which C++ should (on most systems) assume `extern "C"'. */
4543 static int
4544 is_system_include (filename)
4545 register char *filename;
4547 struct file_name_list *searchptr;
4549 for (searchptr = first_system_include; searchptr;
4550 searchptr = searchptr->next)
4551 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4552 return searchptr->c_system_include_path + 1;
4553 return 0;
4556 /* Yield the non-directory suffix of a file name. */
4558 static char *
4559 base_name (fname)
4560 char *fname;
4562 char *s = fname;
4563 char *p;
4564 #if defined (__MSDOS__) || defined (_WIN32)
4565 if (isalpha (s[0]) && s[1] == ':') s += 2;
4566 #endif
4567 #ifdef VMS
4568 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4569 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4570 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4571 if (s != fname)
4572 return s;
4573 #endif
4574 if ((p = rindex (s, '/'))) s = p + 1;
4575 #ifdef DIR_SEPARATOR
4576 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4577 #endif
4578 return s;
4581 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4583 static int
4584 absolute_filename (filename)
4585 char *filename;
4587 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4588 if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4589 #endif
4590 #if defined (__CYGWIN32__)
4591 /* At present, any path that begins with a drive spec is absolute. */
4592 if (isalpha (filename[0]) && filename[1] == ':') return 1;
4593 #endif
4594 if (filename[0] == '/') return 1;
4595 #ifdef DIR_SEPARATOR
4596 if (filename[0] == DIR_SEPARATOR) return 1;
4597 #endif
4598 return 0;
4601 /* Remove unnecessary characters from FILENAME in place,
4602 to avoid unnecessary filename aliasing.
4603 Return the length of the resulting string.
4605 Do only the simplifications allowed by Posix.
4606 It is OK to miss simplifications on non-Posix hosts,
4607 since this merely leads to suboptimal results. */
4609 static size_t
4610 simplify_filename (filename)
4611 char *filename;
4613 register char *from = filename;
4614 register char *to = filename;
4615 char *to0;
4617 /* Remove redundant initial /s. */
4618 if (*from == '/') {
4619 *to++ = '/';
4620 if (*++from == '/') {
4621 if (*++from == '/') {
4622 /* 3 or more initial /s are equivalent to 1 /. */
4623 while (*++from == '/')
4624 continue;
4625 } else {
4626 /* On some hosts // differs from /; Posix allows this. */
4627 static int slashslash_vs_slash;
4628 if (slashslash_vs_slash == 0) {
4629 struct stat s1, s2;
4630 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4631 && INO_T_EQ (s1.st_ino, s2.st_ino)
4632 && s1.st_dev == s2.st_dev)
4633 ? 1 : -1);
4635 if (slashslash_vs_slash < 0)
4636 *to++ = '/';
4640 to0 = to;
4642 for (;;) {
4643 if (from[0] == '.' && from[1] == '/')
4644 from += 2;
4645 else {
4646 /* Copy this component and trailing /, if any. */
4647 while ((*to++ = *from++) != '/') {
4648 if (!to[-1]) {
4649 /* Trim . component at end of nonempty name. */
4650 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4652 /* Trim unnecessary trailing /s. */
4653 while (to0 < --to && to[-1] == '/')
4654 continue;
4656 *to = 0;
4657 return to - filename;
4662 /* Skip /s after a /. */
4663 while (*from == '/')
4664 from++;
4668 /* The file_name_map structure holds a mapping of file names for a
4669 particular directory. This mapping is read from the file named
4670 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4671 map filenames on a file system with severe filename restrictions,
4672 such as DOS. The format of the file name map file is just a series
4673 of lines with two tokens on each line. The first token is the name
4674 to map, and the second token is the actual name to use. */
4676 struct file_name_map
4678 struct file_name_map *map_next;
4679 char *map_from;
4680 char *map_to;
4683 #define FILE_NAME_MAP_FILE "header.gcc"
4685 /* Read a space delimited string of unlimited length from a stdio
4686 file. */
4688 static char *
4689 read_filename_string (ch, f)
4690 int ch;
4691 FILE *f;
4693 char *alloc, *set;
4694 int len;
4696 len = 20;
4697 set = alloc = xmalloc (len + 1);
4698 if (! is_space[ch])
4700 *set++ = ch;
4701 while ((ch = getc (f)) != EOF && ! is_space[ch])
4703 if (set - alloc == len)
4705 len *= 2;
4706 alloc = xrealloc (alloc, len + 1);
4707 set = alloc + len / 2;
4709 *set++ = ch;
4712 *set = '\0';
4713 ungetc (ch, f);
4714 return alloc;
4717 /* Read the file name map file for DIRNAME.
4718 If DIRNAME is empty, read the map file for the working directory;
4719 otherwise DIRNAME must end in '/'. */
4721 static struct file_name_map *
4722 read_name_map (dirname)
4723 char *dirname;
4725 /* This structure holds a linked list of file name maps, one per
4726 directory. */
4727 struct file_name_map_list
4729 struct file_name_map_list *map_list_next;
4730 char *map_list_name;
4731 struct file_name_map *map_list_map;
4733 static struct file_name_map_list *map_list;
4734 register struct file_name_map_list *map_list_ptr;
4735 char *name;
4736 FILE *f;
4737 size_t dirlen;
4739 for (map_list_ptr = map_list; map_list_ptr;
4740 map_list_ptr = map_list_ptr->map_list_next)
4741 if (! strcmp (map_list_ptr->map_list_name, dirname))
4742 return map_list_ptr->map_list_map;
4744 map_list_ptr = ((struct file_name_map_list *)
4745 xmalloc (sizeof (struct file_name_map_list)));
4746 map_list_ptr->map_list_name = savestring (dirname);
4747 map_list_ptr->map_list_map = NULL;
4749 dirlen = strlen (dirname);
4750 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4751 strcpy (name, dirname);
4752 strcat (name, FILE_NAME_MAP_FILE);
4753 f = fopen (name, "r");
4754 if (!f)
4755 map_list_ptr->map_list_map = NULL;
4756 else
4758 int ch;
4760 while ((ch = getc (f)) != EOF)
4762 char *from, *to;
4763 struct file_name_map *ptr;
4764 size_t tolen;
4766 if (is_space[ch])
4767 continue;
4768 from = read_filename_string (ch, f);
4769 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4771 to = read_filename_string (ch, f);
4773 simplify_filename (from);
4774 tolen = simplify_filename (to);
4776 ptr = ((struct file_name_map *)
4777 xmalloc (sizeof (struct file_name_map)));
4778 ptr->map_from = from;
4780 /* Make the real filename absolute. */
4781 if (absolute_filename (to))
4782 ptr->map_to = to;
4783 else
4785 ptr->map_to = xmalloc (dirlen + tolen + 1);
4786 strcpy (ptr->map_to, dirname);
4787 strcat (ptr->map_to, to);
4788 free (to);
4791 ptr->map_next = map_list_ptr->map_list_map;
4792 map_list_ptr->map_list_map = ptr;
4794 while ((ch = getc (f)) != '\n')
4795 if (ch == EOF)
4796 break;
4798 fclose (f);
4801 map_list_ptr->map_list_next = map_list;
4802 map_list = map_list_ptr;
4804 return map_list_ptr->map_list_map;
4807 /* Try to open include file FILENAME. SEARCHPTR is the directory
4808 being tried from the include file search path.
4809 IMPORTING is "" if we are importing, null otherwise.
4810 Return -2 if found, either a matching name or a matching inode.
4811 Otherwise, open the file and return a file descriptor if successful
4812 or -1 if unsuccessful.
4813 Unless unsuccessful, put a descriptor of the included file into *PINC.
4814 This function maps filenames on file systems based on information read by
4815 read_name_map. */
4817 static int
4818 open_include_file (filename, searchptr, importing, pinc)
4819 char *filename;
4820 struct file_name_list *searchptr;
4821 U_CHAR *importing;
4822 struct include_file **pinc;
4824 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
4825 int fd = -2;
4827 /* Look up FNAME in include_hashtab. */
4828 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4829 strlen (fname),
4830 INCLUDE_HASHSIZE)];
4831 struct include_file *inc, *head = *phead;
4832 for (inc = head; inc; inc = inc->next)
4833 if (!strcmp (fname, inc->fname))
4834 break;
4836 if (!inc
4837 || ! inc->control_macro
4838 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4840 fd = open (fname, O_RDONLY, 0);
4842 if (fd < 0)
4843 return fd;
4845 if (!inc) {
4846 /* FNAME was not in include_hashtab; insert a new entry. */
4847 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4848 inc->next = head;
4849 inc->fname = fname;
4850 inc->control_macro = 0;
4851 inc->deps_output = 0;
4852 if (fstat (fd, &inc->st) != 0)
4853 pfatal_with_name (fname);
4854 *phead = inc;
4856 /* Look for another file with the same inode and device. */
4857 if (lookup_ino_include (inc)
4858 && inc->control_macro
4859 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4860 close (fd);
4861 fd = -2;
4865 /* For -M, add this file to the dependencies. */
4866 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4867 inc->deps_output = 1;
4868 deps_output (fname, ' ');
4871 /* Handle -H option. */
4872 if (print_include_names)
4873 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4876 if (importing)
4877 inc->control_macro = importing;
4879 *pinc = inc;
4880 return fd;
4883 /* Return the remapped name of the the include file FILENAME.
4884 SEARCHPTR is the directory being tried from the include file path. */
4886 static char *
4887 remap_include_file (filename, searchptr)
4888 char *filename;
4889 struct file_name_list *searchptr;
4891 register struct file_name_map *map;
4892 register char *from;
4894 if (searchptr)
4896 if (! searchptr->got_name_map)
4898 searchptr->name_map = read_name_map (searchptr->fname);
4899 searchptr->got_name_map = 1;
4902 /* Check the mapping for the directory we are using. */
4903 from = filename + strlen (searchptr->fname);
4904 for (map = searchptr->name_map; map; map = map->map_next)
4905 if (! strcmp (map->map_from, from))
4906 return map->map_to;
4909 from = base_name (filename);
4911 if (from != filename || !searchptr)
4913 /* Try to find a mapping file for the particular directory we are
4914 looking in. Thus #include <sys/types.h> will look up sys/types.h
4915 in /usr/include/header.gcc and look up types.h in
4916 /usr/include/sys/header.gcc. */
4918 char *dir = (char *) alloca (from - filename + 1);
4919 bcopy (filename, dir, from - filename);
4920 dir[from - filename] = '\0';
4922 for (map = read_name_map (dir); map; map = map->map_next)
4923 if (! strcmp (map->map_from, from))
4924 return map->map_to;
4927 return filename;
4930 /* Insert INC into the include file table, hashed by device and inode number.
4931 If a file with different name but same dev+ino was already in the table,
4932 return 1 and set INC's control macro to the already-known macro. */
4934 static int
4935 lookup_ino_include (inc)
4936 struct include_file *inc;
4938 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
4939 % INCLUDE_HASHSIZE);
4940 struct include_file *i = include_ino_hashtab[hash];
4941 inc->next_ino = i;
4942 include_ino_hashtab[hash] = inc;
4944 for (; i; i = i->next_ino)
4945 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
4946 && inc->st.st_dev == i->st.st_dev) {
4947 inc->control_macro = i->control_macro;
4948 return 1;
4951 return 0;
4954 /* Process file descriptor F, which corresponds to include file INC,
4955 with output to OP.
4956 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4957 "system" include directories (as decided by the `is_system_include'
4958 function above).
4959 DIRPTR is the link in the dir path through which this file was found,
4960 or 0 if the file name was absolute. */
4962 static void
4963 finclude (f, inc, op, system_header_p, dirptr)
4964 int f;
4965 struct include_file *inc;
4966 FILE_BUF *op;
4967 int system_header_p;
4968 struct file_name_list *dirptr;
4970 char *fname = inc->fname;
4971 int i;
4972 FILE_BUF *fp; /* For input stack frame */
4973 int missing_newline = 0;
4975 CHECK_DEPTH (return;);
4977 fp = &instack[indepth + 1];
4978 bzero ((char *) fp, sizeof (FILE_BUF));
4979 fp->nominal_fname = fp->fname = fname;
4980 fp->inc = inc;
4981 fp->length = 0;
4982 fp->lineno = 1;
4983 fp->if_stack = if_stack;
4984 fp->system_header_p = system_header_p;
4985 fp->dir = dirptr;
4987 if (S_ISREG (inc->st.st_mode)) {
4988 size_t s = (size_t) inc->st.st_size;
4989 if (s != inc->st.st_size || s + 2 < s)
4990 memory_full ();
4991 fp->buf = (U_CHAR *) xmalloc (s + 2);
4992 fp->bufp = fp->buf;
4994 /* Read the file contents, knowing that s is an upper bound
4995 on the number of bytes we can read. */
4996 fp->length = safe_read (f, (char *) fp->buf, s);
4997 if (fp->length < 0) goto nope;
4999 else if (S_ISDIR (inc->st.st_mode)) {
5000 error ("directory `%s' specified in #include", fname);
5001 close (f);
5002 return;
5003 } else {
5004 /* Cannot count its file size before reading.
5005 First read the entire file into heap and
5006 copy them into buffer on stack. */
5008 int bsize = 2000;
5009 int st_size = 0;
5011 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5013 for (;;) {
5014 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5015 if (i < 0)
5016 goto nope; /* error! */
5017 st_size += i;
5018 if (st_size != bsize)
5019 break; /* End of file */
5020 bsize *= 2;
5021 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5023 fp->bufp = fp->buf;
5024 fp->length = st_size;
5027 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5028 /* Backslash-newline at end is not good enough. */
5029 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5030 fp->buf[fp->length++] = '\n';
5031 missing_newline = 1;
5033 fp->buf[fp->length] = '\0';
5035 /* Close descriptor now, so nesting does not use lots of descriptors. */
5036 close (f);
5038 /* Must do this before calling trigraph_pcp, so that the correct file name
5039 will be printed in warning messages. */
5041 indepth++;
5042 input_file_stack_tick++;
5044 if (!no_trigraphs)
5045 trigraph_pcp (fp);
5047 output_line_directive (fp, op, 0, enter_file);
5048 rescan (op, 0);
5050 if (missing_newline)
5051 fp->lineno--;
5053 if (pedantic && missing_newline)
5054 pedwarn ("file does not end in newline");
5056 indepth--;
5057 input_file_stack_tick++;
5058 output_line_directive (&instack[indepth], op, 0, leave_file);
5059 free (fp->buf);
5060 return;
5062 nope:
5064 perror_with_name (fname);
5065 close (f);
5066 free (fp->buf);
5069 /* Record that inclusion of the include file INC
5070 should be controlled by the macro named MACRO_NAME.
5071 This means that trying to include the file again
5072 will do something if that macro is defined. */
5074 static void
5075 record_control_macro (inc, macro_name)
5076 struct include_file *inc;
5077 U_CHAR *macro_name;
5079 if (!inc->control_macro || inc->control_macro[0])
5080 inc->control_macro = macro_name;
5083 /* Load the specified precompiled header into core, and verify its
5084 preconditions. PCF indicates the file descriptor to read, which must
5085 be a regular file. *ST is its file status.
5086 FNAME indicates the file name of the original header.
5087 *LIMIT will be set to an address one past the end of the file.
5088 If the preconditions of the file are not satisfied, the buffer is
5089 freed and we return 0. If the preconditions are satisfied, return
5090 the address of the buffer following the preconditions. The buffer, in
5091 this case, should never be freed because various pieces of it will
5092 be referred to until all precompiled strings are output at the end of
5093 the run. */
5095 static char *
5096 check_precompiled (pcf, st, fname, limit)
5097 int pcf;
5098 struct stat *st;
5099 char *fname;
5100 char **limit;
5102 int length = 0;
5103 char *buf;
5104 char *cp;
5106 if (pcp_outfile)
5107 return 0;
5109 if (S_ISREG (st->st_mode))
5111 size_t s = (size_t) st->st_size;
5112 if (s != st->st_size || s + 2 < s)
5113 memory_full ();
5114 buf = xmalloc (s + 2);
5115 length = safe_read (pcf, buf, s);
5116 if (length < 0)
5117 goto nope;
5119 else
5120 abort ();
5122 if (length > 0 && buf[length-1] != '\n')
5123 buf[length++] = '\n';
5124 buf[length] = '\0';
5126 *limit = buf + length;
5128 /* File is in core. Check the preconditions. */
5129 if (!check_preconditions (buf))
5130 goto nope;
5131 for (cp = buf; *cp; cp++)
5133 #ifdef DEBUG_PCP
5134 fprintf (stderr, "Using preinclude %s\n", fname);
5135 #endif
5136 return cp + 1;
5138 nope:
5139 #ifdef DEBUG_PCP
5140 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5141 #endif
5142 free (buf);
5143 return 0;
5146 /* PREC (null terminated) points to the preconditions of a
5147 precompiled header. These are a series of #define and #undef
5148 lines which must match the current contents of the hash
5149 table. */
5151 static int
5152 check_preconditions (prec)
5153 char *prec;
5155 MACRODEF mdef;
5156 char *lineend;
5158 while (*prec) {
5159 lineend = index (prec, '\n');
5161 if (*prec++ != '#') {
5162 error ("Bad format encountered while reading precompiled file");
5163 return 0;
5165 if (!strncmp (prec, "define", 6)) {
5166 HASHNODE *hp;
5168 prec += 6;
5169 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5171 if (mdef.defn == 0)
5172 abort ();
5174 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5175 || (hp->type != T_MACRO && hp->type != T_CONST)
5176 || (hp->type == T_MACRO
5177 && !compare_defs (mdef.defn, hp->value.defn)
5178 && (mdef.defn->length != 2
5179 || mdef.defn->expansion[0] != '\n'
5180 || mdef.defn->expansion[1] != ' ')))
5181 return 0;
5182 } else if (!strncmp (prec, "undef", 5)) {
5183 char *name;
5184 int len;
5186 prec += 5;
5187 while (is_hor_space[(U_CHAR) *prec])
5188 prec++;
5189 name = prec;
5190 while (is_idchar[(U_CHAR) *prec])
5191 prec++;
5192 len = prec - name;
5194 if (lookup ((U_CHAR *) name, len, -1))
5195 return 0;
5196 } else {
5197 error ("Bad format encountered while reading precompiled file");
5198 return 0;
5200 prec = lineend + 1;
5202 /* They all passed successfully */
5203 return 1;
5206 /* Process the main body of a precompiled file. BUF points to the
5207 string section of the file, following the preconditions. LIMIT is one
5208 character past the end. NAME is the name of the file being read
5209 in. OP is the main output buffer. */
5211 static void
5212 pcfinclude (buf, limit, name, op)
5213 U_CHAR *buf, *limit, *name;
5214 FILE_BUF *op;
5216 FILE_BUF tmpbuf;
5217 int nstrings;
5218 U_CHAR *cp = buf;
5220 /* First in the file comes 4 bytes indicating the number of strings, */
5221 /* in network byte order. (MSB first). */
5222 nstrings = *cp++;
5223 nstrings = (nstrings << 8) | *cp++;
5224 nstrings = (nstrings << 8) | *cp++;
5225 nstrings = (nstrings << 8) | *cp++;
5227 /* Looping over each string... */
5228 while (nstrings--) {
5229 U_CHAR *string_start;
5230 U_CHAR *endofthiskey;
5231 STRINGDEF *str;
5232 int nkeys;
5234 /* Each string starts with a STRINGDEF structure (str), followed */
5235 /* by the text of the string (string_start) */
5237 /* First skip to a longword boundary */
5238 /* ??? Why a 4-byte boundary? On all machines? */
5239 /* NOTE: This works correctly even if size_t
5240 is narrower than a pointer.
5241 Do not try risky measures here to get another type to use!
5242 Do not include stddef.h--it will fail! */
5243 if ((size_t) cp & 3)
5244 cp += 4 - ((size_t) cp & 3);
5246 /* Now get the string. */
5247 str = (STRINGDEF *) (GENERIC_PTR) cp;
5248 string_start = cp += sizeof (STRINGDEF);
5250 for (; *cp; cp++) /* skip the string */
5253 /* We need to macro expand the string here to ensure that the
5254 proper definition environment is in place. If it were only
5255 expanded when we find out it is needed, macros necessary for
5256 its proper expansion might have had their definitions changed. */
5257 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5258 /* Lineno is already set in the precompiled file */
5259 str->contents = tmpbuf.buf;
5260 str->len = tmpbuf.length;
5261 str->writeflag = 0;
5262 str->filename = name;
5263 str->output_mark = outbuf.bufp - outbuf.buf;
5265 str->chain = 0;
5266 *stringlist_tailp = str;
5267 stringlist_tailp = &str->chain;
5269 /* Next comes a fourbyte number indicating the number of keys
5270 for this string. */
5271 nkeys = *cp++;
5272 nkeys = (nkeys << 8) | *cp++;
5273 nkeys = (nkeys << 8) | *cp++;
5274 nkeys = (nkeys << 8) | *cp++;
5276 /* If this number is -1, then the string is mandatory. */
5277 if (nkeys == -1)
5278 str->writeflag = 1;
5279 else
5280 /* Otherwise, for each key, */
5281 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5282 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5283 HASHNODE *hp;
5285 /* It starts with a KEYDEF structure */
5286 cp += sizeof (KEYDEF);
5288 /* Find the end of the key. At the end of this for loop we
5289 advance CP to the start of the next key using this variable. */
5290 endofthiskey = cp + strlen ((char *) cp);
5291 kp->str = str;
5293 /* Expand the key, and enter it into the hash table. */
5294 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5295 tmpbuf.bufp = tmpbuf.buf;
5297 while (is_hor_space[*tmpbuf.bufp])
5298 tmpbuf.bufp++;
5299 if (!is_idstart[*tmpbuf.bufp]
5300 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5301 str->writeflag = 1;
5302 continue;
5305 hp = lookup (tmpbuf.bufp, -1, -1);
5306 if (hp == NULL) {
5307 kp->chain = 0;
5308 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5310 else if (hp->type == T_PCSTRING) {
5311 kp->chain = hp->value.keydef;
5312 hp->value.keydef = kp;
5314 else
5315 str->writeflag = 1;
5318 /* This output_line_directive serves to switch us back to the current
5319 input file in case some of these strings get output (which will
5320 result in line directives for the header file being output). */
5321 output_line_directive (&instack[indepth], op, 0, enter_file);
5324 /* Called from rescan when it hits a key for strings. Mark them all
5325 used and clean up. */
5327 static void
5328 pcstring_used (hp)
5329 HASHNODE *hp;
5331 KEYDEF *kp;
5333 for (kp = hp->value.keydef; kp; kp = kp->chain)
5334 kp->str->writeflag = 1;
5335 delete_macro (hp);
5338 /* Write the output, interspersing precompiled strings in their
5339 appropriate places. */
5341 static void
5342 write_output ()
5344 STRINGDEF *next_string;
5345 U_CHAR *cur_buf_loc;
5346 int line_directive_len = 80;
5347 char *line_directive = xmalloc (line_directive_len);
5348 int len;
5350 /* In each run through the loop, either cur_buf_loc ==
5351 next_string_loc, in which case we print a series of strings, or
5352 it is less than next_string_loc, in which case we write some of
5353 the buffer. */
5354 cur_buf_loc = outbuf.buf;
5355 next_string = stringlist;
5357 while (cur_buf_loc < outbuf.bufp || next_string) {
5358 if (next_string
5359 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5360 if (next_string->writeflag) {
5361 len = 4 * strlen ((char *) next_string->filename) + 32;
5362 while (len > line_directive_len)
5363 line_directive = xrealloc (line_directive,
5364 line_directive_len *= 2);
5365 sprintf (line_directive, "\n# %d ", next_string->lineno);
5366 strcpy (quote_string (line_directive + strlen (line_directive),
5367 (char *) next_string->filename),
5368 "\n");
5369 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5370 safe_write (fileno (stdout),
5371 (char *) next_string->contents, next_string->len);
5373 next_string = next_string->chain;
5375 else {
5376 len = (next_string
5377 ? (next_string->output_mark
5378 - (cur_buf_loc - outbuf.buf))
5379 : outbuf.bufp - cur_buf_loc);
5381 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5382 cur_buf_loc += len;
5385 free (line_directive);
5388 /* Pass a directive through to the output file.
5389 BUF points to the contents of the directive, as a contiguous string.
5390 LIMIT points to the first character past the end of the directive.
5391 KEYWORD is the keyword-table entry for the directive. */
5393 static void
5394 pass_thru_directive (buf, limit, op, keyword)
5395 U_CHAR *buf, *limit;
5396 FILE_BUF *op;
5397 struct directive *keyword;
5399 register unsigned keyword_length = keyword->length;
5401 check_expand (op, 1 + keyword_length + (limit - buf));
5402 *op->bufp++ = '#';
5403 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5404 op->bufp += keyword_length;
5405 if (limit != buf && buf[0] != ' ')
5406 *op->bufp++ = ' ';
5407 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5408 op->bufp += (limit - buf);
5409 #if 0
5410 *op->bufp++ = '\n';
5411 /* Count the line we have just made in the output,
5412 to get in sync properly. */
5413 op->lineno++;
5414 #endif
5417 /* The arglist structure is built by do_define to tell
5418 collect_definition where the argument names begin. That
5419 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5420 would contain pointers to the strings x, y, and z.
5421 Collect_definition would then build a DEFINITION node,
5422 with reflist nodes pointing to the places x, y, and z had
5423 appeared. So the arglist is just convenience data passed
5424 between these two routines. It is not kept around after
5425 the current #define has been processed and entered into the
5426 hash table. */
5428 struct arglist {
5429 struct arglist *next;
5430 U_CHAR *name;
5431 int length;
5432 int argno;
5433 char rest_args;
5436 /* Create a DEFINITION node from a #define directive. Arguments are
5437 as for do_define. */
5439 static MACRODEF
5440 create_definition (buf, limit, op)
5441 U_CHAR *buf, *limit;
5442 FILE_BUF *op;
5444 U_CHAR *bp; /* temp ptr into input buffer */
5445 U_CHAR *symname; /* remember where symbol name starts */
5446 int sym_length; /* and how long it is */
5447 int line = instack[indepth].lineno;
5448 char *file = instack[indepth].nominal_fname;
5449 int rest_args = 0;
5451 DEFINITION *defn;
5452 int arglengths = 0; /* Accumulate lengths of arg names
5453 plus number of args. */
5454 MACRODEF mdef;
5456 bp = buf;
5458 while (is_hor_space[*bp])
5459 bp++;
5461 symname = bp; /* remember where it starts */
5462 sym_length = check_macro_name (bp, "macro");
5463 bp += sym_length;
5465 /* Lossage will occur if identifiers or control keywords are broken
5466 across lines using backslash. This is not the right place to take
5467 care of that. */
5469 if (*bp == '(') {
5470 struct arglist *arg_ptrs = NULL;
5471 int argno = 0;
5473 bp++; /* skip '(' */
5474 SKIP_WHITE_SPACE (bp);
5476 /* Loop over macro argument names. */
5477 while (*bp != ')') {
5478 struct arglist *temp;
5480 temp = (struct arglist *) alloca (sizeof (struct arglist));
5481 temp->name = bp;
5482 temp->next = arg_ptrs;
5483 temp->argno = argno++;
5484 temp->rest_args = 0;
5485 arg_ptrs = temp;
5487 if (rest_args)
5488 pedwarn ("another parameter follows `%s'",
5489 rest_extension);
5491 if (!is_idstart[*bp])
5492 pedwarn ("invalid character in macro parameter name");
5494 /* Find the end of the arg name. */
5495 while (is_idchar[*bp]) {
5496 bp++;
5497 /* do we have a "special" rest-args extension here? */
5498 if (limit - bp > REST_EXTENSION_LENGTH
5499 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5500 rest_args = 1;
5501 temp->rest_args = 1;
5502 break;
5505 temp->length = bp - temp->name;
5506 if (rest_args == 1)
5507 bp += REST_EXTENSION_LENGTH;
5508 arglengths += temp->length + 2;
5509 SKIP_WHITE_SPACE (bp);
5510 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5511 error ("badly punctuated parameter list in `#define'");
5512 goto nope;
5514 if (*bp == ',') {
5515 bp++;
5516 SKIP_WHITE_SPACE (bp);
5517 /* A comma at this point can only be followed by an identifier. */
5518 if (!is_idstart[*bp]) {
5519 error ("badly punctuated parameter list in `#define'");
5520 goto nope;
5523 if (bp >= limit) {
5524 error ("unterminated parameter list in `#define'");
5525 goto nope;
5528 struct arglist *otemp;
5530 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5531 if (temp->length == otemp->length
5532 && bcmp (temp->name, otemp->name, temp->length) == 0) {
5533 error ("duplicate argument name `%.*s' in `#define'",
5534 temp->length, temp->name);
5535 goto nope;
5540 ++bp; /* skip paren */
5541 SKIP_WHITE_SPACE (bp);
5542 /* now everything from bp before limit is the definition. */
5543 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5544 defn->rest_args = rest_args;
5546 /* Now set defn->args.argnames to the result of concatenating
5547 the argument names in reverse order
5548 with comma-space between them. */
5549 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5551 struct arglist *temp;
5552 int i = 0;
5553 for (temp = arg_ptrs; temp; temp = temp->next) {
5554 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5555 i += temp->length;
5556 if (temp->next != 0) {
5557 defn->args.argnames[i++] = ',';
5558 defn->args.argnames[i++] = ' ';
5561 defn->args.argnames[i] = 0;
5563 } else {
5564 /* Simple expansion or empty definition. */
5566 if (bp < limit)
5568 if (is_hor_space[*bp]) {
5569 bp++;
5570 SKIP_WHITE_SPACE (bp);
5571 } else if (sym_length) {
5572 switch (*bp) {
5573 case '!': case '"': case '#': case '%': case '&': case '\'':
5574 case ')': case '*': case '+': case ',': case '-': case '.':
5575 case '/': case ':': case ';': case '<': case '=': case '>':
5576 case '?': case '[': case '\\': case ']': case '^': case '{':
5577 case '|': case '}': case '~':
5578 warning ("missing white space after `#define %.*s'",
5579 sym_length, symname);
5580 break;
5582 default:
5583 pedwarn ("missing white space after `#define %.*s'",
5584 sym_length, symname);
5585 break;
5589 /* Now everything from bp before limit is the definition. */
5590 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5591 defn->args.argnames = (U_CHAR *) "";
5594 defn->line = line;
5595 defn->file = file;
5597 /* OP is null if this is a predefinition */
5598 defn->predefined = !op;
5599 mdef.defn = defn;
5600 mdef.symnam = symname;
5601 mdef.symlen = sym_length;
5603 return mdef;
5605 nope:
5606 mdef.defn = 0;
5607 return mdef;
5610 /* Process a #define directive.
5611 BUF points to the contents of the #define directive, as a contiguous string.
5612 LIMIT points to the first character past the end of the definition.
5613 KEYWORD is the keyword-table entry for #define. */
5615 static int
5616 do_define (buf, limit, op, keyword)
5617 U_CHAR *buf, *limit;
5618 FILE_BUF *op;
5619 struct directive *keyword;
5621 int hashcode;
5622 MACRODEF mdef;
5624 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5625 if (pcp_outfile && op)
5626 pass_thru_directive (buf, limit, op, keyword);
5628 mdef = create_definition (buf, limit, op);
5629 if (mdef.defn == 0)
5630 goto nope;
5632 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5635 HASHNODE *hp;
5636 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5637 int ok = 0;
5638 /* Redefining a precompiled key is ok. */
5639 if (hp->type == T_PCSTRING)
5640 ok = 1;
5641 /* Redefining a macro is ok if the definitions are the same. */
5642 else if (hp->type == T_MACRO)
5643 ok = ! compare_defs (mdef.defn, hp->value.defn);
5644 /* Redefining a constant is ok with -D. */
5645 else if (hp->type == T_CONST)
5646 ok = ! done_initializing;
5647 /* Print the warning if it's not ok. */
5648 if (!ok) {
5649 /* If we are passing through #define and #undef directives, do
5650 that for this re-definition now. */
5651 if (debug_output && op)
5652 pass_thru_directive (buf, limit, op, keyword);
5654 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5655 if (hp->type == T_MACRO)
5656 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5657 "this is the location of the previous definition");
5659 /* Replace the old definition. */
5660 hp->type = T_MACRO;
5661 hp->value.defn = mdef.defn;
5662 } else {
5663 /* If we are passing through #define and #undef directives, do
5664 that for this new definition now. */
5665 if (debug_output && op)
5666 pass_thru_directive (buf, limit, op, keyword);
5667 install (mdef.symnam, mdef.symlen, T_MACRO,
5668 (char *) mdef.defn, hashcode);
5672 return 0;
5674 nope:
5676 return 1;
5679 /* Check a purported macro name SYMNAME, and yield its length.
5680 USAGE is the kind of name this is intended for. */
5682 static int
5683 check_macro_name (symname, usage)
5684 U_CHAR *symname;
5685 char *usage;
5687 U_CHAR *p;
5688 int sym_length;
5690 for (p = symname; is_idchar[*p]; p++)
5692 sym_length = p - symname;
5693 if (sym_length == 0
5694 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5695 error ("invalid %s name", usage);
5696 else if (!is_idstart[*symname]
5697 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5698 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5699 return sym_length;
5702 /* Return zero if two DEFINITIONs are isomorphic. */
5704 static int
5705 compare_defs (d1, d2)
5706 DEFINITION *d1, *d2;
5708 register struct reflist *a1, *a2;
5709 register U_CHAR *p1 = d1->expansion;
5710 register U_CHAR *p2 = d2->expansion;
5711 int first = 1;
5713 if (d1->nargs != d2->nargs)
5714 return 1;
5715 if (pedantic
5716 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5717 return 1;
5718 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5719 a1 = a1->next, a2 = a2->next) {
5720 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5721 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5722 || a1->argno != a2->argno
5723 || a1->stringify != a2->stringify
5724 || a1->raw_before != a2->raw_before
5725 || a1->raw_after != a2->raw_after)
5726 return 1;
5727 first = 0;
5728 p1 += a1->nchars;
5729 p2 += a2->nchars;
5731 if (a1 != a2)
5732 return 1;
5733 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5734 p2, d2->length - (p2 - d2->expansion), 1))
5735 return 1;
5736 return 0;
5739 /* Return 1 if two parts of two macro definitions are effectively different.
5740 One of the parts starts at BEG1 and has LEN1 chars;
5741 the other has LEN2 chars at BEG2.
5742 Any sequence of whitespace matches any other sequence of whitespace.
5743 FIRST means these parts are the first of a macro definition;
5744 so ignore leading whitespace entirely.
5745 LAST means these parts are the last of a macro definition;
5746 so ignore trailing whitespace entirely. */
5748 static int
5749 comp_def_part (first, beg1, len1, beg2, len2, last)
5750 int first;
5751 U_CHAR *beg1, *beg2;
5752 int len1, len2;
5753 int last;
5755 register U_CHAR *end1 = beg1 + len1;
5756 register U_CHAR *end2 = beg2 + len2;
5757 if (first) {
5758 while (beg1 != end1 && is_space[*beg1]) beg1++;
5759 while (beg2 != end2 && is_space[*beg2]) beg2++;
5761 if (last) {
5762 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5763 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5765 while (beg1 != end1 && beg2 != end2) {
5766 if (is_space[*beg1] && is_space[*beg2]) {
5767 while (beg1 != end1 && is_space[*beg1]) beg1++;
5768 while (beg2 != end2 && is_space[*beg2]) beg2++;
5769 } else if (*beg1 == *beg2) {
5770 beg1++; beg2++;
5771 } else break;
5773 return (beg1 != end1) || (beg2 != end2);
5776 /* Read a replacement list for a macro with parameters.
5777 Build the DEFINITION structure.
5778 Reads characters of text starting at BUF until END.
5779 ARGLIST specifies the formal parameters to look for
5780 in the text of the definition; NARGS is the number of args
5781 in that list, or -1 for a macro name that wants no argument list.
5782 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5783 and NAMELEN is its length in characters.
5785 Note that comments, backslash-newlines, and leading white space
5786 have already been deleted from the argument. */
5788 /* If there is no trailing whitespace, a Newline Space is added at the end
5789 to prevent concatenation that would be contrary to the standard. */
5791 static DEFINITION *
5792 collect_expansion (buf, end, nargs, arglist)
5793 U_CHAR *buf, *end;
5794 int nargs;
5795 struct arglist *arglist;
5797 DEFINITION *defn;
5798 register U_CHAR *p, *limit, *lastp, *exp_p;
5799 struct reflist *endpat = NULL;
5800 /* Pointer to first nonspace after last ## seen. */
5801 U_CHAR *concat = 0;
5802 /* Pointer to first nonspace after last single-# seen. */
5803 U_CHAR *stringify = 0;
5804 /* How those tokens were spelled. */
5805 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5806 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5807 int maxsize;
5808 int expected_delimiter = '\0';
5810 /* Scan thru the replacement list, ignoring comments and quoted
5811 strings, picking up on the macro calls. It does a linear search
5812 thru the arg list on every potential symbol. Profiling might say
5813 that something smarter should happen. */
5815 if (end < buf)
5816 abort ();
5818 /* Find the beginning of the trailing whitespace. */
5819 limit = end;
5820 p = buf;
5821 while (p < limit && is_space[limit[-1]]) limit--;
5823 /* Allocate space for the text in the macro definition.
5824 Each input char may or may not need 1 byte,
5825 so this is an upper bound.
5826 The extra 3 are for invented trailing newline-marker and final null. */
5827 maxsize = (sizeof (DEFINITION)
5828 + (limit - p) + 3);
5829 defn = (DEFINITION *) xcalloc (1, maxsize);
5831 defn->nargs = nargs;
5832 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5833 lastp = exp_p;
5835 if (p[0] == '#'
5836 ? p[1] == '#'
5837 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5838 error ("`##' at start of macro definition");
5839 p += p[0] == '#' ? 2 : 4;
5842 /* Process the main body of the definition. */
5843 while (p < limit) {
5844 int skipped_arg = 0;
5845 register U_CHAR c = *p++;
5847 *exp_p++ = c;
5849 if (!traditional) {
5850 switch (c) {
5851 case '\'':
5852 case '\"':
5853 if (expected_delimiter != '\0') {
5854 if (c == expected_delimiter)
5855 expected_delimiter = '\0';
5856 } else
5857 expected_delimiter = c;
5858 break;
5860 case '\\':
5861 if (p < limit && expected_delimiter) {
5862 /* In a string, backslash goes through
5863 and makes next char ordinary. */
5864 *exp_p++ = *p++;
5866 break;
5868 case '%':
5869 if (!expected_delimiter && *p == ':') {
5870 /* %: is not a digraph if preceded by an odd number of '<'s. */
5871 U_CHAR *p0 = p - 1;
5872 while (buf < p0 && p0[-1] == '<')
5873 p0--;
5874 if ((p - p0) & 1) {
5875 /* Treat %:%: as ## and %: as #. */
5876 if (p[1] == '%' && p[2] == ':') {
5877 p += 2;
5878 goto sharp_sharp_token;
5880 if (nargs >= 0) {
5881 p++;
5882 goto sharp_token;
5886 break;
5888 case '#':
5889 /* # is ordinary inside a string. */
5890 if (expected_delimiter)
5891 break;
5892 if (*p == '#') {
5893 sharp_sharp_token:
5894 /* ##: concatenate preceding and following tokens. */
5895 /* Take out the first #, discard preceding whitespace. */
5896 exp_p--;
5897 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5898 --exp_p;
5899 /* Skip the second #. */
5900 p++;
5901 concat_sharp_token_type = c;
5902 if (is_hor_space[*p]) {
5903 concat_sharp_token_type = c + 1;
5904 p++;
5905 SKIP_WHITE_SPACE (p);
5907 concat = p;
5908 if (p == limit)
5909 error ("`##' at end of macro definition");
5910 } else if (nargs >= 0) {
5911 /* Single #: stringify following argument ref.
5912 Don't leave the # in the expansion. */
5913 sharp_token:
5914 exp_p--;
5915 stringify_sharp_token_type = c;
5916 if (is_hor_space[*p]) {
5917 stringify_sharp_token_type = c + 1;
5918 p++;
5919 SKIP_WHITE_SPACE (p);
5921 if (! is_idstart[*p] || nargs == 0
5922 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
5923 error ("`#' operator is not followed by a macro argument name");
5924 else
5925 stringify = p;
5927 break;
5929 } else {
5930 /* In -traditional mode, recognize arguments inside strings and
5931 and character constants, and ignore special properties of #.
5932 Arguments inside strings are considered "stringified", but no
5933 extra quote marks are supplied. */
5934 switch (c) {
5935 case '\'':
5936 case '\"':
5937 if (expected_delimiter != '\0') {
5938 if (c == expected_delimiter)
5939 expected_delimiter = '\0';
5940 } else
5941 expected_delimiter = c;
5942 break;
5944 case '\\':
5945 /* Backslash quotes delimiters and itself, but not macro args. */
5946 if (expected_delimiter != 0 && p < limit
5947 && (*p == expected_delimiter || *p == '\\')) {
5948 *exp_p++ = *p++;
5949 continue;
5951 break;
5953 case '/':
5954 if (expected_delimiter != '\0') /* No comments inside strings. */
5955 break;
5956 if (*p == '*') {
5957 /* If we find a comment that wasn't removed by handle_directive,
5958 this must be -traditional. So replace the comment with
5959 nothing at all. */
5960 exp_p--;
5961 while (++p < limit) {
5962 if (p[0] == '*' && p[1] == '/') {
5963 p += 2;
5964 break;
5967 #if 0
5968 /* Mark this as a concatenation-point, as if it had been ##. */
5969 concat = p;
5970 #endif
5972 break;
5976 /* Handle the start of a symbol. */
5977 if (is_idchar[c] && nargs > 0) {
5978 U_CHAR *id_beg = p - 1;
5979 int id_len;
5981 --exp_p;
5982 while (p != limit && is_idchar[*p]) p++;
5983 id_len = p - id_beg;
5985 if (is_idstart[c]
5986 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
5987 register struct arglist *arg;
5989 for (arg = arglist; arg != NULL; arg = arg->next) {
5990 struct reflist *tpat;
5992 if (arg->name[0] == c
5993 && arg->length == id_len
5994 && bcmp (arg->name, id_beg, id_len) == 0) {
5995 enum sharp_token_type tpat_stringify;
5996 if (expected_delimiter) {
5997 if (warn_stringify) {
5998 if (traditional) {
5999 warning ("macro argument `%.*s' is stringified.",
6000 id_len, arg->name);
6001 } else {
6002 warning ("macro arg `%.*s' would be stringified with -traditional.",
6003 id_len, arg->name);
6006 /* If ANSI, don't actually substitute inside a string. */
6007 if (!traditional)
6008 break;
6009 tpat_stringify = SHARP_TOKEN;
6010 } else {
6011 tpat_stringify
6012 = (stringify == id_beg
6013 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6015 /* make a pat node for this arg and append it to the end of
6016 the pat list */
6017 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6018 tpat->next = NULL;
6019 tpat->raw_before
6020 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6021 tpat->raw_after = NO_SHARP_TOKEN;
6022 tpat->rest_args = arg->rest_args;
6023 tpat->stringify = tpat_stringify;
6025 if (endpat == NULL)
6026 defn->pattern = tpat;
6027 else
6028 endpat->next = tpat;
6029 endpat = tpat;
6031 tpat->argno = arg->argno;
6032 tpat->nchars = exp_p - lastp;
6034 register U_CHAR *p1 = p;
6035 SKIP_WHITE_SPACE (p1);
6036 if (p1[0]=='#'
6037 ? p1[1]=='#'
6038 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6039 tpat->raw_after = p1[0] + (p != p1);
6041 lastp = exp_p; /* place to start copying from next time */
6042 skipped_arg = 1;
6043 break;
6048 /* If this was not a macro arg, copy it into the expansion. */
6049 if (! skipped_arg) {
6050 register U_CHAR *lim1 = p;
6051 p = id_beg;
6052 while (p != lim1)
6053 *exp_p++ = *p++;
6054 if (stringify == id_beg)
6055 error ("`#' operator should be followed by a macro argument name");
6060 if (!traditional && expected_delimiter == 0) {
6061 /* If ANSI, put in a newline-space marker to prevent token pasting.
6062 But not if "inside a string" (which in ANSI mode happens only for
6063 -D option). */
6064 *exp_p++ = '\n';
6065 *exp_p++ = ' ';
6068 *exp_p = '\0';
6070 defn->length = exp_p - defn->expansion;
6072 /* Crash now if we overrun the allocated size. */
6073 if (defn->length + 1 > maxsize)
6074 abort ();
6076 #if 0
6077 /* This isn't worth the time it takes. */
6078 /* give back excess storage */
6079 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6080 #endif
6082 return defn;
6085 static int
6086 do_assert (buf, limit, op, keyword)
6087 U_CHAR *buf, *limit;
6088 FILE_BUF *op;
6089 struct directive *keyword;
6091 U_CHAR *bp; /* temp ptr into input buffer */
6092 U_CHAR *symname; /* remember where symbol name starts */
6093 int sym_length; /* and how long it is */
6094 struct arglist *tokens = NULL;
6096 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6097 pedwarn ("ANSI C does not allow `#assert'");
6099 bp = buf;
6101 while (is_hor_space[*bp])
6102 bp++;
6104 symname = bp; /* remember where it starts */
6105 sym_length = check_macro_name (bp, "assertion");
6106 bp += sym_length;
6107 /* #define doesn't do this, but we should. */
6108 SKIP_WHITE_SPACE (bp);
6110 /* Lossage will occur if identifiers or control tokens are broken
6111 across lines using backslash. This is not the right place to take
6112 care of that. */
6114 if (*bp != '(') {
6115 error ("missing token-sequence in `#assert'");
6116 return 1;
6120 int error_flag = 0;
6122 bp++; /* skip '(' */
6123 SKIP_WHITE_SPACE (bp);
6125 tokens = read_token_list (&bp, limit, &error_flag);
6126 if (error_flag)
6127 return 1;
6128 if (tokens == 0) {
6129 error ("empty token-sequence in `#assert'");
6130 return 1;
6133 ++bp; /* skip paren */
6134 SKIP_WHITE_SPACE (bp);
6137 /* If this name isn't already an assertion name, make it one.
6138 Error if it was already in use in some other way. */
6141 ASSERTION_HASHNODE *hp;
6142 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6143 struct tokenlist_list *value
6144 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6146 hp = assertion_lookup (symname, sym_length, hashcode);
6147 if (hp == NULL) {
6148 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6149 error ("`defined' redefined as assertion");
6150 hp = assertion_install (symname, sym_length, hashcode);
6153 /* Add the spec'd token-sequence to the list of such. */
6154 value->tokens = tokens;
6155 value->next = hp->value;
6156 hp->value = value;
6159 return 0;
6162 static int
6163 do_unassert (buf, limit, op, keyword)
6164 U_CHAR *buf, *limit;
6165 FILE_BUF *op;
6166 struct directive *keyword;
6168 U_CHAR *bp; /* temp ptr into input buffer */
6169 U_CHAR *symname; /* remember where symbol name starts */
6170 int sym_length; /* and how long it is */
6172 struct arglist *tokens = NULL;
6173 int tokens_specified = 0;
6175 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6176 pedwarn ("ANSI C does not allow `#unassert'");
6178 bp = buf;
6180 while (is_hor_space[*bp])
6181 bp++;
6183 symname = bp; /* remember where it starts */
6184 sym_length = check_macro_name (bp, "assertion");
6185 bp += sym_length;
6186 /* #define doesn't do this, but we should. */
6187 SKIP_WHITE_SPACE (bp);
6189 /* Lossage will occur if identifiers or control tokens are broken
6190 across lines using backslash. This is not the right place to take
6191 care of that. */
6193 if (*bp == '(') {
6194 int error_flag = 0;
6196 bp++; /* skip '(' */
6197 SKIP_WHITE_SPACE (bp);
6199 tokens = read_token_list (&bp, limit, &error_flag);
6200 if (error_flag)
6201 return 1;
6202 if (tokens == 0) {
6203 error ("empty token list in `#unassert'");
6204 return 1;
6207 tokens_specified = 1;
6209 ++bp; /* skip paren */
6210 SKIP_WHITE_SPACE (bp);
6214 ASSERTION_HASHNODE *hp;
6215 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6216 struct tokenlist_list *tail, *prev;
6218 hp = assertion_lookup (symname, sym_length, hashcode);
6219 if (hp == NULL)
6220 return 1;
6222 /* If no token list was specified, then eliminate this assertion
6223 entirely. */
6224 if (! tokens_specified) {
6225 struct tokenlist_list *next;
6226 for (tail = hp->value; tail; tail = next) {
6227 next = tail->next;
6228 free_token_list (tail->tokens);
6229 free (tail);
6231 delete_assertion (hp);
6232 } else {
6233 /* If a list of tokens was given, then delete any matching list. */
6235 tail = hp->value;
6236 prev = 0;
6237 while (tail) {
6238 struct tokenlist_list *next = tail->next;
6239 if (compare_token_lists (tail->tokens, tokens)) {
6240 if (prev)
6241 prev->next = next;
6242 else
6243 hp->value = tail->next;
6244 free_token_list (tail->tokens);
6245 free (tail);
6246 } else {
6247 prev = tail;
6249 tail = next;
6254 return 0;
6257 /* Test whether there is an assertion named NAME
6258 and optionally whether it has an asserted token list TOKENS.
6259 NAME is not null terminated; its length is SYM_LENGTH.
6260 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6263 check_assertion (name, sym_length, tokens_specified, tokens)
6264 U_CHAR *name;
6265 int sym_length;
6266 int tokens_specified;
6267 struct arglist *tokens;
6269 ASSERTION_HASHNODE *hp;
6270 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6272 if (pedantic && !instack[indepth].system_header_p)
6273 pedwarn ("ANSI C does not allow testing assertions");
6275 hp = assertion_lookup (name, sym_length, hashcode);
6276 if (hp == NULL)
6277 /* It is not an assertion; just return false. */
6278 return 0;
6280 /* If no token list was specified, then value is 1. */
6281 if (! tokens_specified)
6282 return 1;
6285 struct tokenlist_list *tail;
6287 tail = hp->value;
6289 /* If a list of tokens was given,
6290 then succeed if the assertion records a matching list. */
6292 while (tail) {
6293 if (compare_token_lists (tail->tokens, tokens))
6294 return 1;
6295 tail = tail->next;
6298 /* Fail if the assertion has no matching list. */
6299 return 0;
6303 /* Compare two lists of tokens for equality including order of tokens. */
6305 static int
6306 compare_token_lists (l1, l2)
6307 struct arglist *l1, *l2;
6309 while (l1 && l2) {
6310 if (l1->length != l2->length)
6311 return 0;
6312 if (bcmp (l1->name, l2->name, l1->length))
6313 return 0;
6314 l1 = l1->next;
6315 l2 = l2->next;
6318 /* Succeed if both lists end at the same time. */
6319 return l1 == l2;
6322 /* Read a space-separated list of tokens ending in a close parenthesis.
6323 Return a list of strings, in the order they were written.
6324 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6325 Parse the text starting at *BPP, and update *BPP.
6326 Don't parse beyond LIMIT. */
6328 static struct arglist *
6329 read_token_list (bpp, limit, error_flag)
6330 U_CHAR **bpp;
6331 U_CHAR *limit;
6332 int *error_flag;
6334 struct arglist *token_ptrs = 0;
6335 U_CHAR *bp = *bpp;
6336 int depth = 1;
6338 *error_flag = 0;
6340 /* Loop over the assertion value tokens. */
6341 while (depth > 0) {
6342 struct arglist *temp;
6343 int eofp = 0;
6344 U_CHAR *beg = bp;
6346 /* Find the end of the token. */
6347 if (*bp == '(') {
6348 bp++;
6349 depth++;
6350 } else if (*bp == ')') {
6351 depth--;
6352 if (depth == 0)
6353 break;
6354 bp++;
6355 } else if (*bp == '"' || *bp == '\'')
6356 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6357 else
6358 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6359 && *bp != '"' && *bp != '\'' && bp != limit)
6360 bp++;
6362 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6363 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6364 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6365 temp->name[bp - beg] = 0;
6366 temp->next = token_ptrs;
6367 token_ptrs = temp;
6368 temp->length = bp - beg;
6370 SKIP_WHITE_SPACE (bp);
6372 if (bp >= limit) {
6373 error ("unterminated token sequence in `#assert' or `#unassert'");
6374 *error_flag = -1;
6375 return 0;
6378 *bpp = bp;
6380 /* We accumulated the names in reverse order.
6381 Now reverse them to get the proper order. */
6383 register struct arglist *prev = 0, *this, *next;
6384 for (this = token_ptrs; this; this = next) {
6385 next = this->next;
6386 this->next = prev;
6387 prev = this;
6389 return prev;
6393 static void
6394 free_token_list (tokens)
6395 struct arglist *tokens;
6397 while (tokens) {
6398 struct arglist *next = tokens->next;
6399 free (tokens->name);
6400 free (tokens);
6401 tokens = next;
6405 /* Install a name in the assertion hash table.
6407 If LEN is >= 0, it is the length of the name.
6408 Otherwise, compute the length by scanning the entire name.
6410 If HASH is >= 0, it is the precomputed hash code.
6411 Otherwise, compute the hash code. */
6413 static ASSERTION_HASHNODE *
6414 assertion_install (name, len, hash)
6415 U_CHAR *name;
6416 int len;
6417 int hash;
6419 register ASSERTION_HASHNODE *hp;
6420 register int i, bucket;
6421 register U_CHAR *p, *q;
6423 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6424 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6425 bucket = hash;
6426 hp->bucket_hdr = &assertion_hashtab[bucket];
6427 hp->next = assertion_hashtab[bucket];
6428 assertion_hashtab[bucket] = hp;
6429 hp->prev = NULL;
6430 if (hp->next != NULL)
6431 hp->next->prev = hp;
6432 hp->length = len;
6433 hp->value = 0;
6434 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6435 p = hp->name;
6436 q = name;
6437 for (i = 0; i < len; i++)
6438 *p++ = *q++;
6439 hp->name[len] = 0;
6440 return hp;
6443 /* Find the most recent hash node for name name (ending with first
6444 non-identifier char) installed by install
6446 If LEN is >= 0, it is the length of the name.
6447 Otherwise, compute the length by scanning the entire name.
6449 If HASH is >= 0, it is the precomputed hash code.
6450 Otherwise, compute the hash code. */
6452 static ASSERTION_HASHNODE *
6453 assertion_lookup (name, len, hash)
6454 U_CHAR *name;
6455 int len;
6456 int hash;
6458 register ASSERTION_HASHNODE *bucket;
6460 bucket = assertion_hashtab[hash];
6461 while (bucket) {
6462 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6463 return bucket;
6464 bucket = bucket->next;
6466 return NULL;
6469 static void
6470 delete_assertion (hp)
6471 ASSERTION_HASHNODE *hp;
6474 if (hp->prev != NULL)
6475 hp->prev->next = hp->next;
6476 if (hp->next != NULL)
6477 hp->next->prev = hp->prev;
6479 /* Make sure that the bucket chain header that the deleted guy was
6480 on points to the right thing afterwards. */
6481 if (hp == *hp->bucket_hdr)
6482 *hp->bucket_hdr = hp->next;
6484 free (hp);
6488 * interpret #line directive. Remembers previously seen fnames
6489 * in its very own hash table.
6491 #define FNAME_HASHSIZE 37
6493 static int
6494 do_line (buf, limit, op, keyword)
6495 U_CHAR *buf, *limit;
6496 FILE_BUF *op;
6497 struct directive *keyword;
6499 register U_CHAR *bp;
6500 FILE_BUF *ip = &instack[indepth];
6501 FILE_BUF tem;
6502 int new_lineno;
6503 enum file_change_code file_change = same_file;
6505 /* Expand any macros. */
6506 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6508 /* Point to macroexpanded line, which is null-terminated now. */
6509 bp = tem.buf;
6510 SKIP_WHITE_SPACE (bp);
6512 if (!isdigit (*bp)) {
6513 error ("invalid format `#line' directive");
6514 return 0;
6517 /* The Newline at the end of this line remains to be processed.
6518 To put the next line at the specified line number,
6519 we must store a line number now that is one less. */
6520 new_lineno = atoi ((char *) bp) - 1;
6522 /* NEW_LINENO is one less than the actual line number here. */
6523 if (pedantic && new_lineno < 0)
6524 pedwarn ("line number out of range in `#line' directive");
6526 /* skip over the line number. */
6527 while (isdigit (*bp))
6528 bp++;
6530 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6531 if (*bp && !is_space[*bp]) {
6532 error ("invalid format `#line' directive");
6533 return;
6535 #endif
6537 SKIP_WHITE_SPACE (bp);
6539 if (*bp == '\"') {
6540 static HASHNODE *fname_table[FNAME_HASHSIZE];
6541 HASHNODE *hp, **hash_bucket;
6542 U_CHAR *fname, *p;
6543 int fname_length;
6545 fname = ++bp;
6547 /* Turn the file name, which is a character string literal,
6548 into a null-terminated string. Do this in place. */
6549 p = bp;
6550 for (;;)
6551 switch ((*p++ = *bp++)) {
6552 case '\0':
6553 error ("invalid format `#line' directive");
6554 return 0;
6556 case '\\':
6558 char *bpc = (char *) bp;
6559 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6560 bp = (U_CHAR *) bpc;
6561 if (c < 0)
6562 p--;
6563 else
6564 p[-1] = c;
6566 break;
6568 case '\"':
6569 p[-1] = 0;
6570 goto fname_done;
6572 fname_done:
6573 fname_length = p - fname;
6575 SKIP_WHITE_SPACE (bp);
6576 if (*bp) {
6577 if (pedantic)
6578 pedwarn ("garbage at end of `#line' directive");
6579 if (*bp == '1')
6580 file_change = enter_file;
6581 else if (*bp == '2')
6582 file_change = leave_file;
6583 else if (*bp == '3')
6584 ip->system_header_p = 1;
6585 else if (*bp == '4')
6586 ip->system_header_p = 2;
6587 else {
6588 error ("invalid format `#line' directive");
6589 return 0;
6592 bp++;
6593 SKIP_WHITE_SPACE (bp);
6594 if (*bp == '3') {
6595 ip->system_header_p = 1;
6596 bp++;
6597 SKIP_WHITE_SPACE (bp);
6599 if (*bp == '4') {
6600 ip->system_header_p = 2;
6601 bp++;
6602 SKIP_WHITE_SPACE (bp);
6604 if (*bp) {
6605 error ("invalid format `#line' directive");
6606 return 0;
6610 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6611 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6612 if (hp->length == fname_length &&
6613 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6614 ip->nominal_fname = hp->value.cpval;
6615 break;
6617 if (hp == 0) {
6618 /* Didn't find it; cons up a new one. */
6619 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6620 hp->next = *hash_bucket;
6621 *hash_bucket = hp;
6623 hp->length = fname_length;
6624 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6625 bcopy (fname, hp->value.cpval, fname_length);
6627 } else if (*bp) {
6628 error ("invalid format `#line' directive");
6629 return 0;
6632 ip->lineno = new_lineno;
6633 output_line_directive (ip, op, 0, file_change);
6634 check_expand (op, ip->length - (ip->bufp - ip->buf));
6635 return 0;
6638 /* Remove the definition of a symbol from the symbol table.
6639 according to un*x /lib/cpp, it is not an error to undef
6640 something that has no definitions, so it isn't one here either. */
6642 static int
6643 do_undef (buf, limit, op, keyword)
6644 U_CHAR *buf, *limit;
6645 FILE_BUF *op;
6646 struct directive *keyword;
6648 int sym_length;
6649 HASHNODE *hp;
6650 U_CHAR *orig_buf = buf;
6652 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6653 if (pcp_outfile && op)
6654 pass_thru_directive (buf, limit, op, keyword);
6656 SKIP_WHITE_SPACE (buf);
6657 sym_length = check_macro_name (buf, "macro");
6659 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6660 /* If we are generating additional info for debugging (with -g) we
6661 need to pass through all effective #undef directives. */
6662 if (debug_output && op)
6663 pass_thru_directive (orig_buf, limit, op, keyword);
6664 if (hp->type != T_MACRO)
6665 warning ("undefining `%s'", hp->name);
6666 delete_macro (hp);
6669 if (pedantic) {
6670 buf += sym_length;
6671 SKIP_WHITE_SPACE (buf);
6672 if (buf != limit)
6673 pedwarn ("garbage after `#undef' directive");
6675 return 0;
6678 /* Report an error detected by the program we are processing.
6679 Use the text of the line in the error message.
6680 (We use error because it prints the filename & line#.) */
6682 static int
6683 do_error (buf, limit, op, keyword)
6684 U_CHAR *buf, *limit;
6685 FILE_BUF *op;
6686 struct directive *keyword;
6688 int length = limit - buf;
6689 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6690 bcopy ((char *) buf, (char *) copy, length);
6691 copy[length] = 0;
6692 SKIP_WHITE_SPACE (copy);
6693 error ("#error %s", copy);
6694 return 0;
6697 /* Report a warning detected by the program we are processing.
6698 Use the text of the line in the warning message, then continue.
6699 (We use error because it prints the filename & line#.) */
6701 static int
6702 do_warning (buf, limit, op, keyword)
6703 U_CHAR *buf, *limit;
6704 FILE_BUF *op;
6705 struct directive *keyword;
6707 int length = limit - buf;
6708 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6709 bcopy ((char *) buf, (char *) copy, length);
6710 copy[length] = 0;
6711 SKIP_WHITE_SPACE (copy);
6712 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
6713 if -pedantic-errors is given, #warning should cause an error. */
6714 pedwarn ("#warning %s", copy);
6715 return 0;
6718 /* Remember the name of the current file being read from so that we can
6719 avoid ever including it again. */
6721 static void
6722 do_once ()
6724 int i;
6726 for (i = indepth; i >= 0; i--)
6727 if (instack[i].inc) {
6728 record_control_macro (instack[i].inc, (U_CHAR *) "");
6729 break;
6733 /* Report program identification. */
6735 static int
6736 do_ident (buf, limit, op, keyword)
6737 U_CHAR *buf, *limit;
6738 FILE_BUF *op;
6739 struct directive *keyword;
6741 FILE_BUF trybuf;
6742 int len;
6744 /* Allow #ident in system headers, since that's not user's fault. */
6745 if (pedantic && !instack[indepth].system_header_p)
6746 pedwarn ("ANSI C does not allow `#ident'");
6748 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6749 buf = trybuf.buf;
6750 len = trybuf.bufp - buf;
6752 /* Output expanded directive. */
6753 check_expand (op, 7 + len);
6754 bcopy ("#ident ", (char *) op->bufp, 7);
6755 op->bufp += 7;
6756 bcopy ((char *) buf, (char *) op->bufp, len);
6757 op->bufp += len;
6759 free (buf);
6760 return 0;
6763 /* #pragma and its argument line have already been copied to the output file.
6764 Just check for some recognized pragmas that need validation here. */
6766 static int
6767 do_pragma (buf, limit, op, keyword)
6768 U_CHAR *buf, *limit;
6769 FILE_BUF *op;
6770 struct directive *keyword;
6772 SKIP_WHITE_SPACE (buf);
6773 if (!strncmp ((char *) buf, "once", 4)) {
6774 /* Allow #pragma once in system headers, since that's not the user's
6775 fault. */
6776 if (!instack[indepth].system_header_p)
6777 warning ("`#pragma once' is obsolete");
6778 do_once ();
6781 if (!strncmp ((char *) buf, "implementation", 14)) {
6782 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6783 been included yet. */
6785 int h;
6786 U_CHAR *p = buf + 14, *fname;
6787 SKIP_WHITE_SPACE (p);
6788 if (*p != '\"')
6789 return 0;
6791 fname = p + 1;
6792 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6793 *p = '\0';
6795 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6796 struct include_file *inc;
6797 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6798 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6799 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6800 return 0;
6805 return 0;
6808 #if 0
6809 /* This was a fun hack, but #pragma seems to start to be useful.
6810 By failing to recognize it, we pass it through unchanged to cc1. */
6812 /* The behavior of the #pragma directive is implementation defined.
6813 this implementation defines it as follows. */
6815 static int
6816 do_pragma ()
6818 close (0);
6819 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6820 goto nope;
6821 close (1);
6822 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6823 goto nope;
6824 execl ("/usr/games/hack", "#pragma", 0);
6825 execl ("/usr/games/rogue", "#pragma", 0);
6826 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6827 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6828 nope:
6829 fatal ("You are in a maze of twisty compiler features, all different");
6831 #endif
6833 #ifdef SCCS_DIRECTIVE
6835 /* Just ignore #sccs, on systems where we define it at all. */
6837 static int
6838 do_sccs (buf, limit, op, keyword)
6839 U_CHAR *buf, *limit;
6840 FILE_BUF *op;
6841 struct directive *keyword;
6843 if (pedantic)
6844 pedwarn ("ANSI C does not allow `#sccs'");
6845 return 0;
6848 #endif /* defined (SCCS_DIRECTIVE) */
6850 /* Handle #if directive by
6851 1) inserting special `defined' keyword into the hash table
6852 that gets turned into 0 or 1 by special_symbol (thus,
6853 if the luser has a symbol called `defined' already, it won't
6854 work inside the #if directive)
6855 2) rescan the input into a temporary output buffer
6856 3) pass the output buffer to the yacc parser and collect a value
6857 4) clean up the mess left from steps 1 and 2.
6858 5) call conditional_skip to skip til the next #endif (etc.),
6859 or not, depending on the value from step 3. */
6861 static int
6862 do_if (buf, limit, op, keyword)
6863 U_CHAR *buf, *limit;
6864 FILE_BUF *op;
6865 struct directive *keyword;
6867 HOST_WIDE_INT value;
6868 FILE_BUF *ip = &instack[indepth];
6870 value = eval_if_expression (buf, limit - buf);
6871 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6872 return 0;
6875 /* Handle a #elif directive by not changing if_stack either.
6876 see the comment above do_else. */
6878 static int
6879 do_elif (buf, limit, op, keyword)
6880 U_CHAR *buf, *limit;
6881 FILE_BUF *op;
6882 struct directive *keyword;
6884 HOST_WIDE_INT value;
6885 FILE_BUF *ip = &instack[indepth];
6887 if (if_stack == instack[indepth].if_stack) {
6888 error ("`#elif' not within a conditional");
6889 return 0;
6890 } else {
6891 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6892 error ("`#elif' after `#else'");
6893 fprintf (stderr, " (matches line %d", if_stack->lineno);
6894 if (if_stack->fname != NULL && ip->fname != NULL
6895 && strcmp (if_stack->fname, ip->nominal_fname) != 0)
6896 fprintf (stderr, ", file %s", if_stack->fname);
6897 fprintf (stderr, ")\n");
6899 if_stack->type = T_ELIF;
6902 if (if_stack->if_succeeded)
6903 skip_if_group (ip, 0, op);
6904 else {
6905 value = eval_if_expression (buf, limit - buf);
6906 if (value == 0)
6907 skip_if_group (ip, 0, op);
6908 else {
6909 ++if_stack->if_succeeded; /* continue processing input */
6910 output_line_directive (ip, op, 1, same_file);
6913 return 0;
6916 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
6917 result as a C expression and return the value as an int. */
6919 static HOST_WIDE_INT
6920 eval_if_expression (buf, length)
6921 U_CHAR *buf;
6922 int length;
6924 FILE_BUF temp_obuf;
6925 HASHNODE *save_defined;
6926 HOST_WIDE_INT value;
6928 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
6929 NULL_PTR, -1);
6930 pcp_inside_if = 1;
6931 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6932 pcp_inside_if = 0;
6933 delete_macro (save_defined); /* clean up special symbol */
6935 temp_obuf.buf[temp_obuf.length] = '\n';
6936 value = parse_c_expression ((char *) temp_obuf.buf,
6937 warn_undef && !instack[indepth].system_header_p);
6939 free (temp_obuf.buf);
6941 return value;
6944 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
6945 or don't skip to the #endif/#else/#elif depending on what directive
6946 is actually being processed. */
6948 static int
6949 do_xifdef (buf, limit, op, keyword)
6950 U_CHAR *buf, *limit;
6951 FILE_BUF *op;
6952 struct directive *keyword;
6954 int skip;
6955 FILE_BUF *ip = &instack[indepth];
6956 U_CHAR *end;
6957 int start_of_file = 0;
6958 U_CHAR *control_macro = 0;
6960 /* Detect a #ifndef at start of file (not counting comments). */
6961 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
6962 U_CHAR *p = ip->buf;
6963 while (p != directive_start) {
6964 U_CHAR c = *p++;
6965 if (is_space[c])
6967 /* Make no special provision for backslash-newline here; this is
6968 slower if backslash-newlines are present, but it's correct,
6969 and it's not worth it to tune for the rare backslash-newline. */
6970 else if (c == '/'
6971 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
6972 /* Skip this comment. */
6973 int junk = 0;
6974 U_CHAR *save_bufp = ip->bufp;
6975 ip->bufp = p + 1;
6976 p = skip_to_end_of_comment (ip, &junk, 1);
6977 ip->bufp = save_bufp;
6978 } else {
6979 goto fail;
6982 /* If we get here, this conditional is the beginning of the file. */
6983 start_of_file = 1;
6984 fail: ;
6987 /* Discard leading and trailing whitespace. */
6988 SKIP_WHITE_SPACE (buf);
6989 while (limit != buf && is_hor_space[limit[-1]]) limit--;
6991 /* Find the end of the identifier at the beginning. */
6992 for (end = buf; is_idchar[*end]; end++);
6994 if (end == buf) {
6995 skip = (keyword->type == T_IFDEF);
6996 if (! traditional)
6997 pedwarn (end == limit ? "`#%s' with no argument"
6998 : "`#%s' argument starts with punctuation",
6999 keyword->name);
7000 } else {
7001 HASHNODE *hp;
7003 if (! traditional) {
7004 if (isdigit (buf[0]))
7005 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7006 else if (end != limit)
7007 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7010 hp = lookup (buf, end-buf, -1);
7012 if (pcp_outfile) {
7013 /* Output a precondition for this macro. */
7014 if (hp
7015 && (hp->type == T_CONST
7016 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7017 fprintf (pcp_outfile, "#define %s\n", hp->name);
7018 else {
7019 U_CHAR *cp = buf;
7020 fprintf (pcp_outfile, "#undef ");
7021 while (is_idchar[*cp]) /* Ick! */
7022 fputc (*cp++, pcp_outfile);
7023 putc ('\n', pcp_outfile);
7027 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7028 if (start_of_file && !skip) {
7029 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7030 bcopy ((char *) buf, (char *) control_macro, end - buf);
7031 control_macro[end - buf] = 0;
7035 conditional_skip (ip, skip, T_IF, control_macro, op);
7036 return 0;
7039 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7040 If this is a #ifndef starting at the beginning of a file,
7041 CONTROL_MACRO is the macro name tested by the #ifndef.
7042 Otherwise, CONTROL_MACRO is 0. */
7044 static void
7045 conditional_skip (ip, skip, type, control_macro, op)
7046 FILE_BUF *ip;
7047 int skip;
7048 enum node_type type;
7049 U_CHAR *control_macro;
7050 FILE_BUF *op;
7052 IF_STACK_FRAME *temp;
7054 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7055 temp->fname = ip->nominal_fname;
7056 temp->lineno = ip->lineno;
7057 temp->next = if_stack;
7058 temp->control_macro = control_macro;
7059 if_stack = temp;
7061 if_stack->type = type;
7063 if (skip != 0) {
7064 skip_if_group (ip, 0, op);
7065 return;
7066 } else {
7067 ++if_stack->if_succeeded;
7068 output_line_directive (ip, &outbuf, 1, same_file);
7072 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7073 Leaves input ptr at the sharp sign found.
7074 If ANY is nonzero, return at next directive of any sort. */
7076 static void
7077 skip_if_group (ip, any, op)
7078 FILE_BUF *ip;
7079 int any;
7080 FILE_BUF *op;
7082 register U_CHAR *bp = ip->bufp, *cp;
7083 register U_CHAR *endb = ip->buf + ip->length;
7084 struct directive *kt;
7085 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7086 U_CHAR *beg_of_line = bp;
7087 register int ident_length;
7088 U_CHAR *ident, *after_ident;
7089 /* Save info about where the group starts. */
7090 U_CHAR *beg_of_group = bp;
7091 int beg_lineno = ip->lineno;
7093 if (output_conditionals && op != 0) {
7094 char *ptr = "#failed\n";
7095 int len = strlen (ptr);
7097 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7099 *op->bufp++ = '\n';
7100 op->lineno++;
7102 check_expand (op, len);
7103 bcopy (ptr, (char *) op->bufp, len);
7104 op->bufp += len;
7105 op->lineno++;
7106 output_line_directive (ip, op, 1, 0);
7109 while (bp < endb) {
7110 switch (*bp++) {
7111 case '/': /* possible comment */
7112 if (*bp == '\\' && bp[1] == '\n')
7113 newline_fix (bp);
7114 if (*bp == '*'
7115 || (cplusplus_comments && *bp == '/')) {
7116 ip->bufp = ++bp;
7117 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7119 break;
7120 case '\"':
7121 case '\'':
7122 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7123 NULL_PTR, NULL_PTR);
7124 break;
7125 case '\\':
7126 /* Char after backslash loses its special meaning. */
7127 if (bp < endb) {
7128 if (*bp == '\n')
7129 ++ip->lineno; /* But do update the line-count. */
7130 bp++;
7132 break;
7133 case '\n':
7134 ++ip->lineno;
7135 beg_of_line = bp;
7136 break;
7137 case '%':
7138 if (beg_of_line == 0 || traditional)
7139 break;
7140 ip->bufp = bp - 1;
7141 while (bp[0] == '\\' && bp[1] == '\n')
7142 bp += 2;
7143 if (*bp == ':')
7144 goto sharp_token;
7145 break;
7146 case '#':
7147 /* # keyword: a # must be first nonblank char on the line */
7148 if (beg_of_line == 0)
7149 break;
7150 ip->bufp = bp - 1;
7151 sharp_token:
7152 /* Scan from start of line, skipping whitespace, comments
7153 and backslash-newlines, and see if we reach this #.
7154 If not, this # is not special. */
7155 bp = beg_of_line;
7156 /* If -traditional, require # to be at beginning of line. */
7157 if (!traditional) {
7158 while (1) {
7159 if (is_hor_space[*bp])
7160 bp++;
7161 else if (*bp == '\\' && bp[1] == '\n')
7162 bp += 2;
7163 else if (*bp == '/' && bp[1] == '*') {
7164 bp += 2;
7165 while (!(*bp == '*' && bp[1] == '/'))
7166 bp++;
7167 bp += 2;
7169 /* There is no point in trying to deal with C++ // comments here,
7170 because if there is one, then this # must be part of the
7171 comment and we would never reach here. */
7172 else break;
7175 if (bp != ip->bufp) {
7176 bp = ip->bufp + 1; /* Reset bp to after the #. */
7177 break;
7180 bp = ip->bufp + 1; /* Point after the '#' */
7181 if (ip->bufp[0] == '%') {
7182 /* Skip past the ':' again. */
7183 while (*bp == '\\') {
7184 ip->lineno++;
7185 bp += 2;
7187 bp++;
7190 /* Skip whitespace and \-newline. */
7191 while (1) {
7192 if (is_hor_space[*bp])
7193 bp++;
7194 else if (*bp == '\\' && bp[1] == '\n')
7195 bp += 2;
7196 else if (*bp == '/') {
7197 if (bp[1] == '*') {
7198 for (bp += 2; ; bp++) {
7199 if (*bp == '\n')
7200 ip->lineno++;
7201 else if (*bp == '*') {
7202 if (bp[-1] == '/' && warn_comments)
7203 warning ("`/*' within comment");
7204 if (bp[1] == '/')
7205 break;
7208 bp += 2;
7209 } else if (bp[1] == '/' && cplusplus_comments) {
7210 for (bp += 2; ; bp++) {
7211 if (*bp == '\n') {
7212 if (bp[-1] != '\\')
7213 break;
7214 if (warn_comments)
7215 warning ("multiline `//' comment");
7216 ip->lineno++;
7219 } else
7220 break;
7221 } else
7222 break;
7225 cp = bp;
7227 /* Now find end of directive name.
7228 If we encounter a backslash-newline, exchange it with any following
7229 symbol-constituents so that we end up with a contiguous name. */
7231 while (1) {
7232 if (is_idchar[*bp])
7233 bp++;
7234 else {
7235 if (*bp == '\\' && bp[1] == '\n')
7236 name_newline_fix (bp);
7237 if (is_idchar[*bp])
7238 bp++;
7239 else break;
7242 ident_length = bp - cp;
7243 ident = cp;
7244 after_ident = bp;
7246 /* A line of just `#' becomes blank. */
7248 if (ident_length == 0 && *after_ident == '\n') {
7249 continue;
7252 if (ident_length == 0 || !is_idstart[*ident]) {
7253 U_CHAR *p = ident;
7254 while (is_idchar[*p]) {
7255 if (*p < '0' || *p > '9')
7256 break;
7257 p++;
7259 /* Handle # followed by a line number. */
7260 if (p != ident && !is_idchar[*p]) {
7261 if (pedantic)
7262 pedwarn ("`#' followed by integer");
7263 continue;
7266 /* Avoid error for `###' and similar cases unless -pedantic. */
7267 if (p == ident) {
7268 while (*p == '#' || is_hor_space[*p]) p++;
7269 if (*p == '\n') {
7270 if (pedantic && !lang_asm)
7271 pedwarn ("invalid preprocessing directive");
7272 continue;
7276 if (!lang_asm && pedantic)
7277 pedwarn ("invalid preprocessing directive name");
7278 continue;
7281 for (kt = directive_table; kt->length >= 0; kt++) {
7282 IF_STACK_FRAME *temp;
7283 if (ident_length == kt->length
7284 && bcmp (cp, kt->name, kt->length) == 0) {
7285 /* If we are asked to return on next directive, do so now. */
7286 if (any)
7287 goto done;
7289 switch (kt->type) {
7290 case T_IF:
7291 case T_IFDEF:
7292 case T_IFNDEF:
7293 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7294 temp->next = if_stack;
7295 if_stack = temp;
7296 temp->lineno = ip->lineno;
7297 temp->fname = ip->nominal_fname;
7298 temp->type = kt->type;
7299 break;
7300 case T_ELSE:
7301 case T_ENDIF:
7302 if (pedantic && if_stack != save_if_stack)
7303 validate_else (bp, endb);
7304 case T_ELIF:
7305 if (if_stack == instack[indepth].if_stack) {
7306 error ("`#%s' not within a conditional", kt->name);
7307 break;
7309 else if (if_stack == save_if_stack)
7310 goto done; /* found what we came for */
7312 if (kt->type != T_ENDIF) {
7313 if (if_stack->type == T_ELSE)
7314 error ("`#else' or `#elif' after `#else'");
7315 if_stack->type = kt->type;
7316 break;
7319 temp = if_stack;
7320 if_stack = if_stack->next;
7321 free (temp);
7322 break;
7324 default:
7325 break;
7327 break;
7330 /* Don't let erroneous code go by. */
7331 if (kt->length < 0 && !lang_asm && pedantic)
7332 pedwarn ("invalid preprocessing directive name");
7336 ip->bufp = bp;
7337 /* after this returns, rescan will exit because ip->bufp
7338 now points to the end of the buffer.
7339 rescan is responsible for the error message also. */
7341 done:
7342 if (output_conditionals && op != 0) {
7343 char *ptr = "#endfailed\n";
7344 int len = strlen (ptr);
7346 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7348 *op->bufp++ = '\n';
7349 op->lineno++;
7351 check_expand (op, beg_of_line - beg_of_group);
7352 bcopy ((char *) beg_of_group, (char *) op->bufp,
7353 beg_of_line - beg_of_group);
7354 op->bufp += beg_of_line - beg_of_group;
7355 op->lineno += ip->lineno - beg_lineno;
7356 check_expand (op, len);
7357 bcopy (ptr, (char *) op->bufp, len);
7358 op->bufp += len;
7359 op->lineno++;
7363 /* Handle a #else directive. Do this by just continuing processing
7364 without changing if_stack ; this is so that the error message
7365 for missing #endif's etc. will point to the original #if. It
7366 is possible that something different would be better. */
7368 static int
7369 do_else (buf, limit, op, keyword)
7370 U_CHAR *buf, *limit;
7371 FILE_BUF *op;
7372 struct directive *keyword;
7374 FILE_BUF *ip = &instack[indepth];
7376 if (pedantic) {
7377 SKIP_WHITE_SPACE (buf);
7378 if (buf != limit)
7379 pedwarn ("text following `#else' violates ANSI standard");
7382 if (if_stack == instack[indepth].if_stack) {
7383 error ("`#else' not within a conditional");
7384 return 0;
7385 } else {
7386 /* #ifndef can't have its special treatment for containing the whole file
7387 if it has a #else clause. */
7388 if_stack->control_macro = 0;
7390 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7391 error ("`#else' after `#else'");
7392 fprintf (stderr, " (matches line %d", if_stack->lineno);
7393 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7394 fprintf (stderr, ", file %s", if_stack->fname);
7395 fprintf (stderr, ")\n");
7397 if_stack->type = T_ELSE;
7400 if (if_stack->if_succeeded)
7401 skip_if_group (ip, 0, op);
7402 else {
7403 ++if_stack->if_succeeded; /* continue processing input */
7404 output_line_directive (ip, op, 1, same_file);
7406 return 0;
7409 /* Unstack after #endif directive. */
7411 static int
7412 do_endif (buf, limit, op, keyword)
7413 U_CHAR *buf, *limit;
7414 FILE_BUF *op;
7415 struct directive *keyword;
7417 if (pedantic) {
7418 SKIP_WHITE_SPACE (buf);
7419 if (buf != limit)
7420 pedwarn ("text following `#endif' violates ANSI standard");
7423 if (if_stack == instack[indepth].if_stack)
7424 error ("unbalanced `#endif'");
7425 else {
7426 IF_STACK_FRAME *temp = if_stack;
7427 if_stack = if_stack->next;
7428 if (temp->control_macro != 0) {
7429 /* This #endif matched a #ifndef at the start of the file.
7430 See if it is at the end of the file. */
7431 FILE_BUF *ip = &instack[indepth];
7432 U_CHAR *p = ip->bufp;
7433 U_CHAR *ep = ip->buf + ip->length;
7435 while (p != ep) {
7436 U_CHAR c = *p++;
7437 if (!is_space[c]) {
7438 if (c == '/'
7439 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7440 /* Skip this comment. */
7441 int junk = 0;
7442 U_CHAR *save_bufp = ip->bufp;
7443 ip->bufp = p + 1;
7444 p = skip_to_end_of_comment (ip, &junk, 1);
7445 ip->bufp = save_bufp;
7446 } else
7447 goto fail;
7450 /* If we get here, this #endif ends a #ifndef
7451 that contains all of the file (aside from whitespace).
7452 Arrange not to include the file again
7453 if the macro that was tested is defined.
7455 Do not do this for the top-level file in a -include or any
7456 file in a -imacros. */
7457 if (indepth != 0
7458 && ! (indepth == 1 && no_record_file)
7459 && ! (no_record_file && no_output))
7460 record_control_macro (ip->inc, temp->control_macro);
7461 fail: ;
7463 free (temp);
7464 output_line_directive (&instack[indepth], op, 1, same_file);
7466 return 0;
7469 /* When an #else or #endif is found while skipping failed conditional,
7470 if -pedantic was specified, this is called to warn about text after
7471 the directive name. P points to the first char after the directive
7472 name. */
7474 static void
7475 validate_else (p, limit)
7476 register U_CHAR *p;
7477 register U_CHAR *limit;
7479 /* Advance P over whitespace and comments. */
7480 while (1) {
7481 while (*p == '\\' && p[1] == '\n')
7482 p += 2;
7483 if (is_hor_space[*p])
7484 p++;
7485 else if (*p == '/') {
7486 while (p[1] == '\\' && p[2] == '\n')
7487 p += 2;
7488 if (p[1] == '*') {
7489 /* Don't bother warning about unterminated comments
7490 since that will happen later. Just be sure to exit. */
7491 for (p += 2; ; p++) {
7492 if (p == limit)
7493 return;
7494 if (*p == '*') {
7495 while (p[1] == '\\' && p[2] == '\n')
7496 p += 2;
7497 if (p[1] == '/') {
7498 p += 2;
7499 break;
7504 else if (cplusplus_comments && p[1] == '/')
7505 return;
7506 else break;
7507 } else break;
7509 if (*p != '\n')
7510 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7513 /* Skip a comment, assuming the input ptr immediately follows the
7514 initial slash-star. Bump *LINE_COUNTER for each newline.
7515 (The canonical line counter is &ip->lineno.)
7516 Don't use this routine (or the next one) if bumping the line
7517 counter is not sufficient to deal with newlines in the string.
7519 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7520 This feature is useful when processing a comment that is going to
7521 be processed or was processed at another point in the preprocessor,
7522 to avoid a duplicate warning. Likewise for unterminated comment
7523 errors. */
7525 static U_CHAR *
7526 skip_to_end_of_comment (ip, line_counter, nowarn)
7527 register FILE_BUF *ip;
7528 int *line_counter; /* place to remember newlines, or NULL */
7529 int nowarn;
7531 register U_CHAR *limit = ip->buf + ip->length;
7532 register U_CHAR *bp = ip->bufp;
7533 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7534 int start_line = line_counter ? *line_counter : 0;
7536 /* JF this line_counter stuff is a crock to make sure the
7537 comment is only put out once, no matter how many times
7538 the comment is skipped. It almost works */
7539 if (op) {
7540 *op->bufp++ = '/';
7541 *op->bufp++ = bp[-1];
7543 if (cplusplus_comments && bp[-1] == '/') {
7544 for (; bp < limit; bp++) {
7545 if (*bp == '\n') {
7546 if (bp[-1] != '\\')
7547 break;
7548 if (!nowarn && warn_comments)
7549 warning ("multiline `//' comment");
7550 if (line_counter)
7551 ++*line_counter;
7552 if (op)
7553 ++op->lineno;
7555 if (op)
7556 *op->bufp++ = *bp;
7558 ip->bufp = bp;
7559 return bp;
7561 while (bp < limit) {
7562 if (op)
7563 *op->bufp++ = *bp;
7564 switch (*bp++) {
7565 case '\n':
7566 /* If this is the end of the file, we have an unterminated comment.
7567 Don't swallow the newline. We are guaranteed that there will be a
7568 trailing newline and various pieces assume it's there. */
7569 if (bp == limit)
7571 --bp;
7572 --limit;
7573 break;
7575 if (line_counter != NULL)
7576 ++*line_counter;
7577 if (op)
7578 ++op->lineno;
7579 break;
7580 case '*':
7581 if (bp[-2] == '/' && !nowarn && warn_comments)
7582 warning ("`/*' within comment");
7583 if (*bp == '\\' && bp[1] == '\n')
7584 newline_fix (bp);
7585 if (*bp == '/') {
7586 if (op)
7587 *op->bufp++ = '/';
7588 ip->bufp = ++bp;
7589 return bp;
7591 break;
7595 if (!nowarn)
7596 error_with_line (line_for_error (start_line), "unterminated comment");
7597 ip->bufp = bp;
7598 return bp;
7601 /* Skip over a quoted string. BP points to the opening quote.
7602 Returns a pointer after the closing quote. Don't go past LIMIT.
7603 START_LINE is the line number of the starting point (but it need
7604 not be valid if the starting point is inside a macro expansion).
7606 The input stack state is not changed.
7608 If COUNT_NEWLINES is nonzero, it points to an int to increment
7609 for each newline passed.
7611 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7612 if we pass a backslash-newline.
7614 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
7616 static U_CHAR *
7617 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7618 register U_CHAR *bp;
7619 register U_CHAR *limit;
7620 int start_line;
7621 int *count_newlines;
7622 int *backslash_newlines_p;
7623 int *eofp;
7625 register U_CHAR c, match;
7627 match = *bp++;
7628 while (1) {
7629 if (bp >= limit) {
7630 error_with_line (line_for_error (start_line),
7631 "unterminated string or character constant");
7632 error_with_line (multiline_string_line,
7633 "possible real start of unterminated constant");
7634 multiline_string_line = 0;
7635 if (eofp)
7636 *eofp = 1;
7637 break;
7639 c = *bp++;
7640 if (c == '\\') {
7641 while (*bp == '\\' && bp[1] == '\n') {
7642 if (backslash_newlines_p)
7643 *backslash_newlines_p = 1;
7644 if (count_newlines)
7645 ++*count_newlines;
7646 bp += 2;
7648 if (*bp == '\n' && count_newlines) {
7649 if (backslash_newlines_p)
7650 *backslash_newlines_p = 1;
7651 ++*count_newlines;
7653 bp++;
7654 } else if (c == '\n') {
7655 if (traditional) {
7656 /* Unterminated strings and character constants are 'valid'. */
7657 bp--; /* Don't consume the newline. */
7658 if (eofp)
7659 *eofp = 1;
7660 break;
7662 if (match == '\'') {
7663 error_with_line (line_for_error (start_line),
7664 "unterminated string or character constant");
7665 bp--;
7666 if (eofp)
7667 *eofp = 1;
7668 break;
7670 /* If not traditional, then allow newlines inside strings. */
7671 if (count_newlines)
7672 ++*count_newlines;
7673 if (multiline_string_line == 0) {
7674 if (pedantic)
7675 pedwarn_with_line (line_for_error (start_line),
7676 "string constant runs past end of line");
7677 multiline_string_line = start_line;
7679 } else if (c == match)
7680 break;
7682 return bp;
7685 /* Place into DST a quoted string representing the string SRC.
7686 Return the address of DST's terminating null. */
7688 static char *
7689 quote_string (dst, src)
7690 char *dst, *src;
7692 U_CHAR c;
7694 *dst++ = '\"';
7695 for (;;)
7696 switch ((c = *src++))
7698 default:
7699 if (isprint (c))
7700 *dst++ = c;
7701 else
7703 sprintf (dst, "\\%03o", c);
7704 dst += 4;
7706 break;
7708 case '\"':
7709 case '\\':
7710 *dst++ = '\\';
7711 *dst++ = c;
7712 break;
7714 case '\0':
7715 *dst++ = '\"';
7716 *dst = '\0';
7717 return dst;
7721 /* Skip across a group of balanced parens, starting from IP->bufp.
7722 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7724 This does not handle newlines, because it's used for the arg of #if,
7725 where there aren't any newlines. Also, backslash-newline can't appear. */
7727 static U_CHAR *
7728 skip_paren_group (ip)
7729 register FILE_BUF *ip;
7731 U_CHAR *limit = ip->buf + ip->length;
7732 U_CHAR *p = ip->bufp;
7733 int depth = 0;
7734 int lines_dummy = 0;
7736 while (p != limit) {
7737 int c = *p++;
7738 switch (c) {
7739 case '(':
7740 depth++;
7741 break;
7743 case ')':
7744 depth--;
7745 if (depth == 0)
7746 return ip->bufp = p;
7747 break;
7749 case '/':
7750 if (*p == '*') {
7751 ip->bufp = p;
7752 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7753 p = ip->bufp;
7756 case '"':
7757 case '\'':
7759 int eofp = 0;
7760 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7761 if (eofp)
7762 return ip->bufp = p;
7764 break;
7768 ip->bufp = p;
7769 return p;
7772 /* Write out a #line directive, for instance, after an #include file.
7773 If CONDITIONAL is nonzero, we can omit the #line if it would
7774 appear to be a no-op, and we can output a few newlines instead
7775 if we want to increase the line number by a small amount.
7776 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
7778 static void
7779 output_line_directive (ip, op, conditional, file_change)
7780 FILE_BUF *ip, *op;
7781 int conditional;
7782 enum file_change_code file_change;
7784 int len;
7785 char *line_directive_buf, *line_end;
7787 if (no_line_directives
7788 || ip->fname == NULL
7789 || no_output) {
7790 op->lineno = ip->lineno;
7791 return;
7794 if (conditional) {
7795 if (ip->lineno == op->lineno)
7796 return;
7798 /* If the inherited line number is a little too small,
7799 output some newlines instead of a #line directive. */
7800 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7801 check_expand (op, 10);
7802 while (ip->lineno > op->lineno) {
7803 *op->bufp++ = '\n';
7804 op->lineno++;
7806 return;
7810 /* Output a positive line number if possible. */
7811 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
7812 && *ip->bufp == '\n') {
7813 ip->lineno++;
7814 ip->bufp++;
7817 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7818 sprintf (line_directive_buf, "# %d ", ip->lineno);
7819 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7820 ip->nominal_fname);
7821 if (file_change != same_file) {
7822 *line_end++ = ' ';
7823 *line_end++ = file_change == enter_file ? '1' : '2';
7825 /* Tell cc1 if following text comes from a system header file. */
7826 if (ip->system_header_p) {
7827 *line_end++ = ' ';
7828 *line_end++ = '3';
7830 #ifndef NO_IMPLICIT_EXTERN_C
7831 /* Tell cc1plus if following text should be treated as C. */
7832 if (ip->system_header_p == 2 && cplusplus) {
7833 *line_end++ = ' ';
7834 *line_end++ = '4';
7836 #endif
7837 *line_end++ = '\n';
7838 len = line_end - line_directive_buf;
7839 check_expand (op, len + 1);
7840 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7841 *op->bufp++ = '\n';
7842 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7843 op->bufp += len;
7844 op->lineno = ip->lineno;
7847 /* This structure represents one parsed argument in a macro call.
7848 `raw' points to the argument text as written (`raw_length' is its length).
7849 `expanded' points to the argument's macro-expansion
7850 (its length is `expand_length').
7851 `stringified_length' is the length the argument would have
7852 if stringified.
7853 `use_count' is the number of times this macro arg is substituted
7854 into the macro. If the actual use count exceeds 10,
7855 the value stored is 10.
7856 `free1' and `free2', if nonzero, point to blocks to be freed
7857 when the macro argument data is no longer needed. */
7859 struct argdata {
7860 U_CHAR *raw, *expanded;
7861 int raw_length, expand_length;
7862 int stringified_length;
7863 U_CHAR *free1, *free2;
7864 char newlines;
7865 char use_count;
7868 /* Expand a macro call.
7869 HP points to the symbol that is the macro being called.
7870 Put the result of expansion onto the input stack
7871 so that subsequent input by our caller will use it.
7873 If macro wants arguments, caller has already verified that
7874 an argument list follows; arguments come from the input stack. */
7876 static void
7877 macroexpand (hp, op)
7878 HASHNODE *hp;
7879 FILE_BUF *op;
7881 int nargs;
7882 DEFINITION *defn = hp->value.defn;
7883 register U_CHAR *xbuf;
7884 int xbuf_len;
7885 int start_line = instack[indepth].lineno;
7886 int rest_args, rest_zero;
7888 CHECK_DEPTH (return;);
7890 /* it might not actually be a macro. */
7891 if (hp->type != T_MACRO) {
7892 special_symbol (hp, op);
7893 return;
7896 /* This macro is being used inside a #if, which means it must be */
7897 /* recorded as a precondition. */
7898 if (pcp_inside_if && pcp_outfile && defn->predefined)
7899 dump_single_macro (hp, pcp_outfile);
7901 nargs = defn->nargs;
7903 if (nargs >= 0) {
7904 register int i;
7905 struct argdata *args;
7906 char *parse_error = 0;
7908 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7910 for (i = 0; i < nargs; i++) {
7911 args[i].raw = (U_CHAR *) "";
7912 args[i].expanded = 0;
7913 args[i].raw_length = args[i].expand_length
7914 = args[i].stringified_length = 0;
7915 args[i].free1 = args[i].free2 = 0;
7916 args[i].use_count = 0;
7919 /* Parse all the macro args that are supplied. I counts them.
7920 The first NARGS args are stored in ARGS.
7921 The rest are discarded.
7922 If rest_args is set then we assume macarg absorbed the rest of the args.
7924 i = 0;
7925 rest_args = 0;
7926 do {
7927 /* Discard the open-parenthesis or comma before the next arg. */
7928 ++instack[indepth].bufp;
7929 if (rest_args)
7930 continue;
7931 if (i < nargs || (nargs == 0 && i == 0)) {
7932 /* If we are working on last arg which absorbs rest of args... */
7933 if (i == nargs - 1 && defn->rest_args)
7934 rest_args = 1;
7935 parse_error = macarg (&args[i], rest_args);
7937 else
7938 parse_error = macarg (NULL_PTR, 0);
7939 if (parse_error) {
7940 error_with_line (line_for_error (start_line), parse_error);
7941 break;
7943 i++;
7944 } while (*instack[indepth].bufp != ')');
7946 /* If we got one arg but it was just whitespace, call that 0 args. */
7947 if (i == 1) {
7948 register U_CHAR *bp = args[0].raw;
7949 register U_CHAR *lim = bp + args[0].raw_length;
7950 /* cpp.texi says for foo ( ) we provide one argument.
7951 However, if foo wants just 0 arguments, treat this as 0. */
7952 if (nargs == 0)
7953 while (bp != lim && is_space[*bp]) bp++;
7954 if (bp == lim)
7955 i = 0;
7958 /* Don't output an error message if we have already output one for
7959 a parse error above. */
7960 rest_zero = 0;
7961 if (nargs == 0 && i > 0) {
7962 if (! parse_error)
7963 error ("arguments given to macro `%s'", hp->name);
7964 } else if (i < nargs) {
7965 /* traditional C allows foo() if foo wants one argument. */
7966 if (nargs == 1 && i == 0 && traditional)
7968 /* the rest args token is allowed to absorb 0 tokens */
7969 else if (i == nargs - 1 && defn->rest_args)
7970 rest_zero = 1;
7971 else if (parse_error)
7973 else if (i == 0)
7974 error ("macro `%s' used without args", hp->name);
7975 else if (i == 1)
7976 error ("macro `%s' used with just one arg", hp->name);
7977 else
7978 error ("macro `%s' used with only %d args", hp->name, i);
7979 } else if (i > nargs) {
7980 if (! parse_error)
7981 error ("macro `%s' used with too many (%d) args", hp->name, i);
7984 /* Swallow the closeparen. */
7985 ++instack[indepth].bufp;
7987 /* If macro wants zero args, we parsed the arglist for checking only.
7988 Read directly from the macro definition. */
7989 if (nargs == 0) {
7990 xbuf = defn->expansion;
7991 xbuf_len = defn->length;
7992 } else {
7993 register U_CHAR *exp = defn->expansion;
7994 register int offset; /* offset in expansion,
7995 copied a piece at a time */
7996 register int totlen; /* total amount of exp buffer filled so far */
7998 register struct reflist *ap, *last_ap;
8000 /* Macro really takes args. Compute the expansion of this call. */
8002 /* Compute length in characters of the macro's expansion.
8003 Also count number of times each arg is used. */
8004 xbuf_len = defn->length;
8005 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8006 if (ap->stringify)
8007 xbuf_len += args[ap->argno].stringified_length;
8008 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8009 /* Add 4 for two newline-space markers to prevent
8010 token concatenation. */
8011 xbuf_len += args[ap->argno].raw_length + 4;
8012 else {
8013 /* We have an ordinary (expanded) occurrence of the arg.
8014 So compute its expansion, if we have not already. */
8015 if (args[ap->argno].expanded == 0) {
8016 FILE_BUF obuf;
8017 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8018 args[ap->argno].raw + args[ap->argno].raw_length,
8019 1, 0);
8021 args[ap->argno].expanded = obuf.buf;
8022 args[ap->argno].expand_length = obuf.length;
8023 args[ap->argno].free2 = obuf.buf;
8026 /* Add 4 for two newline-space markers to prevent
8027 token concatenation. */
8028 xbuf_len += args[ap->argno].expand_length + 4;
8030 if (args[ap->argno].use_count < 10)
8031 args[ap->argno].use_count++;
8034 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8036 /* Generate in XBUF the complete expansion
8037 with arguments substituted in.
8038 TOTLEN is the total size generated so far.
8039 OFFSET is the index in the definition
8040 of where we are copying from. */
8041 offset = totlen = 0;
8042 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8043 last_ap = ap, ap = ap->next) {
8044 register struct argdata *arg = &args[ap->argno];
8045 int count_before = totlen;
8047 /* Add chars to XBUF. */
8048 for (i = 0; i < ap->nchars; i++, offset++)
8049 xbuf[totlen++] = exp[offset];
8051 /* If followed by an empty rest arg with concatenation,
8052 delete the last run of nonwhite chars. */
8053 if (rest_zero && totlen > count_before
8054 && ((ap->rest_args && ap->raw_before != 0)
8055 || (last_ap != NULL && last_ap->rest_args
8056 && last_ap->raw_after != 0))) {
8057 /* Delete final whitespace. */
8058 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8059 totlen--;
8062 /* Delete the nonwhites before them. */
8063 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8064 totlen--;
8068 if (ap->stringify != 0) {
8069 int arglen = arg->raw_length;
8070 int escaped = 0;
8071 int in_string = 0;
8072 int c;
8073 i = 0;
8074 while (i < arglen
8075 && (c = arg->raw[i], is_space[c]))
8076 i++;
8077 while (i < arglen
8078 && (c = arg->raw[arglen - 1], is_space[c]))
8079 arglen--;
8080 if (!traditional)
8081 xbuf[totlen++] = '\"'; /* insert beginning quote */
8082 for (; i < arglen; i++) {
8083 c = arg->raw[i];
8085 /* Special markers Newline Space
8086 generate nothing for a stringified argument. */
8087 if (c == '\n' && arg->raw[i+1] != '\n') {
8088 i++;
8089 continue;
8092 /* Internal sequences of whitespace are replaced by one space
8093 except within an string or char token. */
8094 if (! in_string
8095 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8096 while (1) {
8097 /* Note that Newline Space does occur within whitespace
8098 sequences; consider it part of the sequence. */
8099 if (c == '\n' && is_space[arg->raw[i+1]])
8100 i += 2;
8101 else if (c != '\n' && is_space[c])
8102 i++;
8103 else break;
8104 c = arg->raw[i];
8106 i--;
8107 c = ' ';
8110 if (escaped)
8111 escaped = 0;
8112 else {
8113 if (c == '\\')
8114 escaped = 1;
8115 if (in_string) {
8116 if (c == in_string)
8117 in_string = 0;
8118 } else if (c == '\"' || c == '\'')
8119 in_string = c;
8122 /* Escape these chars */
8123 if (c == '\"' || (in_string && c == '\\'))
8124 xbuf[totlen++] = '\\';
8125 if (isprint (c))
8126 xbuf[totlen++] = c;
8127 else {
8128 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8129 totlen += 4;
8132 if (!traditional)
8133 xbuf[totlen++] = '\"'; /* insert ending quote */
8134 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8135 U_CHAR *p1 = arg->raw;
8136 U_CHAR *l1 = p1 + arg->raw_length;
8137 if (ap->raw_before != 0) {
8138 while (p1 != l1 && is_space[*p1]) p1++;
8139 while (p1 != l1 && is_idchar[*p1])
8140 xbuf[totlen++] = *p1++;
8141 /* Delete any no-reexpansion marker that follows
8142 an identifier at the beginning of the argument
8143 if the argument is concatenated with what precedes it. */
8144 if (p1[0] == '\n' && p1[1] == '-')
8145 p1 += 2;
8146 } else if (!traditional) {
8147 /* Ordinary expanded use of the argument.
8148 Put in newline-space markers to prevent token pasting. */
8149 xbuf[totlen++] = '\n';
8150 xbuf[totlen++] = ' ';
8152 if (ap->raw_after != 0) {
8153 /* Arg is concatenated after: delete trailing whitespace,
8154 whitespace markers, and no-reexpansion markers. */
8155 while (p1 != l1) {
8156 if (is_space[l1[-1]]) l1--;
8157 else if (l1[-1] == '-') {
8158 U_CHAR *p2 = l1 - 1;
8159 /* If a `-' is preceded by an odd number of newlines then it
8160 and the last newline are a no-reexpansion marker. */
8161 while (p2 != p1 && p2[-1] == '\n') p2--;
8162 if ((l1 - 1 - p2) & 1) {
8163 l1 -= 2;
8165 else break;
8167 else break;
8171 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8172 totlen += l1 - p1;
8173 if (!traditional && ap->raw_after == 0) {
8174 /* Ordinary expanded use of the argument.
8175 Put in newline-space markers to prevent token pasting. */
8176 xbuf[totlen++] = '\n';
8177 xbuf[totlen++] = ' ';
8179 } else {
8180 /* Ordinary expanded use of the argument.
8181 Put in newline-space markers to prevent token pasting. */
8182 if (!traditional) {
8183 xbuf[totlen++] = '\n';
8184 xbuf[totlen++] = ' ';
8186 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8187 arg->expand_length);
8188 totlen += arg->expand_length;
8189 if (!traditional) {
8190 xbuf[totlen++] = '\n';
8191 xbuf[totlen++] = ' ';
8193 /* If a macro argument with newlines is used multiple times,
8194 then only expand the newlines once. This avoids creating output
8195 lines which don't correspond to any input line, which confuses
8196 gdb and gcov. */
8197 if (arg->use_count > 1 && arg->newlines > 0) {
8198 /* Don't bother doing change_newlines for subsequent
8199 uses of arg. */
8200 arg->use_count = 1;
8201 arg->expand_length
8202 = change_newlines (arg->expanded, arg->expand_length);
8206 if (totlen > xbuf_len)
8207 abort ();
8210 /* If there is anything left of the definition after handling
8211 the arg list, copy that in too. */
8213 for (i = offset; i < defn->length; i++) {
8214 /* if we've reached the end of the macro */
8215 if (exp[i] == ')')
8216 rest_zero = 0;
8217 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8218 && last_ap->raw_after != 0))
8219 xbuf[totlen++] = exp[i];
8222 xbuf[totlen] = 0;
8223 xbuf_len = totlen;
8225 for (i = 0; i < nargs; i++) {
8226 if (args[i].free1 != 0)
8227 free (args[i].free1);
8228 if (args[i].free2 != 0)
8229 free (args[i].free2);
8232 } else {
8233 xbuf = defn->expansion;
8234 xbuf_len = defn->length;
8237 /* Now put the expansion on the input stack
8238 so our caller will commence reading from it. */
8240 register FILE_BUF *ip2;
8242 ip2 = &instack[++indepth];
8244 ip2->fname = 0;
8245 ip2->nominal_fname = 0;
8246 ip2->inc = 0;
8247 /* This may not be exactly correct, but will give much better error
8248 messages for nested macro calls than using a line number of zero. */
8249 ip2->lineno = start_line;
8250 ip2->buf = xbuf;
8251 ip2->length = xbuf_len;
8252 ip2->bufp = xbuf;
8253 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8254 ip2->macro = hp;
8255 ip2->if_stack = if_stack;
8256 ip2->system_header_p = 0;
8258 /* Recursive macro use sometimes works traditionally.
8259 #define foo(x,y) bar (x (y,0), y)
8260 foo (foo, baz) */
8262 if (!traditional)
8263 hp->type = T_DISABLED;
8267 /* Parse a macro argument and store the info on it into *ARGPTR.
8268 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8269 Return nonzero to indicate a syntax error. */
8271 static char *
8272 macarg (argptr, rest_args)
8273 register struct argdata *argptr;
8274 int rest_args;
8276 FILE_BUF *ip = &instack[indepth];
8277 int paren = 0;
8278 int newlines = 0;
8279 int comments = 0;
8280 char *result = 0;
8282 /* Try to parse as much of the argument as exists at this
8283 input stack level. */
8284 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8285 &paren, &newlines, &comments, rest_args);
8287 /* If we find the end of the argument at this level,
8288 set up *ARGPTR to point at it in the input stack. */
8289 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8290 && bp != ip->buf + ip->length) {
8291 if (argptr != 0) {
8292 argptr->raw = ip->bufp;
8293 argptr->raw_length = bp - ip->bufp;
8294 argptr->newlines = newlines;
8296 ip->bufp = bp;
8297 } else {
8298 /* This input stack level ends before the macro argument does.
8299 We must pop levels and keep parsing.
8300 Therefore, we must allocate a temporary buffer and copy
8301 the macro argument into it. */
8302 int bufsize = bp - ip->bufp;
8303 int extra = newlines;
8304 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8305 int final_start = 0;
8307 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8308 ip->bufp = bp;
8309 ip->lineno += newlines;
8311 while (bp == ip->buf + ip->length) {
8312 if (instack[indepth].macro == 0) {
8313 result = "unterminated macro call";
8314 break;
8316 ip->macro->type = T_MACRO;
8317 if (ip->free_ptr)
8318 free (ip->free_ptr);
8319 ip = &instack[--indepth];
8320 newlines = 0;
8321 comments = 0;
8322 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8323 &newlines, &comments, rest_args);
8324 final_start = bufsize;
8325 bufsize += bp - ip->bufp;
8326 extra += newlines;
8327 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8328 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8329 bp - ip->bufp);
8330 ip->bufp = bp;
8331 ip->lineno += newlines;
8334 /* Now, if arg is actually wanted, record its raw form,
8335 discarding comments and duplicating newlines in whatever
8336 part of it did not come from a macro expansion.
8337 EXTRA space has been preallocated for duplicating the newlines.
8338 FINAL_START is the index of the start of that part. */
8339 if (argptr != 0) {
8340 argptr->raw = buffer;
8341 argptr->raw_length = bufsize;
8342 argptr->free1 = buffer;
8343 argptr->newlines = newlines;
8344 if ((newlines || comments) && ip->fname != 0)
8345 argptr->raw_length
8346 = final_start +
8347 discard_comments (argptr->raw + final_start,
8348 argptr->raw_length - final_start,
8349 newlines);
8350 argptr->raw[argptr->raw_length] = 0;
8351 if (argptr->raw_length > bufsize + extra)
8352 abort ();
8356 /* If we are not discarding this argument,
8357 macroexpand it and compute its length as stringified.
8358 All this info goes into *ARGPTR. */
8360 if (argptr != 0) {
8361 register U_CHAR *buf, *lim;
8362 register int totlen;
8364 buf = argptr->raw;
8365 lim = buf + argptr->raw_length;
8367 while (buf != lim && is_space[*buf])
8368 buf++;
8369 while (buf != lim && is_space[lim[-1]])
8370 lim--;
8371 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8372 while (buf != lim) {
8373 register U_CHAR c = *buf++;
8374 totlen++;
8375 /* Internal sequences of whitespace are replaced by one space
8376 in most cases, but not always. So count all the whitespace
8377 in case we need to keep it all. */
8378 #if 0
8379 if (is_space[c])
8380 SKIP_ALL_WHITE_SPACE (buf);
8381 else
8382 #endif
8383 if (c == '\"' || c == '\\') /* escape these chars */
8384 totlen++;
8385 else if (!isprint (c))
8386 totlen += 3;
8388 argptr->stringified_length = totlen;
8390 return result;
8393 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8394 counting parens in *DEPTHPTR,
8395 and return if reach LIMIT
8396 or before a `)' that would make *DEPTHPTR negative
8397 or before a comma when *DEPTHPTR is zero.
8398 Single and double quotes are matched and termination
8399 is inhibited within them. Comments also inhibit it.
8400 Value returned is pointer to stopping place.
8402 Increment *NEWLINES each time a newline is passed.
8403 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8404 Set *COMMENTS to 1 if a comment is seen. */
8406 static U_CHAR *
8407 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8408 U_CHAR *start;
8409 register U_CHAR *limit;
8410 int *depthptr, *newlines, *comments;
8411 int rest_args;
8413 register U_CHAR *bp = start;
8415 while (bp < limit) {
8416 switch (*bp) {
8417 case '(':
8418 (*depthptr)++;
8419 break;
8420 case ')':
8421 if (--(*depthptr) < 0)
8422 return bp;
8423 break;
8424 case '\\':
8425 /* Traditionally, backslash makes following char not special. */
8426 if (bp + 1 < limit && traditional)
8428 bp++;
8429 /* But count source lines anyway. */
8430 if (*bp == '\n')
8431 ++*newlines;
8433 break;
8434 case '\n':
8435 ++*newlines;
8436 break;
8437 case '/':
8438 if (bp[1] == '\\' && bp[2] == '\n')
8439 newline_fix (bp + 1);
8440 if (bp[1] == '*') {
8441 *comments = 1;
8442 for (bp += 2; bp < limit; bp++) {
8443 if (*bp == '\n')
8444 ++*newlines;
8445 else if (*bp == '*') {
8446 if (bp[-1] == '/' && warn_comments)
8447 warning ("`/*' within comment");
8448 if (bp[1] == '\\' && bp[2] == '\n')
8449 newline_fix (bp + 1);
8450 if (bp[1] == '/') {
8451 bp++;
8452 break;
8456 } else if (bp[1] == '/' && cplusplus_comments) {
8457 *comments = 1;
8458 for (bp += 2; bp < limit; bp++) {
8459 if (*bp == '\n') {
8460 ++*newlines;
8461 if (bp[-1] != '\\')
8462 break;
8463 if (warn_comments)
8464 warning ("multiline `//' comment");
8468 break;
8469 case '\'':
8470 case '\"':
8472 int quotec;
8473 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8474 if (*bp == '\\') {
8475 bp++;
8476 if (*bp == '\n')
8477 ++*newlines;
8478 while (*bp == '\\' && bp[1] == '\n') {
8479 bp += 2;
8481 } else if (*bp == '\n') {
8482 ++*newlines;
8483 if (quotec == '\'')
8484 break;
8488 break;
8489 case ',':
8490 /* if we've returned to lowest level and we aren't absorbing all args */
8491 if ((*depthptr) == 0 && rest_args == 0)
8492 return bp;
8493 break;
8495 bp++;
8498 return bp;
8501 /* Discard comments and duplicate newlines
8502 in the string of length LENGTH at START,
8503 except inside of string constants.
8504 The string is copied into itself with its beginning staying fixed.
8506 NEWLINES is the number of newlines that must be duplicated.
8507 We assume that that much extra space is available past the end
8508 of the string. */
8510 static int
8511 discard_comments (start, length, newlines)
8512 U_CHAR *start;
8513 int length;
8514 int newlines;
8516 register U_CHAR *ibp;
8517 register U_CHAR *obp;
8518 register U_CHAR *limit;
8519 register int c;
8521 /* If we have newlines to duplicate, copy everything
8522 that many characters up. Then, in the second part,
8523 we will have room to insert the newlines
8524 while copying down.
8525 NEWLINES may actually be too large, because it counts
8526 newlines in string constants, and we don't duplicate those.
8527 But that does no harm. */
8528 if (newlines > 0) {
8529 ibp = start + length;
8530 obp = ibp + newlines;
8531 limit = start;
8532 while (limit != ibp)
8533 *--obp = *--ibp;
8536 ibp = start + newlines;
8537 limit = start + length + newlines;
8538 obp = start;
8540 while (ibp < limit) {
8541 *obp++ = c = *ibp++;
8542 switch (c) {
8543 case '\n':
8544 /* Duplicate the newline. */
8545 *obp++ = '\n';
8546 break;
8548 case '\\':
8549 if (*ibp == '\n') {
8550 obp--;
8551 ibp++;
8553 break;
8555 case '/':
8556 if (*ibp == '\\' && ibp[1] == '\n')
8557 newline_fix (ibp);
8558 /* Delete any comment. */
8559 if (cplusplus_comments && ibp[0] == '/') {
8560 /* Comments are equivalent to spaces. */
8561 obp[-1] = ' ';
8562 ibp++;
8563 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8564 ibp++;
8565 break;
8567 if (ibp[0] != '*' || ibp + 1 >= limit)
8568 break;
8569 /* Comments are equivalent to spaces.
8570 For -traditional, a comment is equivalent to nothing. */
8571 if (traditional)
8572 obp--;
8573 else
8574 obp[-1] = ' ';
8575 ibp++;
8576 while (ibp + 1 < limit) {
8577 if (ibp[0] == '*'
8578 && ibp[1] == '\\' && ibp[2] == '\n')
8579 newline_fix (ibp + 1);
8580 if (ibp[0] == '*' && ibp[1] == '/')
8581 break;
8582 ibp++;
8584 ibp += 2;
8585 break;
8587 case '\'':
8588 case '\"':
8589 /* Notice and skip strings, so that we don't
8590 think that comments start inside them,
8591 and so we don't duplicate newlines in them. */
8593 int quotec = c;
8594 while (ibp < limit) {
8595 *obp++ = c = *ibp++;
8596 if (c == quotec)
8597 break;
8598 if (c == '\n' && quotec == '\'')
8599 break;
8600 if (c == '\\' && ibp < limit) {
8601 while (*ibp == '\\' && ibp[1] == '\n')
8602 ibp += 2;
8603 *obp++ = *ibp++;
8607 break;
8611 return obp - start;
8614 /* Turn newlines to spaces in the string of length LENGTH at START,
8615 except inside of string constants.
8616 The string is copied into itself with its beginning staying fixed. */
8618 static int
8619 change_newlines (start, length)
8620 U_CHAR *start;
8621 int length;
8623 register U_CHAR *ibp;
8624 register U_CHAR *obp;
8625 register U_CHAR *limit;
8626 register int c;
8628 ibp = start;
8629 limit = start + length;
8630 obp = start;
8632 while (ibp < limit) {
8633 *obp++ = c = *ibp++;
8634 switch (c) {
8635 case '\n':
8636 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8637 string. Skip past the newline and its duplicate.
8638 Put a space in the output. */
8639 if (*ibp == '\n')
8641 ibp++;
8642 obp--;
8643 *obp++ = ' ';
8645 break;
8647 case '\'':
8648 case '\"':
8649 /* Notice and skip strings, so that we don't delete newlines in them. */
8651 int quotec = c;
8652 while (ibp < limit) {
8653 *obp++ = c = *ibp++;
8654 if (c == quotec)
8655 break;
8656 if (c == '\n' && quotec == '\'')
8657 break;
8660 break;
8664 return obp - start;
8667 /* my_strerror - return the descriptive text associated with an
8668 `errno' code. */
8670 char *
8671 my_strerror (errnum)
8672 int errnum;
8674 char *result;
8676 #ifndef VMS
8677 #ifndef HAVE_STRERROR
8678 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8679 #else
8680 result = strerror (errnum);
8681 #endif
8682 #else /* VMS */
8683 /* VAXCRTL's strerror() takes an optional second argument, which only
8684 matters when the first argument is EVMSERR. However, it's simplest
8685 just to pass it unconditionally. `vaxc$errno' is declared in
8686 <errno.h>, and maintained by the library in parallel with `errno'.
8687 We assume that caller's `errnum' either matches the last setting of
8688 `errno' by the library or else does not have the value `EVMSERR'. */
8690 result = strerror (errnum, vaxc$errno);
8691 #endif
8693 if (!result)
8694 result = "undocumented I/O error";
8696 return result;
8699 /* error - print error message and increment count of errors. */
8701 void
8702 error (PRINTF_ALIST (msg))
8703 PRINTF_DCL (msg)
8705 va_list args;
8707 VA_START (args, msg);
8708 verror (msg, args);
8709 va_end (args);
8712 static void
8713 verror (msg, args)
8714 char *msg;
8715 va_list args;
8717 int i;
8718 FILE_BUF *ip = NULL;
8720 print_containing_files ();
8722 for (i = indepth; i >= 0; i--)
8723 if (instack[i].fname != NULL) {
8724 ip = &instack[i];
8725 break;
8728 if (ip != NULL)
8729 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8730 vfprintf (stderr, msg, args);
8731 fprintf (stderr, "\n");
8732 errors++;
8735 /* Error including a message from `errno'. */
8737 static void
8738 error_from_errno (name)
8739 char *name;
8741 int i;
8742 FILE_BUF *ip = NULL;
8744 print_containing_files ();
8746 for (i = indepth; i >= 0; i--)
8747 if (instack[i].fname != NULL) {
8748 ip = &instack[i];
8749 break;
8752 if (ip != NULL)
8753 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8755 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8757 errors++;
8760 /* Print error message but don't count it. */
8762 void
8763 warning (PRINTF_ALIST (msg))
8764 PRINTF_DCL (msg)
8766 va_list args;
8768 VA_START (args, msg);
8769 vwarning (msg, args);
8770 va_end (args);
8773 static void
8774 vwarning (msg, args)
8775 char *msg;
8776 va_list args;
8778 int i;
8779 FILE_BUF *ip = NULL;
8781 if (inhibit_warnings)
8782 return;
8784 if (warnings_are_errors)
8785 errors++;
8787 print_containing_files ();
8789 for (i = indepth; i >= 0; i--)
8790 if (instack[i].fname != NULL) {
8791 ip = &instack[i];
8792 break;
8795 if (ip != NULL)
8796 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8797 fprintf (stderr, "warning: ");
8798 vfprintf (stderr, msg, args);
8799 fprintf (stderr, "\n");
8802 static void
8803 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8804 error_with_line (int line, PRINTF_ALIST (msg))
8805 #else
8806 error_with_line (line, PRINTF_ALIST (msg))
8807 int line;
8808 PRINTF_DCL (msg)
8809 #endif
8811 va_list args;
8813 VA_START (args, msg);
8814 verror_with_line (line, msg, args);
8815 va_end (args);
8818 static void
8819 verror_with_line (line, msg, args)
8820 int line;
8821 char *msg;
8822 va_list args;
8824 int i;
8825 FILE_BUF *ip = NULL;
8827 print_containing_files ();
8829 for (i = indepth; i >= 0; i--)
8830 if (instack[i].fname != NULL) {
8831 ip = &instack[i];
8832 break;
8835 if (ip != NULL)
8836 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8837 vfprintf (stderr, msg, args);
8838 fprintf (stderr, "\n");
8839 errors++;
8842 static void
8843 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8844 warning_with_line (int line, PRINTF_ALIST (msg))
8845 #else
8846 warning_with_line (line, PRINTF_ALIST (msg))
8847 int line;
8848 PRINTF_DCL (msg)
8849 #endif
8851 va_list args;
8853 VA_START (args, msg);
8854 vwarning_with_line (line, msg, args);
8855 va_end (args);
8858 static void
8859 vwarning_with_line (line, msg, args)
8860 int line;
8861 char *msg;
8862 va_list args;
8864 int i;
8865 FILE_BUF *ip = NULL;
8867 if (inhibit_warnings)
8868 return;
8870 if (warnings_are_errors)
8871 errors++;
8873 print_containing_files ();
8875 for (i = indepth; i >= 0; i--)
8876 if (instack[i].fname != NULL) {
8877 ip = &instack[i];
8878 break;
8881 if (ip != NULL)
8882 fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
8883 fprintf (stderr, "warning: ");
8884 vfprintf (stderr, msg, args);
8885 fprintf (stderr, "\n");
8888 /* Print an error message and maybe count it. */
8890 void
8891 pedwarn (PRINTF_ALIST (msg))
8892 PRINTF_DCL (msg)
8894 va_list args;
8896 VA_START (args, msg);
8897 if (pedantic_errors)
8898 verror (msg, args);
8899 else
8900 vwarning (msg, args);
8901 va_end (args);
8904 void
8905 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8906 pedwarn_with_line (int line, PRINTF_ALIST (msg))
8907 #else
8908 pedwarn_with_line (line, PRINTF_ALIST (msg))
8909 int line;
8910 PRINTF_DCL (msg)
8911 #endif
8913 va_list args;
8915 VA_START (args, msg);
8916 if (pedantic_errors)
8917 verror_with_line (line, msg, args);
8918 else
8919 vwarning_with_line (line, msg, args);
8920 va_end (args);
8923 /* Report a warning (or an error if pedantic_errors)
8924 giving specified file name and line number, not current. */
8926 static void
8927 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8928 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
8929 #else
8930 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
8931 char *file;
8932 int line;
8933 PRINTF_DCL (msg)
8934 #endif
8936 va_list args;
8938 if (!pedantic_errors && inhibit_warnings)
8939 return;
8940 if (file != NULL)
8941 fprintf (stderr, "%s:%d: ", file, line);
8942 if (pedantic_errors)
8943 errors++;
8944 if (!pedantic_errors)
8945 fprintf (stderr, "warning: ");
8946 VA_START (args, msg);
8947 vfprintf (stderr, msg, args);
8948 va_end (args);
8949 fprintf (stderr, "\n");
8952 /* Print the file names and line numbers of the #include
8953 directives which led to the current file. */
8955 static void
8956 print_containing_files ()
8958 FILE_BUF *ip = NULL;
8959 int i;
8960 int first = 1;
8962 /* If stack of files hasn't changed since we last printed
8963 this info, don't repeat it. */
8964 if (last_error_tick == input_file_stack_tick)
8965 return;
8967 for (i = indepth; i >= 0; i--)
8968 if (instack[i].fname != NULL) {
8969 ip = &instack[i];
8970 break;
8973 /* Give up if we don't find a source file. */
8974 if (ip == NULL)
8975 return;
8977 /* Find the other, outer source files. */
8978 for (i--; i >= 0; i--)
8979 if (instack[i].fname != NULL) {
8980 ip = &instack[i];
8981 if (first) {
8982 first = 0;
8983 fprintf (stderr, "In file included");
8984 } else {
8985 fprintf (stderr, ",\n ");
8988 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
8990 if (! first)
8991 fprintf (stderr, ":\n");
8993 /* Record we have printed the status as of this time. */
8994 last_error_tick = input_file_stack_tick;
8997 /* Return the line at which an error occurred.
8998 The error is not necessarily associated with the current spot
8999 in the input stack, so LINE says where. LINE will have been
9000 copied from ip->lineno for the current input level.
9001 If the current level is for a file, we return LINE.
9002 But if the current level is not for a file, LINE is meaningless.
9003 In that case, we return the lineno of the innermost file. */
9005 static int
9006 line_for_error (line)
9007 int line;
9009 int i;
9010 int line1 = line;
9012 for (i = indepth; i >= 0; ) {
9013 if (instack[i].fname != 0)
9014 return line1;
9015 i--;
9016 if (i < 0)
9017 return 0;
9018 line1 = instack[i].lineno;
9020 abort ();
9021 /*NOTREACHED*/
9022 return 0;
9026 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9028 * As things stand, nothing is ever placed in the output buffer to be
9029 * removed again except when it's KNOWN to be part of an identifier,
9030 * so flushing and moving down everything left, instead of expanding,
9031 * should work ok.
9034 /* You might think void was cleaner for the return type,
9035 but that would get type mismatch in check_expand in strict ANSI. */
9037 static int
9038 grow_outbuf (obuf, needed)
9039 register FILE_BUF *obuf;
9040 register int needed;
9042 register U_CHAR *p;
9043 int minsize;
9045 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9046 return 0;
9048 /* Make it at least twice as big as it is now. */
9049 obuf->length *= 2;
9050 /* Make it have at least 150% of the free space we will need. */
9051 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9052 if (minsize > obuf->length)
9053 obuf->length = minsize;
9055 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9056 memory_full ();
9058 obuf->bufp = p + (obuf->bufp - obuf->buf);
9059 obuf->buf = p;
9061 return 0;
9064 /* Symbol table for macro names and special symbols */
9067 * install a name in the main hash table, even if it is already there.
9068 * name stops with first non alphanumeric, except leading '#'.
9069 * caller must check against redefinition if that is desired.
9070 * delete_macro () removes things installed by install () in fifo order.
9071 * this is important because of the `defined' special symbol used
9072 * in #if, and also if pushdef/popdef directives are ever implemented.
9074 * If LEN is >= 0, it is the length of the name.
9075 * Otherwise, compute the length by scanning the entire name.
9077 * If HASH is >= 0, it is the precomputed hash code.
9078 * Otherwise, compute the hash code.
9081 static HASHNODE *
9082 install (name, len, type, value, hash)
9083 U_CHAR *name;
9084 int len;
9085 enum node_type type;
9086 char *value;
9087 int hash;
9089 register HASHNODE *hp;
9090 register int i, bucket;
9091 register U_CHAR *p, *q;
9093 if (len < 0) {
9094 p = name;
9095 while (is_idchar[*p])
9096 p++;
9097 len = p - name;
9100 if (hash < 0)
9101 hash = hashf (name, len, HASHSIZE);
9103 i = sizeof (HASHNODE) + len + 1;
9104 hp = (HASHNODE *) xmalloc (i);
9105 bucket = hash;
9106 hp->bucket_hdr = &hashtab[bucket];
9107 hp->next = hashtab[bucket];
9108 hashtab[bucket] = hp;
9109 hp->prev = NULL;
9110 if (hp->next != NULL)
9111 hp->next->prev = hp;
9112 hp->type = type;
9113 hp->length = len;
9114 hp->value.cpval = value;
9115 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9116 p = hp->name;
9117 q = name;
9118 for (i = 0; i < len; i++)
9119 *p++ = *q++;
9120 hp->name[len] = 0;
9121 return hp;
9125 * find the most recent hash node for name name (ending with first
9126 * non-identifier char) installed by install
9128 * If LEN is >= 0, it is the length of the name.
9129 * Otherwise, compute the length by scanning the entire name.
9131 * If HASH is >= 0, it is the precomputed hash code.
9132 * Otherwise, compute the hash code.
9135 HASHNODE *
9136 lookup (name, len, hash)
9137 U_CHAR *name;
9138 int len;
9139 int hash;
9141 register U_CHAR *bp;
9142 register HASHNODE *bucket;
9144 if (len < 0) {
9145 for (bp = name; is_idchar[*bp]; bp++) ;
9146 len = bp - name;
9149 if (hash < 0)
9150 hash = hashf (name, len, HASHSIZE);
9152 bucket = hashtab[hash];
9153 while (bucket) {
9154 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9155 return bucket;
9156 bucket = bucket->next;
9158 return NULL;
9162 * Delete a hash node. Some weirdness to free junk from macros.
9163 * More such weirdness will have to be added if you define more hash
9164 * types that need it.
9167 /* Note that the DEFINITION of a macro is removed from the hash table
9168 but its storage is not freed. This would be a storage leak
9169 except that it is not reasonable to keep undefining and redefining
9170 large numbers of macros many times.
9171 In any case, this is necessary, because a macro can be #undef'd
9172 in the middle of reading the arguments to a call to it.
9173 If #undef freed the DEFINITION, that would crash. */
9175 static void
9176 delete_macro (hp)
9177 HASHNODE *hp;
9180 if (hp->prev != NULL)
9181 hp->prev->next = hp->next;
9182 if (hp->next != NULL)
9183 hp->next->prev = hp->prev;
9185 /* Make sure that the bucket chain header that the deleted guy was
9186 on points to the right thing afterwards. */
9187 if (hp == *hp->bucket_hdr)
9188 *hp->bucket_hdr = hp->next;
9190 #if 0
9191 if (hp->type == T_MACRO) {
9192 DEFINITION *d = hp->value.defn;
9193 struct reflist *ap, *nextap;
9195 for (ap = d->pattern; ap != NULL; ap = nextap) {
9196 nextap = ap->next;
9197 free (ap);
9199 free (d);
9201 #endif
9202 free (hp);
9206 * return hash function on name. must be compatible with the one
9207 * computed a step at a time, elsewhere
9210 static int
9211 hashf (name, len, hashsize)
9212 register U_CHAR *name;
9213 register int len;
9214 int hashsize;
9216 register int r = 0;
9218 while (len--)
9219 r = HASHSTEP (r, *name++);
9221 return MAKE_POS (r) % hashsize;
9225 /* Dump the definition of a single macro HP to OF. */
9227 static void
9228 dump_single_macro (hp, of)
9229 register HASHNODE *hp;
9230 FILE *of;
9232 register DEFINITION *defn = hp->value.defn;
9233 struct reflist *ap;
9234 int offset;
9235 int concat;
9238 /* Print the definition of the macro HP. */
9240 fprintf (of, "#define %s", hp->name);
9242 if (defn->nargs >= 0) {
9243 int i;
9245 fprintf (of, "(");
9246 for (i = 0; i < defn->nargs; i++) {
9247 dump_arg_n (defn, i, of);
9248 if (i + 1 < defn->nargs)
9249 fprintf (of, ", ");
9251 fprintf (of, ")");
9254 fprintf (of, " ");
9256 offset = 0;
9257 concat = 0;
9258 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9259 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9260 offset += ap->nchars;
9261 if (!traditional) {
9262 if (ap->nchars != 0)
9263 concat = 0;
9264 if (ap->stringify) {
9265 switch (ap->stringify) {
9266 case SHARP_TOKEN: fprintf (of, "#"); break;
9267 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9268 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9269 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9270 default: abort ();
9273 if (ap->raw_before != 0) {
9274 if (concat) {
9275 switch (ap->raw_before) {
9276 case WHITE_SHARP_TOKEN:
9277 case WHITE_PERCENT_COLON_TOKEN:
9278 fprintf (of, " ");
9279 break;
9280 default:
9281 break;
9283 } else {
9284 switch (ap->raw_before) {
9285 case SHARP_TOKEN: fprintf (of, "##"); break;
9286 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9287 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9288 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9289 default: abort ();
9293 concat = 0;
9295 dump_arg_n (defn, ap->argno, of);
9296 if (!traditional && ap->raw_after != 0) {
9297 switch (ap->raw_after) {
9298 case SHARP_TOKEN: fprintf (of, "##"); break;
9299 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9300 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9301 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9302 default: abort ();
9304 concat = 1;
9307 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9308 fprintf (of, "\n");
9311 /* Dump all macro definitions as #defines to stdout. */
9313 static void
9314 dump_all_macros ()
9316 int bucket;
9318 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9319 register HASHNODE *hp;
9321 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9322 if (hp->type == T_MACRO)
9323 dump_single_macro (hp, stdout);
9328 /* Output to OF a substring of a macro definition.
9329 BASE is the beginning of the definition.
9330 Output characters START thru LENGTH.
9331 Unless traditional, discard newlines outside of strings, thus
9332 converting funny-space markers to ordinary spaces. */
9334 static void
9335 dump_defn_1 (base, start, length, of)
9336 U_CHAR *base;
9337 int start;
9338 int length;
9339 FILE *of;
9341 U_CHAR *p = base + start;
9342 U_CHAR *limit = base + start + length;
9344 if (traditional)
9345 fwrite (p, sizeof (*p), length, of);
9346 else {
9347 while (p < limit) {
9348 if (*p == '\"' || *p =='\'') {
9349 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9350 NULL_PTR, NULL_PTR);
9351 fwrite (p, sizeof (*p), p1 - p, of);
9352 p = p1;
9353 } else {
9354 if (*p != '\n')
9355 putc (*p, of);
9356 p++;
9362 /* Print the name of argument number ARGNUM of macro definition DEFN
9363 to OF.
9364 Recall that DEFN->args.argnames contains all the arg names
9365 concatenated in reverse order with comma-space in between. */
9367 static void
9368 dump_arg_n (defn, argnum, of)
9369 DEFINITION *defn;
9370 int argnum;
9371 FILE *of;
9373 register U_CHAR *p = defn->args.argnames;
9374 while (argnum + 1 < defn->nargs) {
9375 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9376 argnum++;
9379 while (*p && *p != ',') {
9380 putc (*p, of);
9381 p++;
9385 /* Initialize syntactic classifications of characters. */
9387 static void
9388 initialize_char_syntax ()
9390 register int i;
9393 * Set up is_idchar and is_idstart tables. These should be
9394 * faster than saying (is_alpha (c) || c == '_'), etc.
9395 * Set up these things before calling any routines tthat
9396 * refer to them.
9398 for (i = 'a'; i <= 'z'; i++) {
9399 is_idchar[i - 'a' + 'A'] = 1;
9400 is_idchar[i] = 1;
9401 is_idstart[i - 'a' + 'A'] = 1;
9402 is_idstart[i] = 1;
9404 for (i = '0'; i <= '9'; i++)
9405 is_idchar[i] = 1;
9406 is_idchar['_'] = 1;
9407 is_idstart['_'] = 1;
9408 is_idchar['$'] = 1;
9409 is_idstart['$'] = 1;
9411 /* horizontal space table */
9412 is_hor_space[' '] = 1;
9413 is_hor_space['\t'] = 1;
9414 is_hor_space['\v'] = 1;
9415 is_hor_space['\f'] = 1;
9416 is_hor_space['\r'] = 1;
9418 is_space[' '] = 1;
9419 is_space['\t'] = 1;
9420 is_space['\v'] = 1;
9421 is_space['\f'] = 1;
9422 is_space['\n'] = 1;
9423 is_space['\r'] = 1;
9425 char_name['\v'] = "vertical tab";
9426 char_name['\f'] = "formfeed";
9427 char_name['\r'] = "carriage return";
9430 /* Initialize the built-in macros. */
9432 static void
9433 initialize_builtins (inp, outp)
9434 FILE_BUF *inp;
9435 FILE_BUF *outp;
9437 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9438 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9439 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9440 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9441 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9442 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9443 #ifndef NO_BUILTIN_SIZE_TYPE
9444 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9445 #endif
9446 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9447 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9448 #endif
9449 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9450 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9451 NULL_PTR, -1);
9452 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9453 NULL_PTR, -1);
9454 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9455 NULL_PTR, -1);
9456 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9457 if (!traditional) {
9458 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9459 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9461 if (objc)
9462 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9463 /* This is supplied using a -D by the compiler driver
9464 so that it is present only when truly compiling with GNU C. */
9465 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9466 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9468 if (debug_output)
9470 char directive[2048];
9471 U_CHAR *udirective = (U_CHAR *) directive;
9472 register struct directive *dp = &directive_table[0];
9473 struct tm *timebuf = timestamp ();
9475 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9476 instack[0].nominal_fname);
9477 output_line_directive (inp, outp, 0, same_file);
9478 pass_thru_directive (udirective, &udirective[strlen (directive)],
9479 outp, dp);
9481 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9482 output_line_directive (inp, outp, 0, same_file);
9483 pass_thru_directive (udirective, &udirective[strlen (directive)],
9484 outp, dp);
9486 #ifndef NO_BUILTIN_SIZE_TYPE
9487 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9488 output_line_directive (inp, outp, 0, same_file);
9489 pass_thru_directive (udirective, &udirective[strlen (directive)],
9490 outp, dp);
9491 #endif
9493 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9494 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9495 output_line_directive (inp, outp, 0, same_file);
9496 pass_thru_directive (udirective, &udirective[strlen (directive)],
9497 outp, dp);
9498 #endif
9500 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9501 output_line_directive (inp, outp, 0, same_file);
9502 pass_thru_directive (udirective, &udirective[strlen (directive)],
9503 outp, dp);
9505 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9506 monthnames[timebuf->tm_mon],
9507 timebuf->tm_mday, timebuf->tm_year + 1900);
9508 output_line_directive (inp, outp, 0, same_file);
9509 pass_thru_directive (udirective, &udirective[strlen (directive)],
9510 outp, dp);
9512 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9513 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9514 output_line_directive (inp, outp, 0, same_file);
9515 pass_thru_directive (udirective, &udirective[strlen (directive)],
9516 outp, dp);
9518 if (!traditional)
9520 sprintf (directive, " __STDC__ 1");
9521 output_line_directive (inp, outp, 0, same_file);
9522 pass_thru_directive (udirective, &udirective[strlen (directive)],
9523 outp, dp);
9525 if (objc)
9527 sprintf (directive, " __OBJC__ 1");
9528 output_line_directive (inp, outp, 0, same_file);
9529 pass_thru_directive (udirective, &udirective[strlen (directive)],
9530 outp, dp);
9536 * process a given definition string, for initialization
9537 * If STR is just an identifier, define it with value 1.
9538 * If STR has anything after the identifier, then it should
9539 * be identifier=definition.
9542 static void
9543 make_definition (str, op)
9544 char *str;
9545 FILE_BUF *op;
9547 FILE_BUF *ip;
9548 struct directive *kt;
9549 U_CHAR *buf, *p;
9551 p = buf = (U_CHAR *) str;
9552 if (!is_idstart[*p]) {
9553 error ("malformed option `-D %s'", str);
9554 return;
9556 while (is_idchar[*++p])
9558 if (*p == '(') {
9559 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9561 if (*p++ != ')')
9562 p = (U_CHAR *) str; /* Error */
9564 if (*p == 0) {
9565 buf = (U_CHAR *) alloca (p - buf + 4);
9566 strcpy ((char *)buf, str);
9567 strcat ((char *)buf, " 1");
9568 } else if (*p != '=') {
9569 error ("malformed option `-D %s'", str);
9570 return;
9571 } else {
9572 U_CHAR *q;
9573 /* Copy the entire option so we can modify it. */
9574 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9575 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9576 /* Change the = to a space. */
9577 buf[p - (U_CHAR *) str] = ' ';
9578 /* Scan for any backslash-newline and remove it. */
9579 p++;
9580 q = &buf[p - (U_CHAR *) str];
9581 while (*p) {
9582 if (*p == '\"' || *p == '\'') {
9583 int unterminated = 0;
9584 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9585 NULL_PTR, NULL_PTR, &unterminated);
9586 if (unterminated)
9587 return;
9588 while (p != p1)
9589 if (*p == '\\' && p[1] == '\n')
9590 p += 2;
9591 else
9592 *q++ = *p++;
9593 } else if (*p == '\\' && p[1] == '\n')
9594 p += 2;
9595 /* Change newline chars into newline-markers. */
9596 else if (*p == '\n')
9598 *q++ = '\n';
9599 *q++ = '\n';
9600 p++;
9602 else
9603 *q++ = *p++;
9605 *q = 0;
9608 ip = &instack[++indepth];
9609 ip->nominal_fname = ip->fname = "*Initialization*";
9611 ip->buf = ip->bufp = buf;
9612 ip->length = strlen ((char *) buf);
9613 ip->lineno = 1;
9614 ip->macro = 0;
9615 ip->free_ptr = 0;
9616 ip->if_stack = if_stack;
9617 ip->system_header_p = 0;
9619 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9622 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9623 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9624 --indepth;
9627 /* JF, this does the work for the -U option */
9629 static void
9630 make_undef (str, op)
9631 char *str;
9632 FILE_BUF *op;
9634 FILE_BUF *ip;
9635 struct directive *kt;
9637 ip = &instack[++indepth];
9638 ip->nominal_fname = ip->fname = "*undef*";
9640 ip->buf = ip->bufp = (U_CHAR *) str;
9641 ip->length = strlen (str);
9642 ip->lineno = 1;
9643 ip->macro = 0;
9644 ip->free_ptr = 0;
9645 ip->if_stack = if_stack;
9646 ip->system_header_p = 0;
9648 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9651 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9652 --indepth;
9655 /* Process the string STR as if it appeared as the body of a #assert.
9656 OPTION is the option name for which STR was the argument. */
9658 static void
9659 make_assertion (option, str)
9660 char *option;
9661 char *str;
9663 FILE_BUF *ip;
9664 struct directive *kt;
9665 U_CHAR *buf, *p, *q;
9667 /* Copy the entire option so we can modify it. */
9668 buf = (U_CHAR *) alloca (strlen (str) + 1);
9669 strcpy ((char *) buf, str);
9670 /* Scan for any backslash-newline and remove it. */
9671 p = q = buf;
9672 while (*p) {
9673 if (*p == '\\' && p[1] == '\n')
9674 p += 2;
9675 else
9676 *q++ = *p++;
9678 *q = 0;
9680 p = buf;
9681 if (!is_idstart[*p]) {
9682 error ("malformed option `%s %s'", option, str);
9683 return;
9685 while (is_idchar[*++p])
9687 SKIP_WHITE_SPACE (p);
9688 if (! (*p == 0 || *p == '(')) {
9689 error ("malformed option `%s %s'", option, str);
9690 return;
9693 ip = &instack[++indepth];
9694 ip->nominal_fname = ip->fname = "*Initialization*";
9696 ip->buf = ip->bufp = buf;
9697 ip->length = strlen ((char *) buf);
9698 ip->lineno = 1;
9699 ip->macro = 0;
9700 ip->free_ptr = 0;
9701 ip->if_stack = if_stack;
9702 ip->system_header_p = 0;
9704 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9707 /* Pass NULL as output ptr to do_define since we KNOW it never does
9708 any output.... */
9709 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9710 --indepth;
9713 #ifndef DIR_SEPARATOR
9714 #define DIR_SEPARATOR '/'
9715 #endif
9717 /* The previous include prefix, if any, is PREV_FILE_NAME.
9718 Translate any pathnames with COMPONENT.
9719 Allocate a new include prefix whose name is the
9720 simplified concatenation of PREFIX and NAME,
9721 with a trailing / added if needed.
9722 But return 0 if the include prefix should be ignored,
9723 e.g. because it is a duplicate of PREV_FILE_NAME. */
9725 static struct file_name_list *
9726 new_include_prefix (prev_file_name, component, prefix, name)
9727 struct file_name_list *prev_file_name;
9728 char *component;
9729 char *prefix;
9730 char *name;
9732 if (name == 0)
9733 fatal ("Directory name missing after command line option");
9735 if (*name == 0)
9736 /* Ignore the empty string. */
9737 return 0;
9739 prefix = update_path (prefix, component);
9740 name = update_path (name, component);
9743 struct file_name_list *dir
9744 = ((struct file_name_list *)
9745 xmalloc (sizeof (struct file_name_list)
9746 + strlen (prefix) + strlen (name) + 2));
9747 size_t len;
9748 strcpy (dir->fname, prefix);
9749 strcat (dir->fname, name);
9750 len = simplify_filename (dir->fname);
9752 /* Convert directory name to a prefix. */
9753 if (dir->fname[len - 1] != DIR_SEPARATOR) {
9754 if (len == 1 && dir->fname[len - 1] == '.')
9755 len = 0;
9756 else
9757 dir->fname[len++] = DIR_SEPARATOR;
9758 dir->fname[len] = 0;
9761 /* Ignore a directory whose name matches the previous one. */
9762 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9763 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9764 if (!first_bracket_include)
9765 first_bracket_include = prev_file_name;
9766 free (dir);
9767 return 0;
9770 #ifndef VMS
9771 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
9773 /* Add a trailing "." if there is a filename. This increases the number
9774 of systems that can stat directories. We remove it below. */
9775 if (len != 0)
9777 dir->fname[len] = '.';
9778 dir->fname[len + 1] = 0;
9781 /* Ignore a nonexistent directory. */
9782 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9783 if (errno != ENOENT && errno != ENOTDIR)
9784 error_from_errno (dir->fname);
9785 free (dir);
9786 return 0;
9789 if (len != 0)
9790 dir->fname[len] = 0;
9792 /* Ignore a directory whose identity matches the previous one. */
9793 if (prev_file_name
9794 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9795 && prev_file_name->st.st_dev == dir->st.st_dev) {
9796 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9797 if (!first_bracket_include)
9798 first_bracket_include = prev_file_name;
9799 free (dir);
9800 return 0;
9802 #endif /* ! VMS */
9804 dir->next = 0;
9805 dir->c_system_include_path = 0;
9806 dir->got_name_map = 0;
9808 return dir;
9812 /* Append a chain of `struct file_name_list's
9813 to the end of the main include chain.
9814 FIRST is the beginning of the chain to append, and LAST is the end. */
9816 static void
9817 append_include_chain (first, last)
9818 struct file_name_list *first, *last;
9820 struct file_name_list *dir;
9822 if (!first || !last)
9823 return;
9825 if (include == 0)
9826 include = first;
9827 else
9828 last_include->next = first;
9830 if (first_bracket_include == 0)
9831 first_bracket_include = first;
9833 for (dir = first; ; dir = dir->next) {
9834 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9835 if (len > max_include_len)
9836 max_include_len = len;
9837 if (dir == last)
9838 break;
9841 last->next = NULL;
9842 last_include = last;
9845 /* Place into DST a representation of the file named SRC that is suitable
9846 for `make'. Do not null-terminate DST. Return its length. */
9847 static int
9848 quote_string_for_make (dst, src)
9849 char *dst;
9850 char *src;
9852 char *p = src;
9853 int i = 0;
9854 for (;;)
9856 char c = *p++;
9857 switch (c)
9859 case '\0':
9860 case ' ':
9861 case '\t':
9863 /* GNU make uses a weird quoting scheme for white space.
9864 A space or tab preceded by 2N+1 backslashes represents
9865 N backslashes followed by space; a space or tab
9866 preceded by 2N backslashes represents N backslashes at
9867 the end of a file name; and backslashes in other
9868 contexts should not be doubled. */
9869 char *q;
9870 for (q = p - 1; src < q && q[-1] == '\\'; q--)
9872 if (dst)
9873 dst[i] = '\\';
9874 i++;
9877 if (!c)
9878 return i;
9879 if (dst)
9880 dst[i] = '\\';
9881 i++;
9882 goto ordinary_char;
9884 case '$':
9885 if (dst)
9886 dst[i] = c;
9887 i++;
9888 /* Fall through. This can mishandle things like "$(" but
9889 there's no easy fix. */
9890 default:
9891 ordinary_char:
9892 /* This can mishandle characters in the string "\0\n%*?[\\~";
9893 exactly which chars are mishandled depends on the `make' version.
9894 We know of no portable solution for this;
9895 even GNU make 3.76.1 doesn't solve the problem entirely.
9896 (Also, '\0' is mishandled due to our calling conventions.) */
9897 if (dst)
9898 dst[i] = c;
9899 i++;
9900 break;
9906 /* Add output to `deps_buffer' for the -M switch.
9907 STRING points to the text to be output.
9908 SPACER is ':' for targets, ' ' for dependencies. */
9910 static void
9911 deps_output (string, spacer)
9912 char *string;
9913 int spacer;
9915 int size = quote_string_for_make ((char *) 0, string);
9917 if (size == 0)
9918 return;
9920 #ifndef MAX_OUTPUT_COLUMNS
9921 #define MAX_OUTPUT_COLUMNS 72
9922 #endif
9923 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9924 && 1 < deps_column) {
9925 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9926 deps_size += 4;
9927 deps_column = 1;
9928 if (spacer == ' ')
9929 spacer = 0;
9932 if (deps_size + size + 8 > deps_allocated_size) {
9933 deps_allocated_size = (deps_size + size + 50) * 2;
9934 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
9936 if (spacer == ' ') {
9937 deps_buffer[deps_size++] = ' ';
9938 deps_column++;
9940 quote_string_for_make (&deps_buffer[deps_size], string);
9941 deps_size += size;
9942 deps_column += size;
9943 if (spacer == ':') {
9944 deps_buffer[deps_size++] = ':';
9945 deps_column++;
9947 deps_buffer[deps_size] = 0;
9950 static void
9951 fatal (PRINTF_ALIST (msg))
9952 PRINTF_DCL (msg)
9954 va_list args;
9956 fprintf (stderr, "%s: ", progname);
9957 VA_START (args, msg);
9958 vfprintf (stderr, msg, args);
9959 va_end (args);
9960 fprintf (stderr, "\n");
9961 exit (FATAL_EXIT_CODE);
9964 /* More 'friendly' abort that prints the line and file.
9965 config.h can #define abort fancy_abort if you like that sort of thing. */
9967 void
9968 fancy_abort ()
9970 fatal ("Internal gcc abort.");
9973 static void
9974 perror_with_name (name)
9975 char *name;
9977 fprintf (stderr, "%s: ", progname);
9978 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9979 errors++;
9982 static void
9983 pfatal_with_name (name)
9984 char *name;
9986 perror_with_name (name);
9987 #ifdef VMS
9988 exit (vaxc$errno);
9989 #else
9990 exit (FATAL_EXIT_CODE);
9991 #endif
9994 /* Handler for SIGPIPE. */
9996 static void
9997 pipe_closed (signo)
9998 /* If this is missing, some compilers complain. */
9999 int signo;
10001 fatal ("output pipe has been closed");
10004 static void
10005 memory_full ()
10007 fatal ("Memory exhausted.");
10011 GENERIC_PTR
10012 xmalloc (size)
10013 size_t size;
10015 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10016 if (!ptr)
10017 memory_full ();
10018 return ptr;
10021 static GENERIC_PTR
10022 xrealloc (old, size)
10023 GENERIC_PTR old;
10024 size_t size;
10026 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10027 if (!ptr)
10028 memory_full ();
10029 return ptr;
10032 static GENERIC_PTR
10033 xcalloc (number, size)
10034 size_t number, size;
10036 register size_t total = number * size;
10037 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10038 if (!ptr)
10039 memory_full ();
10040 bzero (ptr, total);
10041 return ptr;
10044 static char *
10045 savestring (input)
10046 char *input;
10048 size_t size = strlen (input);
10049 char *output = xmalloc (size + 1);
10050 strcpy (output, input);
10051 return output;
10054 #ifdef VMS
10056 /* Under VMS we need to fix up the "include" specification filename so
10057 that everything following the 1st slash is changed into its correct
10058 VMS file specification. */
10060 static void
10061 hack_vms_include_specification (fname, vaxc_include)
10062 char *fname;
10063 int vaxc_include;
10065 register char *cp, *cp1, *cp2;
10066 int f, check_filename_before_returning;
10067 char Local[512];
10069 check_filename_before_returning = 0;
10071 cp = base_name (fname);
10074 * Check if we have a vax-c style '#include filename'
10075 * and add the missing .h
10077 if (vaxc_include && !index (cp,'.'))
10078 strcat (cp, ".h");
10080 cp2 = Local; /* initialize */
10082 /* We are trying to do a number of things here. First of all, we are
10083 trying to hammer the filenames into a standard format, such that later
10084 processing can handle them.
10086 If the file name contains something like [dir.], then it recognizes this
10087 as a root, and strips the ".]". Later processing will add whatever is
10088 needed to get things working properly.
10090 If no device is specified, then the first directory name is taken to be
10091 a device name (or a rooted logical). */
10093 /* See if we found that 1st slash */
10094 if (cp == 0) return; /* Nothing to do!!! */
10095 if (*cp != '/') return; /* Nothing to do!!! */
10096 /* Point to the UNIX filename part (which needs to be fixed!) */
10097 cp1 = cp+1;
10098 /* If the directory spec is not rooted, we can just copy
10099 the UNIX filename part and we are done */
10100 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10101 if (cp[-2] != '.') {
10103 * The VMS part ends in a `]', and the preceding character is not a `.'.
10104 * We strip the `]', and then splice the two parts of the name in the
10105 * usual way. Given the default locations for include files in cccp.c,
10106 * we will only use this code if the user specifies alternate locations
10107 * with the /include (-I) switch on the command line. */
10108 cp -= 1; /* Strip "]" */
10109 cp1--; /* backspace */
10110 } else {
10112 * The VMS part has a ".]" at the end, and this will not do. Later
10113 * processing will add a second directory spec, and this would be a syntax
10114 * error. Thus we strip the ".]", and thus merge the directory specs.
10115 * We also backspace cp1, so that it points to a '/'. This inhibits the
10116 * generation of the 000000 root directory spec (which does not belong here
10117 * in this case).
10119 cp -= 2; /* Strip ".]" */
10120 cp1--; }; /* backspace */
10121 } else {
10123 /* We drop in here if there is no VMS style directory specification yet.
10124 * If there is no device specification either, we make the first dir a
10125 * device and try that. If we do not do this, then we will be essentially
10126 * searching the users default directory (as if they did a #include "asdf.h").
10128 * Then all we need to do is to push a '[' into the output string. Later
10129 * processing will fill this in, and close the bracket.
10131 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10132 *cp2++ = '['; /* Open the directory specification */
10135 /* at this point we assume that we have the device spec, and (at least
10136 the opening "[" for a directory specification. We may have directories
10137 specified already */
10139 /* If there are no other slashes then the filename will be
10140 in the "root" directory. Otherwise, we need to add
10141 directory specifications. */
10142 if (index (cp1, '/') == 0) {
10143 /* Just add "000000]" as the directory string */
10144 strcpy (cp2, "000000]");
10145 cp2 += strlen (cp2);
10146 check_filename_before_returning = 1; /* we might need to fool with this later */
10147 } else {
10148 /* As long as there are still subdirectories to add, do them. */
10149 while (index (cp1, '/') != 0) {
10150 /* If this token is "." we can ignore it */
10151 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10152 cp1 += 2;
10153 continue;
10155 /* Add a subdirectory spec. Do not duplicate "." */
10156 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10157 *cp2++ = '.';
10158 /* If this is ".." then the spec becomes "-" */
10159 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10160 /* Add "-" and skip the ".." */
10161 *cp2++ = '-';
10162 cp1 += 3;
10163 continue;
10165 /* Copy the subdirectory */
10166 while (*cp1 != '/') *cp2++= *cp1++;
10167 cp1++; /* Skip the "/" */
10169 /* Close the directory specification */
10170 if (cp2[-1] == '.') /* no trailing periods */
10171 cp2--;
10172 *cp2++ = ']';
10174 /* Now add the filename */
10175 while (*cp1) *cp2++ = *cp1++;
10176 *cp2 = 0;
10177 /* Now append it to the original VMS spec. */
10178 strcpy (cp, Local);
10180 /* If we put a [000000] in the filename, try to open it first. If this fails,
10181 remove the [000000], and return that name. This provides flexibility
10182 to the user in that they can use both rooted and non-rooted logical names
10183 to point to the location of the file. */
10185 if (check_filename_before_returning) {
10186 f = open (fname, O_RDONLY, 0666);
10187 if (f >= 0) {
10188 /* The file name is OK as it is, so return it as is. */
10189 close (f);
10190 return;
10192 /* The filename did not work. Try to remove the [000000] from the name,
10193 and return it. */
10194 cp = index (fname, '[');
10195 cp2 = index (fname, ']') + 1;
10196 strcpy (cp, cp2); /* this gets rid of it */
10198 return;
10200 #endif /* VMS */
10202 #ifdef VMS
10204 /* The following wrapper functions supply additional arguments to the VMS
10205 I/O routines to optimize performance with file handling. The arguments
10206 are:
10207 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10208 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10209 "fop=tef"- Truncate unused portions of file when closing file.
10210 "shr=nil"- Disallow file sharing while file is open. */
10212 static FILE *
10213 VMS_freopen (fname, type, oldfile)
10214 char *fname;
10215 char *type;
10216 FILE *oldfile;
10218 #undef freopen /* Get back the real freopen routine. */
10219 if (strcmp (type, "w") == 0)
10220 return freopen (fname, type, oldfile,
10221 "mbc=16", "deq=64", "fop=tef", "shr=nil");
10222 return freopen (fname, type, oldfile, "mbc=16");
10225 static FILE *
10226 VMS_fopen (fname, type)
10227 char *fname;
10228 char *type;
10230 #undef fopen /* Get back the real fopen routine. */
10231 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10232 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10233 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10234 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10236 if (*type == 'w')
10237 return (*vmslib_fopen) (fname, type, "mbc=32",
10238 "deq=64", "fop=tef", "shr=nil");
10239 else
10240 return (*vmslib_fopen) (fname, type, "mbc=32");
10243 static int
10244 VMS_open (fname, flags, prot)
10245 char *fname;
10246 int flags;
10247 int prot;
10249 #undef open /* Get back the real open routine. */
10250 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10253 /* more VMS hackery */
10254 #include <fab.h>
10255 #include <nam.h>
10257 extern unsigned long sys$parse(), sys$search();
10259 /* Work around another library bug. If a file is located via a searchlist,
10260 and if the device it's on is not the same device as the one specified
10261 in the first element of that searchlist, then both stat() and fstat()
10262 will fail to return info about it. `errno' will be set to EVMSERR, and
10263 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10264 We can get around this by fully parsing the filename and then passing
10265 that absolute name to stat().
10267 Without this fix, we can end up failing to find header files, which is
10268 bad enough, but then compounding the problem by reporting the reason for
10269 failure as "normal successful completion." */
10271 #undef fstat /* Get back to the library version. */
10273 static int
10274 VMS_fstat (fd, statbuf)
10275 int fd;
10276 struct stat *statbuf;
10278 int result = fstat (fd, statbuf);
10280 if (result < 0)
10282 FILE *fp;
10283 char nambuf[NAM$C_MAXRSS+1];
10285 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10286 result = VMS_stat (nambuf, statbuf);
10287 /* No fclose(fp) here; that would close(fd) as well. */
10290 return result;
10293 static int
10294 VMS_stat (name, statbuf)
10295 const char *name;
10296 struct stat *statbuf;
10298 int result = stat (name, statbuf);
10300 if (result < 0)
10302 struct FAB fab;
10303 struct NAM nam;
10304 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for sys$parse */
10305 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for sys$search */
10307 fab = cc$rms_fab;
10308 fab.fab$l_fna = (char *) name;
10309 fab.fab$b_fns = (unsigned char) strlen (name);
10310 fab.fab$l_nam = (void *) &nam;
10311 nam = cc$rms_nam;
10312 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10313 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10314 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10315 if (sys$parse (&fab) & 1)
10317 if (sys$search (&fab) & 1)
10319 res_nam[nam.nam$b_rsl] = '\0';
10320 result = stat (res_nam, statbuf);
10322 /* Clean up searchlist context cached by the system. */
10323 nam.nam$b_nop = NAM$M_SYNCHK;
10324 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10325 (void) sys$parse (&fab);
10329 return result;
10331 #endif /* VMS */