* ropeimpl.h: Check __STL_PTHREADS instead of _PTHREADS.
[official-gcc.git] / gcc / cccp.c
blobf8877be99df9a5c0816bfa7c604b856e1d66d290
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-96, 1997 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "config.h"
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <ctype.h>
25 #include <stdio.h>
26 #include <signal.h>
28 #ifdef TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # if HAVE_SYS_TIME_H
33 # include <sys/time.h>
34 # else
35 # include <time.h>
36 #endif
37 #endif
39 #ifdef HAVE_SYS_RESOURCE_H
40 # include <sys/resource.h>
41 #endif
43 #if HAVE_FCNTL_H
44 # include <fcntl.h>
45 #endif
47 #if HAVE_LIMITS_H
48 # include <limits.h>
49 #endif
51 #if HAVE_UNISTD_H
52 # include <unistd.h>
53 #endif
55 #include <errno.h>
57 #if HAVE_STDLIB_H
58 # include <stdlib.h>
59 #endif
61 #ifdef HAVE_STRING_H
62 # include <string.h>
63 #else
64 # ifdef HAVE_STRINGS_H
65 # include <strings.h>
66 #endif
67 #endif
69 typedef unsigned char U_CHAR;
71 #include "gansidecl.h"
72 #include "pcp.h"
74 #ifdef NEED_DECLARATION_INDEX
75 extern char *index ();
76 #endif
78 #ifdef NEED_DECLARATION_RINDEX
79 extern char *rindex ();
80 #endif
82 #ifdef NEED_DECLARATION_GETENV
83 extern char *getenv ();
84 #endif
86 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
87 # define __attribute__(x)
88 #endif
90 #ifndef STANDARD_INCLUDE_DIR
91 # define STANDARD_INCLUDE_DIR "/usr/include"
92 #endif
94 /* By default, colon separates directories in a path. */
95 #ifndef PATH_SEPARATOR
96 # define PATH_SEPARATOR ':'
97 #endif
99 /* By default, the suffix for object files is ".o". */
100 #ifdef OBJECT_SUFFIX
101 # define HAVE_OBJECT_SUFFIX
102 #else
103 # define OBJECT_SUFFIX ".o"
104 #endif
106 #if defined (__STDC__) && defined (HAVE_VPRINTF)
107 # include <stdarg.h>
108 # define PRINTF_ALIST(msg) char *msg, ...
109 # define PRINTF_DCL(msg)
110 # define PRINTF_PROTO(ARGS, m, n) PROTO (ARGS) __attribute__ ((format (__printf__, m, n)))
111 #else
112 # include <varargs.h>
113 # define PRINTF_ALIST(msg) msg, va_alist
114 # define PRINTF_DCL(msg) char *msg; va_dcl
115 # define PRINTF_PROTO(ARGS, m, n) () __attribute__ ((format (__printf__, m, n)))
116 # define vfprintf(file, msg, args) \
118 char *a0 = va_arg(args, char *); \
119 char *a1 = va_arg(args, char *); \
120 char *a2 = va_arg(args, char *); \
121 char *a3 = va_arg(args, char *); \
122 fprintf (file, msg, a0, a1, a2, a3); \
124 #endif
126 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
127 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
128 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
130 /* VMS-specific definitions */
131 #ifdef VMS
132 #include <descrip.h>
133 #include <ssdef.h>
134 #include <syidef.h>
135 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
136 #define fopen(fname,mode) VMS_fopen (fname,mode)
137 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
138 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
139 static int VMS_fstat (), VMS_stat ();
140 static int VMS_open ();
141 static FILE *VMS_fopen ();
142 static FILE *VMS_freopen ();
143 static void hack_vms_include_specification ();
144 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
145 #define INO_T_HASH(a) 0
146 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
147 #endif /* VMS */
149 /* Windows does not natively support inodes, and neither does MSDOS. */
150 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
151 #define INO_T_EQ(a, b) 0
152 #endif
154 #ifndef O_RDONLY
155 #define O_RDONLY 0
156 #endif
158 #undef MIN
159 #undef MAX
160 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
161 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
163 /* Find the largest host integer type and set its size and type.
164 Watch out: on some crazy hosts `long' is shorter than `int'. */
166 #ifndef HOST_WIDE_INT
167 # if HAVE_INTTYPES_H
168 # include <inttypes.h>
169 # define HOST_WIDE_INT intmax_t
170 # else
171 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
172 # define HOST_WIDE_INT int
173 # else
174 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
175 # define HOST_WIDE_INT long
176 # else
177 # define HOST_WIDE_INT long long
178 # endif
179 # endif
180 # endif
181 #endif
183 #ifndef S_ISREG
184 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
185 #endif
187 #ifndef S_ISDIR
188 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
189 #endif
191 #ifndef INO_T_EQ
192 #define INO_T_EQ(a, b) ((a) == (b))
193 #endif
195 #ifndef INO_T_HASH
196 #define INO_T_HASH(a) (a)
197 #endif
199 #ifndef INCLUDE_LEN_FUDGE
200 #define INCLUDE_LEN_FUDGE 0
201 #endif
203 /* External declarations. */
205 extern char *version_string;
206 extern char *update_path PROTO((char *, char *));
207 #ifndef VMS
208 #ifndef HAVE_STRERROR
209 extern int sys_nerr;
210 extern char *sys_errlist[];
211 #else /* HAVE_STRERROR */
212 char *strerror ();
213 #endif
214 #else /* VMS */
215 char *strerror (int,...);
216 #endif
217 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
218 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
220 #ifndef errno
221 extern int errno;
222 #endif
224 /* Name under which this program was invoked. */
226 static char *progname;
228 /* Nonzero means use extra default include directories for C++. */
230 static int cplusplus;
232 /* Nonzero means handle cplusplus style comments */
234 static int cplusplus_comments;
236 /* Nonzero means handle #import, for objective C. */
238 static int objc;
240 /* Nonzero means this is an assembly file, and allow
241 unknown directives, which could be comments. */
243 static int lang_asm;
245 /* Current maximum length of directory names in the search path
246 for include files. (Altered as we get more of them.) */
248 static int max_include_len;
250 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
252 static int for_lint = 0;
254 /* Nonzero means copy comments into the output file. */
256 static int put_out_comments = 0;
258 /* Nonzero means don't process the ANSI trigraph sequences. */
260 static int no_trigraphs = 0;
262 /* Nonzero means print the names of included files rather than
263 the preprocessed output. 1 means just the #include "...",
264 2 means #include <...> as well. */
266 static int print_deps = 0;
268 /* Nonzero if missing .h files in -M output are assumed to be generated
269 files and not errors. */
271 static int print_deps_missing_files = 0;
273 /* Nonzero means print names of header files (-H). */
275 static int print_include_names = 0;
277 /* Nonzero means don't output line number information. */
279 static int no_line_directives;
281 /* Nonzero means output the text in failing conditionals,
282 inside #failed ... #endfailed. */
284 static int output_conditionals;
286 /* dump_only means inhibit output of the preprocessed text
287 and instead output the definitions of all user-defined
288 macros in a form suitable for use as input to cccp.
289 dump_names means pass #define and the macro name through to output.
290 dump_definitions means pass the whole definition (plus #define) through
293 static enum {dump_none, dump_only, dump_names, dump_definitions}
294 dump_macros = dump_none;
296 /* Nonzero means pass all #define and #undef directives which we actually
297 process through to the output stream. This feature is used primarily
298 to allow cc1 to record the #defines and #undefs for the sake of
299 debuggers which understand about preprocessor macros, but it may
300 also be useful with -E to figure out how symbols are defined, and
301 where they are defined. */
302 static int debug_output = 0;
304 /* Nonzero means pass #include lines through to the output,
305 even if they are ifdefed out. */
306 static int dump_includes;
308 /* Nonzero indicates special processing used by the pcp program. The
309 special effects of this mode are:
311 Inhibit all macro expansion, except those inside #if directives.
313 Process #define directives normally, and output their contents
314 to the output file.
316 Output preconditions to pcp_outfile indicating all the relevant
317 preconditions for use of this file in a later cpp run.
319 static FILE *pcp_outfile;
321 /* Nonzero means we are inside an IF during a -pcp run. In this mode
322 macro expansion is done, and preconditions are output for all macro
323 uses requiring them. */
324 static int pcp_inside_if;
326 /* Nonzero means never to include precompiled files.
327 This is 1 since there's no way now to make precompiled files,
328 so it's not worth testing for them. */
329 static int no_precomp = 1;
331 /* Nonzero means give all the error messages the ANSI standard requires. */
333 int pedantic;
335 /* Nonzero means try to make failure to fit ANSI C an error. */
337 static int pedantic_errors;
339 /* Nonzero means don't print warning messages. -w. */
341 static int inhibit_warnings = 0;
343 /* Nonzero means warn if slash-star appears in a slash-star comment,
344 or if newline-backslash appears in a slash-slash comment. */
346 static int warn_comments;
348 /* Nonzero means warn if a macro argument is (or would be)
349 stringified with -traditional. */
351 static int warn_stringify;
353 /* Nonzero means warn if there are any trigraphs. */
355 static int warn_trigraphs;
357 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
359 static int warn_undef;
361 /* Nonzero means warn if #import is used. */
363 static int warn_import = 1;
365 /* Nonzero means turn warnings into errors. */
367 static int warnings_are_errors;
369 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
371 int traditional;
373 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
375 int c89;
377 /* Nonzero causes output not to be done,
378 but directives such as #define that have side effects
379 are still obeyed. */
381 static int no_output;
383 /* Nonzero means we should look for header.gcc files that remap file names. */
384 static int remap;
386 /* Nonzero means this file was included with a -imacros or -include
387 command line and should not be recorded as an include file. */
389 static int no_record_file;
391 /* Nonzero means that we have finished processing the command line options.
392 This flag is used to decide whether or not to issue certain errors
393 and/or warnings. */
395 static int done_initializing = 0;
397 /* Line where a newline was first seen in a string constant. */
399 static int multiline_string_line = 0;
401 /* I/O buffer structure.
402 The `fname' field is nonzero for source files and #include files
403 and for the dummy text used for -D and -U.
404 It is zero for rescanning results of macro expansion
405 and for expanding macro arguments. */
406 #define INPUT_STACK_MAX 400
407 static struct file_buf {
408 char *fname;
409 /* Filename specified with #line directive. */
410 char *nominal_fname;
411 /* Include file description. */
412 struct include_file *inc;
413 /* Record where in the search path this file was found.
414 For #include_next. */
415 struct file_name_list *dir;
416 int lineno;
417 int length;
418 U_CHAR *buf;
419 U_CHAR *bufp;
420 /* Macro that this level is the expansion of.
421 Included so that we can reenable the macro
422 at the end of this level. */
423 struct hashnode *macro;
424 /* Value of if_stack at start of this file.
425 Used to prohibit unmatched #endif (etc) in an include file. */
426 struct if_stack *if_stack;
427 /* Object to be freed at end of input at this level. */
428 U_CHAR *free_ptr;
429 /* True if this is a system header file; see is_system_include. */
430 char system_header_p;
431 } instack[INPUT_STACK_MAX];
433 static int last_error_tick; /* Incremented each time we print it. */
434 static int input_file_stack_tick; /* Incremented when the status changes. */
436 /* Current nesting level of input sources.
437 `instack[indepth]' is the level currently being read. */
438 static int indepth = -1;
439 #define CHECK_DEPTH(code) \
440 if (indepth >= (INPUT_STACK_MAX - 1)) \
442 error_with_line (line_for_error (instack[indepth].lineno), \
443 "macro or `#include' recursion too deep"); \
444 code; \
447 /* Current depth in #include directives that use <...>. */
448 static int system_include_depth = 0;
450 typedef struct file_buf FILE_BUF;
452 /* The output buffer. Its LENGTH field is the amount of room allocated
453 for the buffer, not the number of chars actually present. To get
454 that, subtract outbuf.buf from outbuf.bufp. */
456 #define OUTBUF_SIZE 10 /* initial size of output buffer */
457 static FILE_BUF outbuf;
459 /* Grow output buffer OBUF points at
460 so it can hold at least NEEDED more chars. */
462 #define check_expand(OBUF, NEEDED) \
463 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
464 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
466 struct file_name_list
468 struct file_name_list *next;
469 /* If the following is 1, it is a C-language system include
470 directory. */
471 int c_system_include_path;
472 /* Mapping of file names for this directory. */
473 struct file_name_map *name_map;
474 /* Non-zero if name_map is valid. */
475 int got_name_map;
476 /* The include directory status. */
477 struct stat st;
478 /* The include prefix: "" denotes the working directory,
479 otherwise fname must end in '/'.
480 The actual size is dynamically allocated. */
481 char fname[1];
484 /* #include "file" looks in source file dir, then stack. */
485 /* #include <file> just looks in the stack. */
486 /* -I directories are added to the end, then the defaults are added. */
487 /* The */
488 static struct default_include {
489 char *fname; /* The name of the directory. */
490 char *component; /* The component containing the directory */
491 int cplusplus; /* Only look here if we're compiling C++. */
492 int cxx_aware; /* Includes in this directory don't need to
493 be wrapped in extern "C" when compiling
494 C++. */
495 } include_defaults_array[]
496 #ifdef INCLUDE_DEFAULTS
497 = INCLUDE_DEFAULTS;
498 #else
500 /* Pick up GNU C++ specific include files. */
501 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
502 { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
503 #ifdef CROSS_COMPILE
504 /* This is the dir for fixincludes. Put it just before
505 the files that we fix. */
506 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
507 /* For cross-compilation, this dir name is generated
508 automatically in Makefile.in. */
509 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
510 #ifdef TOOL_INCLUDE_DIR
511 /* This is another place that the target system's headers might be. */
512 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
513 #endif
514 #else /* not CROSS_COMPILE */
515 #ifdef LOCAL_INCLUDE_DIR
516 /* This should be /usr/local/include and should come before
517 the fixincludes-fixed header files. */
518 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
519 #endif
520 #ifdef TOOL_INCLUDE_DIR
521 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
522 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
523 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
524 #endif
525 /* This is the dir for fixincludes. Put it just before
526 the files that we fix. */
527 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
528 /* Some systems have an extra dir of include files. */
529 #ifdef SYSTEM_INCLUDE_DIR
530 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
531 #endif
532 #ifndef STANDARD_INCLUDE_COMPONENT
533 #define STANDARD_INCLUDE_COMPONENT 0
534 #endif
535 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
536 #endif /* not CROSS_COMPILE */
537 { 0, 0, 0, 0 }
539 #endif /* no INCLUDE_DEFAULTS */
541 /* The code looks at the defaults through this pointer, rather than through
542 the constant structure above. This pointer gets changed if an environment
543 variable specifies other defaults. */
544 static struct default_include *include_defaults = include_defaults_array;
546 static struct file_name_list *include = 0; /* First dir to search */
547 /* First dir to search for <file> */
548 /* This is the first element to use for #include <...>.
549 If it is 0, use the entire chain for such includes. */
550 static struct file_name_list *first_bracket_include = 0;
551 /* This is the first element in the chain that corresponds to
552 a directory of system header files. */
553 static struct file_name_list *first_system_include = 0;
554 static struct file_name_list *last_include = 0; /* Last in chain */
556 /* Chain of include directories to put at the end of the other chain. */
557 static struct file_name_list *after_include = 0;
558 static struct file_name_list *last_after_include = 0; /* Last in chain */
560 /* Chain to put at the start of the system include files. */
561 static struct file_name_list *before_system = 0;
562 static struct file_name_list *last_before_system = 0; /* Last in chain */
564 /* Directory prefix that should replace `/usr' in the standard
565 include file directories. */
566 static char *include_prefix;
568 /* Maintain and search list of included files. */
570 struct include_file {
571 struct include_file *next; /* for include_hashtab */
572 struct include_file *next_ino; /* for include_ino_hashtab */
573 char *fname;
574 /* If the following is the empty string, it means #pragma once
575 was seen in this include file, or #import was applied to the file.
576 Otherwise, if it is nonzero, it is a macro name.
577 Don't include the file again if that macro is defined. */
578 U_CHAR *control_macro;
579 /* Nonzero if the dependency on this include file has been output. */
580 int deps_output;
581 struct stat st;
584 /* Hash tables of files already included with #include or #import.
585 include_hashtab is by full name; include_ino_hashtab is by inode number. */
587 #define INCLUDE_HASHSIZE 61
588 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
589 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
591 /* Global list of strings read in from precompiled files. This list
592 is kept in the order the strings are read in, with new strings being
593 added at the end through stringlist_tailp. We use this list to output
594 the strings at the end of the run.
596 static STRINGDEF *stringlist;
597 static STRINGDEF **stringlist_tailp = &stringlist;
600 /* Structure returned by create_definition */
601 typedef struct macrodef MACRODEF;
602 struct macrodef
604 struct definition *defn;
605 U_CHAR *symnam;
606 int symlen;
609 enum sharp_token_type {
610 NO_SHARP_TOKEN = 0, /* token not present */
612 SHARP_TOKEN = '#', /* token spelled with # only */
613 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
615 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
616 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
619 /* Structure allocated for every #define. For a simple replacement
620 such as
621 #define foo bar ,
622 nargs = -1, the `pattern' list is null, and the expansion is just
623 the replacement text. Nargs = 0 means a functionlike macro with no args,
624 e.g.,
625 #define getchar() getc (stdin) .
626 When there are args, the expansion is the replacement text with the
627 args squashed out, and the reflist is a list describing how to
628 build the output from the input: e.g., "3 chars, then the 1st arg,
629 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
630 The chars here come from the expansion. Whatever is left of the
631 expansion after the last arg-occurrence is copied after that arg.
632 Note that the reflist can be arbitrarily long---
633 its length depends on the number of times the arguments appear in
634 the replacement text, not how many args there are. Example:
635 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
636 pattern list
637 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
638 where (x, y) means (nchars, argno). */
640 typedef struct definition DEFINITION;
641 struct definition {
642 int nargs;
643 int length; /* length of expansion string */
644 int predefined; /* True if the macro was builtin or */
645 /* came from the command line */
646 U_CHAR *expansion;
647 int line; /* Line number of definition */
648 char *file; /* File of definition */
649 char rest_args; /* Nonzero if last arg. absorbs the rest */
650 struct reflist {
651 struct reflist *next;
653 enum sharp_token_type stringify; /* set if a # operator before arg */
654 enum sharp_token_type raw_before; /* set if a ## operator before arg */
655 enum sharp_token_type raw_after; /* set if a ## operator after arg */
657 char rest_args; /* Nonzero if this arg. absorbs the rest */
658 int nchars; /* Number of literal chars to copy before
659 this arg occurrence. */
660 int argno; /* Number of arg to substitute (origin-0) */
661 } *pattern;
662 union {
663 /* Names of macro args, concatenated in reverse order
664 with comma-space between them.
665 The only use of this is that we warn on redefinition
666 if this differs between the old and new definitions. */
667 U_CHAR *argnames;
668 } args;
671 /* different kinds of things that can appear in the value field
672 of a hash node. Actually, this may be useless now. */
673 union hashval {
674 char *cpval;
675 DEFINITION *defn;
676 KEYDEF *keydef;
680 * special extension string that can be added to the last macro argument to
681 * allow it to absorb the "rest" of the arguments when expanded. Ex:
682 * #define wow(a, b...) process (b, a, b)
683 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
684 * { wow (one, two); } -> { process (two, one, two); }
685 * if this "rest_arg" is used with the concat token '##' and if it is not
686 * supplied then the token attached to with ## will not be outputted. Ex:
687 * #define wow (a, b...) process (b ## , a, ## b)
688 * { wow (1, 2); } -> { process (2, 1, 2); }
689 * { wow (one); } -> { process (one); {
691 static char rest_extension[] = "...";
692 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
694 /* The structure of a node in the hash table. The hash table
695 has entries for all tokens defined by #define directives (type T_MACRO),
696 plus some special tokens like __LINE__ (these each have their own
697 type, and the appropriate code is run when that type of node is seen.
698 It does not contain control words like "#define", which are recognized
699 by a separate piece of code. */
701 /* different flavors of hash nodes --- also used in keyword table */
702 enum node_type {
703 T_DEFINE = 1, /* the `#define' keyword */
704 T_INCLUDE, /* the `#include' keyword */
705 T_INCLUDE_NEXT, /* the `#include_next' keyword */
706 T_IMPORT, /* the `#import' keyword */
707 T_IFDEF, /* the `#ifdef' keyword */
708 T_IFNDEF, /* the `#ifndef' keyword */
709 T_IF, /* the `#if' keyword */
710 T_ELSE, /* `#else' */
711 T_PRAGMA, /* `#pragma' */
712 T_ELIF, /* `#elif' */
713 T_UNDEF, /* `#undef' */
714 T_LINE, /* `#line' */
715 T_ERROR, /* `#error' */
716 T_WARNING, /* `#warning' */
717 T_ENDIF, /* `#endif' */
718 T_SCCS, /* `#sccs', used on system V. */
719 T_IDENT, /* `#ident', used on system V. */
720 T_ASSERT, /* `#assert', taken from system V. */
721 T_UNASSERT, /* `#unassert', taken from system V. */
722 T_SPECLINE, /* special symbol `__LINE__' */
723 T_DATE, /* `__DATE__' */
724 T_FILE, /* `__FILE__' */
725 T_BASE_FILE, /* `__BASE_FILE__' */
726 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
727 T_VERSION, /* `__VERSION__' */
728 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
729 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
730 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
731 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
732 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
733 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
734 T_TIME, /* `__TIME__' */
735 T_CONST, /* Constant value, used by `__STDC__' */
736 T_MACRO, /* macro defined by `#define' */
737 T_DISABLED, /* macro temporarily turned off for rescan */
738 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
739 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
740 T_UNUSED /* Used for something not defined. */
743 struct hashnode {
744 struct hashnode *next; /* double links for easy deletion */
745 struct hashnode *prev;
746 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
747 chain is kept, in case the node is the head
748 of the chain and gets deleted. */
749 enum node_type type; /* type of special token */
750 int length; /* length of token, for quick comparison */
751 U_CHAR *name; /* the actual name */
752 union hashval value; /* pointer to expansion, or whatever */
755 typedef struct hashnode HASHNODE;
757 /* Some definitions for the hash table. The hash function MUST be
758 computed as shown in hashf () below. That is because the rescan
759 loop computes the hash value `on the fly' for most tokens,
760 in order to avoid the overhead of a lot of procedure calls to
761 the hashf () function. Hashf () only exists for the sake of
762 politeness, for use when speed isn't so important. */
764 #define HASHSIZE 1403
765 static HASHNODE *hashtab[HASHSIZE];
766 #define HASHSTEP(old, c) ((old << 2) + c)
767 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
769 /* Symbols to predefine. */
771 #ifdef CPP_PREDEFINES
772 static char *predefs = CPP_PREDEFINES;
773 #else
774 static char *predefs = "";
775 #endif
777 /* We let tm.h override the types used here, to handle trivial differences
778 such as the choice of unsigned int or long unsigned int for size_t.
779 When machines start needing nontrivial differences in the size type,
780 it would be best to do something here to figure out automatically
781 from other information what type to use. */
783 /* The string value for __SIZE_TYPE__. */
785 #ifndef SIZE_TYPE
786 #define SIZE_TYPE "long unsigned int"
787 #endif
789 /* The string value for __PTRDIFF_TYPE__. */
791 #ifndef PTRDIFF_TYPE
792 #define PTRDIFF_TYPE "long int"
793 #endif
795 /* The string value for __WCHAR_TYPE__. */
797 #ifndef WCHAR_TYPE
798 #define WCHAR_TYPE "int"
799 #endif
800 char * wchar_type = WCHAR_TYPE;
801 #undef WCHAR_TYPE
803 /* The string value for __USER_LABEL_PREFIX__ */
805 #ifndef USER_LABEL_PREFIX
806 #define USER_LABEL_PREFIX ""
807 #endif
809 /* The string value for __REGISTER_PREFIX__ */
811 #ifndef REGISTER_PREFIX
812 #define REGISTER_PREFIX ""
813 #endif
815 /* The string value for __IMMEDIATE_PREFIX__ */
817 #ifndef IMMEDIATE_PREFIX
818 #define IMMEDIATE_PREFIX ""
819 #endif
821 /* In the definition of a #assert name, this structure forms
822 a list of the individual values asserted.
823 Each value is itself a list of "tokens".
824 These are strings that are compared by name. */
826 struct tokenlist_list {
827 struct tokenlist_list *next;
828 struct arglist *tokens;
831 struct assertion_hashnode {
832 struct assertion_hashnode *next; /* double links for easy deletion */
833 struct assertion_hashnode *prev;
834 /* also, a back pointer to this node's hash
835 chain is kept, in case the node is the head
836 of the chain and gets deleted. */
837 struct assertion_hashnode **bucket_hdr;
838 int length; /* length of token, for quick comparison */
839 U_CHAR *name; /* the actual name */
840 /* List of token-sequences. */
841 struct tokenlist_list *value;
844 typedef struct assertion_hashnode ASSERTION_HASHNODE;
846 /* Some definitions for the hash table. The hash function MUST be
847 computed as shown in hashf below. That is because the rescan
848 loop computes the hash value `on the fly' for most tokens,
849 in order to avoid the overhead of a lot of procedure calls to
850 the hashf function. hashf only exists for the sake of
851 politeness, for use when speed isn't so important. */
853 #define ASSERTION_HASHSIZE 37
854 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
856 /* Nonzero means inhibit macroexpansion of what seem to be
857 assertion tests, in rescan. For #if. */
858 static int assertions_flag;
860 /* `struct directive' defines one #-directive, including how to handle it. */
862 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
864 struct directive {
865 int length; /* Length of name */
866 int (*func) DO_PROTO; /* Function to handle directive */
867 char *name; /* Name of directive */
868 enum node_type type; /* Code which describes which directive. */
871 #define IS_INCLUDE_DIRECTIVE_TYPE(t) (T_INCLUDE <= (t) && (t) <= T_IMPORT)
873 /* These functions are declared to return int instead of void since they
874 are going to be placed in the table and some old compilers have trouble with
875 pointers to functions returning void. */
877 static int do_assert DO_PROTO;
878 static int do_define DO_PROTO;
879 static int do_elif DO_PROTO;
880 static int do_else DO_PROTO;
881 static int do_endif DO_PROTO;
882 static int do_error DO_PROTO;
883 static int do_ident DO_PROTO;
884 static int do_if DO_PROTO;
885 static int do_include DO_PROTO;
886 static int do_line DO_PROTO;
887 static int do_pragma DO_PROTO;
888 #ifdef SCCS_DIRECTIVE
889 static int do_sccs DO_PROTO;
890 #endif
891 static int do_unassert DO_PROTO;
892 static int do_undef DO_PROTO;
893 static int do_warning DO_PROTO;
894 static int do_xifdef DO_PROTO;
896 /* Here is the actual list of #-directives, most-often-used first. */
898 static struct directive directive_table[] = {
899 { 6, do_define, "define", T_DEFINE},
900 { 2, do_if, "if", T_IF},
901 { 5, do_xifdef, "ifdef", T_IFDEF},
902 { 6, do_xifdef, "ifndef", T_IFNDEF},
903 { 5, do_endif, "endif", T_ENDIF},
904 { 4, do_else, "else", T_ELSE},
905 { 4, do_elif, "elif", T_ELIF},
906 { 4, do_line, "line", T_LINE},
907 { 7, do_include, "include", T_INCLUDE},
908 { 12, do_include, "include_next", T_INCLUDE_NEXT},
909 { 6, do_include, "import", T_IMPORT},
910 { 5, do_undef, "undef", T_UNDEF},
911 { 5, do_error, "error", T_ERROR},
912 { 7, do_warning, "warning", T_WARNING},
913 #ifdef SCCS_DIRECTIVE
914 { 4, do_sccs, "sccs", T_SCCS},
915 #endif
916 { 6, do_pragma, "pragma", T_PRAGMA},
917 { 5, do_ident, "ident", T_IDENT},
918 { 6, do_assert, "assert", T_ASSERT},
919 { 8, do_unassert, "unassert", T_UNASSERT},
920 { -1, 0, "", T_UNUSED},
923 /* When a directive handler is called,
924 this points to the # (or the : of the %:) that started the directive. */
925 U_CHAR *directive_start;
927 /* table to tell if char can be part of a C identifier. */
928 U_CHAR is_idchar[256];
929 /* table to tell if char can be first char of a c identifier. */
930 U_CHAR is_idstart[256];
931 /* table to tell if c is horizontal space. */
932 static U_CHAR is_hor_space[256];
933 /* table to tell if c is horizontal or vertical space. */
934 U_CHAR is_space[256];
935 /* names of some characters */
936 static char *char_name[256];
938 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
939 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
941 static int errors = 0; /* Error counter for exit code */
943 /* Name of output file, for error messages. */
944 static char *out_fname;
947 /* Stack of conditionals currently in progress
948 (including both successful and failing conditionals). */
950 struct if_stack {
951 struct if_stack *next; /* for chaining to the next stack frame */
952 char *fname; /* copied from input when frame is made */
953 int lineno; /* similarly */
954 int if_succeeded; /* true if a leg of this if-group
955 has been passed through rescan */
956 U_CHAR *control_macro; /* For #ifndef at start of file,
957 this is the macro name tested. */
958 enum node_type type; /* type of last directive seen in this group */
960 typedef struct if_stack IF_STACK_FRAME;
961 static IF_STACK_FRAME *if_stack = NULL;
963 /* Buffer of -M output. */
964 static char *deps_buffer;
966 /* Number of bytes allocated in above. */
967 static int deps_allocated_size;
969 /* Number of bytes used. */
970 static int deps_size;
972 /* Number of bytes since the last newline. */
973 static int deps_column;
975 /* Nonzero means -I- has been seen,
976 so don't look for #include "foo" the source-file directory. */
977 static int ignore_srcdir;
979 static int safe_read PROTO((int, char *, int));
980 static void safe_write PROTO((int, char *, int));
982 int main PROTO((int, char **));
984 static void path_include PROTO((char *));
986 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
988 static void trigraph_pcp PROTO((FILE_BUF *));
990 static void newline_fix PROTO((U_CHAR *));
991 static void name_newline_fix PROTO((U_CHAR *));
993 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
995 static void rescan PROTO((FILE_BUF *, int));
997 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
999 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1001 static struct tm *timestamp PROTO((void));
1002 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1004 static int is_system_include PROTO((char *));
1005 static char *base_name PROTO((char *));
1006 static int absolute_filename PROTO((char *));
1007 static size_t simplify_filename PROTO((char *));
1009 static char *read_filename_string PROTO((int, FILE *));
1010 static struct file_name_map *read_name_map PROTO((char *));
1011 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
1012 static char *remap_include_file PROTO((char *, struct file_name_list *));
1013 static int lookup_ino_include PROTO((struct include_file *));
1015 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
1016 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
1018 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
1019 static int check_preconditions PROTO((char *));
1020 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1021 static void pcstring_used PROTO((HASHNODE *));
1022 static void write_output PROTO((void));
1023 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1025 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1027 static int check_macro_name PROTO((U_CHAR *, char *));
1028 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1029 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1031 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1033 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1034 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1036 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1037 static void free_token_list PROTO((struct arglist *));
1039 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1040 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1041 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1043 static void do_once PROTO((void));
1045 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1046 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1047 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1048 static void validate_else PROTO((U_CHAR *, U_CHAR *));
1050 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1051 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1052 static char *quote_string PROTO((char *, char *));
1053 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1055 /* Last arg to output_line_directive. */
1056 enum file_change_code {same_file, enter_file, leave_file};
1057 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1059 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1061 struct argdata;
1062 static char *macarg PROTO((struct argdata *, int));
1064 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1066 static int discard_comments PROTO((U_CHAR *, int, int));
1068 static int change_newlines PROTO((U_CHAR *, int));
1070 char *my_strerror PROTO((int));
1071 void error PRINTF_PROTO_1((char *, ...));
1072 static void verror PROTO((char *, va_list));
1073 static void error_from_errno PROTO((char *));
1074 void warning PRINTF_PROTO_1((char *, ...));
1075 static void vwarning PROTO((char *, va_list));
1076 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1077 static void verror_with_line PROTO((int, char *, va_list));
1078 static void vwarning_with_line PROTO((int, char *, va_list));
1079 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1080 void pedwarn PRINTF_PROTO_1((char *, ...));
1081 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1082 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1084 static void print_containing_files PROTO((void));
1086 static int line_for_error PROTO((int));
1087 static int grow_outbuf PROTO((FILE_BUF *, int));
1089 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1090 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1091 static void delete_macro PROTO((HASHNODE *));
1092 static int hashf PROTO((U_CHAR *, int, int));
1094 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1095 static void dump_all_macros PROTO((void));
1096 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1097 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1099 static void initialize_char_syntax PROTO((void));
1100 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1102 static void make_definition PROTO((char *, FILE_BUF *));
1103 static void make_undef PROTO((char *, FILE_BUF *));
1105 static void make_assertion PROTO((char *, char *));
1107 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1108 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1110 static int quote_string_for_make PROTO((char *, char *));
1111 static void deps_output PROTO((char *, int));
1113 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1114 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1115 static void perror_with_name PROTO((char *));
1116 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1117 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1119 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1120 GENERIC_PTR xmalloc PROTO((size_t));
1121 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1122 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1123 static char *savestring PROTO((char *));
1125 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1126 retrying if necessary. If MAX_READ_LEN is defined, read at most
1127 that bytes at a time. Return a negative value if an error occurs,
1128 otherwise return the actual number of bytes read,
1129 which must be LEN unless end-of-file was reached. */
1131 static int
1132 safe_read (desc, ptr, len)
1133 int desc;
1134 char *ptr;
1135 int len;
1137 int left, rcount, nchars;
1139 left = len;
1140 while (left > 0) {
1141 rcount = left;
1142 #ifdef MAX_READ_LEN
1143 if (rcount > MAX_READ_LEN)
1144 rcount = MAX_READ_LEN;
1145 #endif
1146 nchars = read (desc, ptr, rcount);
1147 if (nchars < 0)
1149 #ifdef EINTR
1150 if (errno == EINTR)
1151 continue;
1152 #endif
1153 return nchars;
1155 if (nchars == 0)
1156 break;
1157 ptr += nchars;
1158 left -= nchars;
1160 return len - left;
1163 /* Write LEN bytes at PTR to descriptor DESC,
1164 retrying if necessary, and treating any real error as fatal.
1165 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1167 static void
1168 safe_write (desc, ptr, len)
1169 int desc;
1170 char *ptr;
1171 int len;
1173 int wcount, written;
1175 while (len > 0) {
1176 wcount = len;
1177 #ifdef MAX_WRITE_LEN
1178 if (wcount > MAX_WRITE_LEN)
1179 wcount = MAX_WRITE_LEN;
1180 #endif
1181 written = write (desc, ptr, wcount);
1182 if (written < 0)
1184 #ifdef EINTR
1185 if (errno == EINTR)
1186 continue;
1187 #endif
1188 pfatal_with_name (out_fname);
1190 ptr += written;
1191 len -= written;
1196 main (argc, argv)
1197 int argc;
1198 char **argv;
1200 struct stat st;
1201 char *in_fname;
1202 char *cp;
1203 int f, i;
1204 FILE_BUF *fp;
1205 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1206 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1207 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1208 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1209 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1211 /* Record the option used with each element of pend_assertions.
1212 This is preparation for supporting more than one option for making
1213 an assertion. */
1214 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1215 int inhibit_predefs = 0;
1216 int no_standard_includes = 0;
1217 int no_standard_cplusplus_includes = 0;
1218 int missing_newline = 0;
1220 /* Non-0 means don't output the preprocessed program. */
1221 int inhibit_output = 0;
1222 /* Non-0 means -v, so print the full set of include dirs. */
1223 int verbose = 0;
1225 /* File name which deps are being written to.
1226 This is 0 if deps are being written to stdout. */
1227 char *deps_file = 0;
1228 /* Fopen file mode to open deps_file with. */
1229 char *deps_mode = "a";
1230 /* Stream on which to print the dependency information. */
1231 FILE *deps_stream = 0;
1232 /* Target-name to write with the dependency information. */
1233 char *deps_target = 0;
1235 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1236 /* Get rid of any avoidable limit on stack size. */
1238 struct rlimit rlim;
1240 /* Set the stack limit huge so that alloca (particularly stringtab
1241 in dbxread.c) does not fail. */
1242 getrlimit (RLIMIT_STACK, &rlim);
1243 rlim.rlim_cur = rlim.rlim_max;
1244 setrlimit (RLIMIT_STACK, &rlim);
1246 #endif
1248 #ifdef SIGPIPE
1249 signal (SIGPIPE, pipe_closed);
1250 #endif
1252 progname = base_name (argv[0]);
1254 #ifdef VMS
1256 /* Remove extension from PROGNAME. */
1257 char *p;
1258 char *s = progname = savestring (progname);
1260 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1261 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1262 && (p[1] == 'e' || p[1] == 'E')
1263 && (p[2] == 'x' || p[2] == 'X')
1264 && (p[3] == 'e' || p[3] == 'E')
1265 && !p[4])
1266 *p = '\0';
1268 #endif
1270 in_fname = NULL;
1271 out_fname = NULL;
1273 /* Initialize is_idchar. */
1274 initialize_char_syntax ();
1276 no_line_directives = 0;
1277 no_trigraphs = 1;
1278 dump_macros = dump_none;
1279 no_output = 0;
1280 cplusplus = 0;
1281 cplusplus_comments = 1;
1283 bzero ((char *) pend_files, argc * sizeof (char *));
1284 bzero ((char *) pend_defs, argc * sizeof (char *));
1285 bzero ((char *) pend_undefs, argc * sizeof (char *));
1286 bzero ((char *) pend_assertions, argc * sizeof (char *));
1287 bzero ((char *) pend_includes, argc * sizeof (char *));
1289 /* Process switches and find input file name. */
1291 for (i = 1; i < argc; i++) {
1292 if (argv[i][0] != '-') {
1293 if (out_fname != NULL)
1294 fatal ("Usage: %s [switches] input output", argv[0]);
1295 else if (in_fname != NULL)
1296 out_fname = argv[i];
1297 else
1298 in_fname = argv[i];
1299 } else {
1300 switch (argv[i][1]) {
1302 case 'i':
1303 if (!strcmp (argv[i], "-include")) {
1304 if (i + 1 == argc)
1305 fatal ("Filename missing after `-include' option");
1306 else
1307 simplify_filename (pend_includes[i] = argv[++i]);
1309 if (!strcmp (argv[i], "-imacros")) {
1310 if (i + 1 == argc)
1311 fatal ("Filename missing after `-imacros' option");
1312 else
1313 simplify_filename (pend_files[i] = argv[++i]);
1315 if (!strcmp (argv[i], "-iprefix")) {
1316 if (i + 1 == argc)
1317 fatal ("Filename missing after `-iprefix' option");
1318 else
1319 include_prefix = argv[++i];
1321 if (!strcmp (argv[i], "-ifoutput")) {
1322 output_conditionals = 1;
1324 if (!strcmp (argv[i], "-isystem")) {
1325 struct file_name_list *dirtmp;
1327 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1328 "", argv[++i])))
1329 break;
1330 dirtmp->c_system_include_path = 1;
1332 if (before_system == 0)
1333 before_system = dirtmp;
1334 else
1335 last_before_system->next = dirtmp;
1336 last_before_system = dirtmp; /* Tail follows the last one */
1338 /* Add directory to end of path for includes,
1339 with the default prefix at the front of its name. */
1340 if (!strcmp (argv[i], "-iwithprefix")) {
1341 struct file_name_list *dirtmp;
1342 char *prefix;
1344 if (include_prefix != 0)
1345 prefix = include_prefix;
1346 else {
1347 prefix = savestring (GCC_INCLUDE_DIR);
1348 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1349 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1350 prefix[strlen (prefix) - 7] = 0;
1353 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1354 prefix, argv[++i])))
1355 break;
1357 if (after_include == 0)
1358 after_include = dirtmp;
1359 else
1360 last_after_include->next = dirtmp;
1361 last_after_include = dirtmp; /* Tail follows the last one */
1363 /* Add directory to main path for includes,
1364 with the default prefix at the front of its name. */
1365 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1366 struct file_name_list *dirtmp;
1367 char *prefix;
1369 if (include_prefix != 0)
1370 prefix = include_prefix;
1371 else {
1372 prefix = savestring (GCC_INCLUDE_DIR);
1373 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1374 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1375 prefix[strlen (prefix) - 7] = 0;
1378 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1379 append_include_chain (dirtmp, dirtmp);
1381 /* Add directory to end of path for includes. */
1382 if (!strcmp (argv[i], "-idirafter")) {
1383 struct file_name_list *dirtmp;
1385 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1386 "", argv[++i])))
1387 break;
1389 if (after_include == 0)
1390 after_include = dirtmp;
1391 else
1392 last_after_include->next = dirtmp;
1393 last_after_include = dirtmp; /* Tail follows the last one */
1395 break;
1397 case 'o':
1398 if (out_fname != NULL)
1399 fatal ("Output filename specified twice");
1400 if (i + 1 == argc)
1401 fatal ("Filename missing after -o option");
1402 out_fname = argv[++i];
1403 if (!strcmp (out_fname, "-"))
1404 out_fname = "";
1405 break;
1407 case 'p':
1408 if (!strcmp (argv[i], "-pedantic"))
1409 pedantic = 1;
1410 else if (!strcmp (argv[i], "-pedantic-errors")) {
1411 pedantic = 1;
1412 pedantic_errors = 1;
1413 } else if (!strcmp (argv[i], "-pcp")) {
1414 char *pcp_fname;
1415 if (i + 1 == argc)
1416 fatal ("Filename missing after -pcp option");
1417 pcp_fname = argv[++i];
1418 pcp_outfile
1419 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1420 ? fopen (pcp_fname, "w")
1421 : stdout);
1422 if (pcp_outfile == 0)
1423 pfatal_with_name (pcp_fname);
1424 no_precomp = 1;
1426 break;
1428 case 't':
1429 if (!strcmp (argv[i], "-traditional")) {
1430 traditional = 1;
1431 cplusplus_comments = 0;
1432 } else if (!strcmp (argv[i], "-trigraphs")) {
1433 no_trigraphs = 0;
1435 break;
1437 case 'l':
1438 if (! strcmp (argv[i], "-lang-c"))
1439 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1440 if (! strcmp (argv[i], "-lang-c89"))
1441 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1442 if (! strcmp (argv[i], "-lang-c++"))
1443 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1444 if (! strcmp (argv[i], "-lang-objc"))
1445 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1446 if (! strcmp (argv[i], "-lang-objc++"))
1447 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1448 if (! strcmp (argv[i], "-lang-asm"))
1449 lang_asm = 1;
1450 if (! strcmp (argv[i], "-lint"))
1451 for_lint = 1;
1452 break;
1454 case '+':
1455 cplusplus = 1, cplusplus_comments = 1;
1456 break;
1458 case 'w':
1459 inhibit_warnings = 1;
1460 break;
1462 case 'W':
1463 if (!strcmp (argv[i], "-Wtrigraphs"))
1464 warn_trigraphs = 1;
1465 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1466 warn_trigraphs = 0;
1467 else if (!strcmp (argv[i], "-Wcomment"))
1468 warn_comments = 1;
1469 else if (!strcmp (argv[i], "-Wno-comment"))
1470 warn_comments = 0;
1471 else if (!strcmp (argv[i], "-Wcomments"))
1472 warn_comments = 1;
1473 else if (!strcmp (argv[i], "-Wno-comments"))
1474 warn_comments = 0;
1475 else if (!strcmp (argv[i], "-Wtraditional"))
1476 warn_stringify = 1;
1477 else if (!strcmp (argv[i], "-Wno-traditional"))
1478 warn_stringify = 0;
1479 else if (!strcmp (argv[i], "-Wundef"))
1480 warn_undef = 1;
1481 else if (!strcmp (argv[i], "-Wno-undef"))
1482 warn_undef = 0;
1483 else if (!strcmp (argv[i], "-Wimport"))
1484 warn_import = 1;
1485 else if (!strcmp (argv[i], "-Wno-import"))
1486 warn_import = 0;
1487 else if (!strcmp (argv[i], "-Werror"))
1488 warnings_are_errors = 1;
1489 else if (!strcmp (argv[i], "-Wno-error"))
1490 warnings_are_errors = 0;
1491 else if (!strcmp (argv[i], "-Wall"))
1493 warn_trigraphs = 1;
1494 warn_comments = 1;
1496 break;
1498 case 'M':
1499 /* The style of the choices here is a bit mixed.
1500 The chosen scheme is a hybrid of keeping all options in one string
1501 and specifying each option in a separate argument:
1502 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1503 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1504 -M[M][G][D file]. This is awkward to handle in specs, and is not
1505 as extensible. */
1506 /* ??? -MG must be specified in addition to one of -M or -MM.
1507 This can be relaxed in the future without breaking anything.
1508 The converse isn't true. */
1510 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1511 if (!strcmp (argv[i], "-MG"))
1513 print_deps_missing_files = 1;
1514 break;
1516 if (!strcmp (argv[i], "-M"))
1517 print_deps = 2;
1518 else if (!strcmp (argv[i], "-MM"))
1519 print_deps = 1;
1520 else if (!strcmp (argv[i], "-MD"))
1521 print_deps = 2;
1522 else if (!strcmp (argv[i], "-MMD"))
1523 print_deps = 1;
1524 /* For -MD and -MMD options, write deps on file named by next arg. */
1525 if (!strcmp (argv[i], "-MD")
1526 || !strcmp (argv[i], "-MMD")) {
1527 if (i + 1 == argc)
1528 fatal ("Filename missing after %s option", argv[i]);
1529 i++;
1530 deps_file = argv[i];
1531 deps_mode = "w";
1532 } else {
1533 /* For -M and -MM, write deps on standard output
1534 and suppress the usual output. */
1535 deps_stream = stdout;
1536 inhibit_output = 1;
1538 break;
1540 case 'd':
1542 char *p = argv[i] + 2;
1543 char c;
1544 while ((c = *p++)) {
1545 /* Arg to -d specifies what parts of macros to dump */
1546 switch (c) {
1547 case 'M':
1548 dump_macros = dump_only;
1549 no_output = 1;
1550 break;
1551 case 'N':
1552 dump_macros = dump_names;
1553 break;
1554 case 'D':
1555 dump_macros = dump_definitions;
1556 break;
1557 case 'I':
1558 dump_includes = 1;
1559 break;
1563 break;
1565 case 'g':
1566 if (argv[i][2] == '3')
1567 debug_output = 1;
1568 break;
1570 case 'v':
1571 fprintf (stderr, "GNU CPP version %s", version_string);
1572 #ifdef TARGET_VERSION
1573 TARGET_VERSION;
1574 #endif
1575 fprintf (stderr, "\n");
1576 verbose = 1;
1577 break;
1579 case 'H':
1580 print_include_names = 1;
1581 break;
1583 case 'D':
1584 if (argv[i][2] != 0)
1585 pend_defs[i] = argv[i] + 2;
1586 else if (i + 1 == argc)
1587 fatal ("Macro name missing after -D option");
1588 else
1589 i++, pend_defs[i] = argv[i];
1590 break;
1592 case 'A':
1594 char *p;
1596 if (argv[i][2] != 0)
1597 p = argv[i] + 2;
1598 else if (i + 1 == argc)
1599 fatal ("Assertion missing after -A option");
1600 else
1601 p = argv[++i];
1603 if (!strcmp (p, "-")) {
1604 /* -A- eliminates all predefined macros and assertions.
1605 Let's include also any that were specified earlier
1606 on the command line. That way we can get rid of any
1607 that were passed automatically in from GCC. */
1608 int j;
1609 inhibit_predefs = 1;
1610 for (j = 0; j < i; j++)
1611 pend_defs[j] = pend_assertions[j] = 0;
1612 } else {
1613 pend_assertions[i] = p;
1614 pend_assertion_options[i] = "-A";
1617 break;
1619 case 'U': /* JF #undef something */
1620 if (argv[i][2] != 0)
1621 pend_undefs[i] = argv[i] + 2;
1622 else if (i + 1 == argc)
1623 fatal ("Macro name missing after -U option");
1624 else
1625 pend_undefs[i] = argv[i+1], i++;
1626 break;
1628 case 'C':
1629 put_out_comments = 1;
1630 break;
1632 case 'E': /* -E comes from cc -E; ignore it. */
1633 break;
1635 case 'P':
1636 no_line_directives = 1;
1637 break;
1639 case '$': /* Don't include $ in identifiers. */
1640 is_idchar['$'] = is_idstart['$'] = 0;
1641 break;
1643 case 'I': /* Add directory to path for includes. */
1645 struct file_name_list *dirtmp;
1647 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1648 ignore_srcdir = 1;
1649 /* Don't use any preceding -I directories for #include <...>. */
1650 first_bracket_include = 0;
1652 else {
1653 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1654 argv[i][2] ? argv[i] + 2 : argv[++i]);
1655 append_include_chain (dirtmp, dirtmp);
1658 break;
1660 case 'n':
1661 if (!strcmp (argv[i], "-nostdinc"))
1662 /* -nostdinc causes no default include directories.
1663 You must specify all include-file directories with -I. */
1664 no_standard_includes = 1;
1665 else if (!strcmp (argv[i], "-nostdinc++"))
1666 /* -nostdinc++ causes no default C++-specific include directories. */
1667 no_standard_cplusplus_includes = 1;
1668 else if (!strcmp (argv[i], "-noprecomp"))
1669 no_precomp = 1;
1670 break;
1672 case 'r':
1673 if (!strcmp (argv[i], "-remap"))
1674 remap = 1;
1675 break;
1677 case 'u':
1678 /* Sun compiler passes undocumented switch "-undef".
1679 Let's assume it means to inhibit the predefined symbols. */
1680 inhibit_predefs = 1;
1681 break;
1683 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1684 if (in_fname == NULL) {
1685 in_fname = "";
1686 break;
1687 } else if (out_fname == NULL) {
1688 out_fname = "";
1689 break;
1690 } /* else fall through into error */
1692 default:
1693 fatal ("Invalid option `%s'", argv[i]);
1698 /* Add dirs from CPATH after dirs from -I. */
1699 /* There seems to be confusion about what CPATH should do,
1700 so for the moment it is not documented. */
1701 /* Some people say that CPATH should replace the standard include dirs,
1702 but that seems pointless: it comes before them, so it overrides them
1703 anyway. */
1704 cp = getenv ("CPATH");
1705 if (cp && ! no_standard_includes)
1706 path_include (cp);
1708 /* Initialize output buffer */
1710 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1711 outbuf.bufp = outbuf.buf;
1712 outbuf.length = OUTBUF_SIZE;
1714 /* Do partial setup of input buffer for the sake of generating
1715 early #line directives (when -g is in effect). */
1717 fp = &instack[++indepth];
1718 if (in_fname == NULL)
1719 in_fname = "";
1720 fp->nominal_fname = fp->fname = in_fname;
1721 fp->lineno = 0;
1723 /* In C++, wchar_t is a distinct basic type, and we can expect
1724 __wchar_t to be defined by cc1plus. */
1725 if (cplusplus)
1726 wchar_type = "__wchar_t";
1728 /* Install __LINE__, etc. Must follow initialize_char_syntax
1729 and option processing. */
1730 initialize_builtins (fp, &outbuf);
1732 /* Do standard #defines and assertions
1733 that identify system and machine type. */
1735 if (!inhibit_predefs) {
1736 char *p = (char *) alloca (strlen (predefs) + 1);
1738 #ifdef VMS
1739 struct dsc$descriptor_s lcl_name;
1740 struct item_list {
1741 unsigned short length; /* input length */
1742 unsigned short code; /* item code */
1743 unsigned long dptr; /* data ptr */
1744 unsigned long lptr; /* output length ptr */
1747 unsigned long syi_length;
1748 char syi_data[16];
1750 struct item_list items[] = {
1751 { 16, SYI$_VERSION, 0, 0 },
1752 { 0, 0, 0, 0 }
1755 items[0].dptr = (unsigned long)syi_data;
1756 items[0].lptr = (unsigned long)(&syi_length);
1758 if (SYS$GETSYIW (0, 0, 0, items, NULL, NULL, NULL, NULL) == SS$_NORMAL)
1760 unsigned long vms_version_value;
1761 char *vers;
1763 vers = syi_data;
1764 vms_version_value = 0;
1766 if (*vers == 'V')
1767 vers++;
1768 if (isdigit (*vers))
1770 vms_version_value = (*vers - '0') * 10000000;
1772 vers++;
1773 if (*vers == '.')
1775 vers++;
1776 if (isdigit (*vers))
1778 vms_version_value += (*vers - '0') * 100000;
1782 if (vms_version_value > 0)
1784 char versbuf[32];
1786 sprintf (versbuf, "__VMS_VER=%08ld", vms_version_value);
1787 if (debug_output)
1788 output_line_directive (fp, &outbuf, 0, same_file);
1789 make_definition (versbuf, &outbuf);
1792 #endif
1794 strcpy (p, predefs);
1795 while (*p) {
1796 char *q;
1797 while (*p == ' ' || *p == '\t')
1798 p++;
1799 /* Handle -D options. */
1800 if (p[0] == '-' && p[1] == 'D') {
1801 q = &p[2];
1802 while (*p && *p != ' ' && *p != '\t')
1803 p++;
1804 if (*p != 0)
1805 *p++= 0;
1806 if (debug_output)
1807 output_line_directive (fp, &outbuf, 0, same_file);
1808 make_definition (q, &outbuf);
1809 while (*p == ' ' || *p == '\t')
1810 p++;
1811 } else if (p[0] == '-' && p[1] == 'A') {
1812 /* Handle -A options (assertions). */
1813 char *assertion;
1814 char *past_name;
1815 char *value;
1816 char *past_value;
1817 char *termination;
1818 int save_char;
1820 assertion = &p[2];
1821 past_name = assertion;
1822 /* Locate end of name. */
1823 while (*past_name && *past_name != ' '
1824 && *past_name != '\t' && *past_name != '(')
1825 past_name++;
1826 /* Locate `(' at start of value. */
1827 value = past_name;
1828 while (*value && (*value == ' ' || *value == '\t'))
1829 value++;
1830 if (*value++ != '(')
1831 abort ();
1832 while (*value && (*value == ' ' || *value == '\t'))
1833 value++;
1834 past_value = value;
1835 /* Locate end of value. */
1836 while (*past_value && *past_value != ' '
1837 && *past_value != '\t' && *past_value != ')')
1838 past_value++;
1839 termination = past_value;
1840 while (*termination && (*termination == ' ' || *termination == '\t'))
1841 termination++;
1842 if (*termination++ != ')')
1843 abort ();
1844 if (*termination && *termination != ' ' && *termination != '\t')
1845 abort ();
1846 /* Temporarily null-terminate the value. */
1847 save_char = *termination;
1848 *termination = '\0';
1849 /* Install the assertion. */
1850 make_assertion ("-A", assertion);
1851 *termination = (char) save_char;
1852 p = termination;
1853 while (*p == ' ' || *p == '\t')
1854 p++;
1855 } else {
1856 abort ();
1861 /* Now handle the command line options. */
1863 /* Do -U's, -D's and -A's in the order they were seen. */
1864 for (i = 1; i < argc; i++) {
1865 if (pend_undefs[i]) {
1866 if (debug_output)
1867 output_line_directive (fp, &outbuf, 0, same_file);
1868 make_undef (pend_undefs[i], &outbuf);
1870 if (pend_defs[i]) {
1871 if (debug_output)
1872 output_line_directive (fp, &outbuf, 0, same_file);
1873 make_definition (pend_defs[i], &outbuf);
1875 if (pend_assertions[i])
1876 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1879 done_initializing = 1;
1881 { /* Read the appropriate environment variable and if it exists
1882 replace include_defaults with the listed path. */
1883 char *epath = 0;
1884 switch ((objc << 1) + cplusplus)
1886 case 0:
1887 epath = getenv ("C_INCLUDE_PATH");
1888 break;
1889 case 1:
1890 epath = getenv ("CPLUS_INCLUDE_PATH");
1891 break;
1892 case 2:
1893 epath = getenv ("OBJC_INCLUDE_PATH");
1894 break;
1895 case 3:
1896 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1897 break;
1899 /* If the environment var for this language is set,
1900 add to the default list of include directories. */
1901 if (epath) {
1902 int num_dirs;
1903 char *startp, *endp;
1905 for (num_dirs = 1, startp = epath; *startp; startp++)
1906 if (*startp == PATH_SEPARATOR)
1907 num_dirs++;
1908 include_defaults
1909 = (struct default_include *) xmalloc ((num_dirs
1910 * sizeof (struct default_include))
1911 + sizeof (include_defaults_array));
1912 startp = endp = epath;
1913 num_dirs = 0;
1914 while (1) {
1915 char c = *endp++;
1916 if (c == PATH_SEPARATOR || !c) {
1917 endp[-1] = 0;
1918 include_defaults[num_dirs].fname
1919 = startp == endp ? "." : savestring (startp);
1920 endp[-1] = c;
1921 include_defaults[num_dirs].component = 0;
1922 include_defaults[num_dirs].cplusplus = cplusplus;
1923 include_defaults[num_dirs].cxx_aware = 1;
1924 num_dirs++;
1925 if (!c)
1926 break;
1927 startp = endp;
1930 /* Put the usual defaults back in at the end. */
1931 bcopy ((char *) include_defaults_array,
1932 (char *) &include_defaults[num_dirs],
1933 sizeof (include_defaults_array));
1937 append_include_chain (before_system, last_before_system);
1938 first_system_include = before_system;
1940 /* Unless -fnostdinc,
1941 tack on the standard include file dirs to the specified list */
1942 if (!no_standard_includes) {
1943 struct default_include *p = include_defaults;
1944 char *specd_prefix = include_prefix;
1945 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1946 int default_len = 0;
1947 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1948 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1949 default_len = strlen (default_prefix) - 7;
1950 default_prefix[default_len] = 0;
1952 /* Search "translated" versions of GNU directories.
1953 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1954 if (specd_prefix != 0 && default_len != 0)
1955 for (p = include_defaults; p->fname; p++) {
1956 /* Some standard dirs are only for C++. */
1957 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1958 /* Does this dir start with the prefix? */
1959 if (!strncmp (p->fname, default_prefix, default_len)) {
1960 /* Yes; change prefix and add to search list. */
1961 struct file_name_list *new
1962 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1963 p->fname + default_len);
1964 if (new) {
1965 new->c_system_include_path = !p->cxx_aware;
1966 append_include_chain (new, new);
1967 if (first_system_include == 0)
1968 first_system_include = new;
1973 /* Search ordinary names for GNU include directories. */
1974 for (p = include_defaults; p->fname; p++) {
1975 /* Some standard dirs are only for C++. */
1976 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1977 struct file_name_list *new
1978 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1979 if (new) {
1980 new->c_system_include_path = !p->cxx_aware;
1981 append_include_chain (new, new);
1982 if (first_system_include == 0)
1983 first_system_include = new;
1989 /* Tack the after_include chain at the end of the include chain. */
1990 append_include_chain (after_include, last_after_include);
1991 if (first_system_include == 0)
1992 first_system_include = after_include;
1994 /* With -v, print the list of dirs to search. */
1995 if (verbose) {
1996 struct file_name_list *p;
1997 fprintf (stderr, "#include \"...\" search starts here:\n");
1998 for (p = include; p; p = p->next) {
1999 if (p == first_bracket_include)
2000 fprintf (stderr, "#include <...> search starts here:\n");
2001 if (!p->fname[0])
2002 fprintf (stderr, " .\n");
2003 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
2004 fprintf (stderr, " %s\n", p->fname);
2005 else
2006 /* Omit trailing '/'. */
2007 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
2009 fprintf (stderr, "End of search list.\n");
2012 /* -MG doesn't select the form of output and must be specified with one of
2013 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2014 inhibit compilation. */
2015 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2016 fatal ("-MG must be specified with one of -M or -MM");
2018 /* Either of two environment variables can specify output of deps.
2019 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2020 where OUTPUT_FILE is the file to write deps info to
2021 and DEPS_TARGET is the target to mention in the deps. */
2023 if (print_deps == 0
2024 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2025 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2026 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2027 char *s;
2028 char *output_file;
2030 if (spec == 0) {
2031 spec = getenv ("SUNPRO_DEPENDENCIES");
2032 print_deps = 2;
2034 else
2035 print_deps = 1;
2037 s = spec;
2038 /* Find the space before the DEPS_TARGET, if there is one. */
2039 /* This should use index. (mrs) */
2040 while (*s != 0 && *s != ' ') s++;
2041 if (*s != 0) {
2042 deps_target = s + 1;
2043 output_file = xmalloc (s - spec + 1);
2044 bcopy (spec, output_file, s - spec);
2045 output_file[s - spec] = 0;
2047 else {
2048 deps_target = 0;
2049 output_file = spec;
2052 deps_file = output_file;
2053 deps_mode = "a";
2056 /* For -M, print the expected object file name
2057 as the target of this Make-rule. */
2058 if (print_deps) {
2059 deps_allocated_size = 200;
2060 deps_buffer = xmalloc (deps_allocated_size);
2061 deps_buffer[0] = 0;
2062 deps_size = 0;
2063 deps_column = 0;
2065 if (deps_target) {
2066 deps_output (deps_target, ':');
2067 } else if (*in_fname == 0) {
2068 deps_output ("-", ':');
2069 } else {
2070 char *p, *q;
2071 int len;
2073 q = base_name (in_fname);
2075 /* Copy remainder to mungable area. */
2076 p = (char *) alloca (strlen(q) + 8);
2077 strcpy (p, q);
2079 /* Output P, but remove known suffixes. */
2080 len = strlen (p);
2081 q = p + len;
2082 if (len >= 2
2083 && p[len - 2] == '.'
2084 && index("cCsSm", p[len - 1]))
2085 q = p + (len - 2);
2086 else if (len >= 3
2087 && p[len - 3] == '.'
2088 && p[len - 2] == 'c'
2089 && p[len - 1] == 'c')
2090 q = p + (len - 3);
2091 else if (len >= 4
2092 && p[len - 4] == '.'
2093 && p[len - 3] == 'c'
2094 && p[len - 2] == 'x'
2095 && p[len - 1] == 'x')
2096 q = p + (len - 4);
2097 else if (len >= 4
2098 && p[len - 4] == '.'
2099 && p[len - 3] == 'c'
2100 && p[len - 2] == 'p'
2101 && p[len - 1] == 'p')
2102 q = p + (len - 4);
2104 /* Supply our own suffix. */
2105 strcpy (q, OBJECT_SUFFIX);
2107 deps_output (p, ':');
2108 deps_output (in_fname, ' ');
2112 /* Scan the -imacros files before the main input.
2113 Much like #including them, but with no_output set
2114 so that only their macro definitions matter. */
2116 no_output++; no_record_file++;
2117 for (i = 1; i < argc; i++)
2118 if (pend_files[i]) {
2119 struct include_file *inc;
2120 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2121 if (fd < 0) {
2122 perror_with_name (pend_files[i]);
2123 return FATAL_EXIT_CODE;
2125 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2127 no_output--; no_record_file--;
2129 /* Copy the entire contents of the main input file into
2130 the stacked input buffer previously allocated for it. */
2132 /* JF check for stdin */
2133 if (in_fname == NULL || *in_fname == 0) {
2134 in_fname = "";
2135 f = 0;
2136 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2137 goto perror;
2139 if (fstat (f, &st) != 0)
2140 pfatal_with_name (in_fname);
2141 fp->nominal_fname = fp->fname = in_fname;
2142 fp->lineno = 1;
2143 fp->system_header_p = 0;
2144 /* JF all this is mine about reading pipes and ttys */
2145 if (! S_ISREG (st.st_mode)) {
2146 /* Read input from a file that is not a normal disk file.
2147 We cannot preallocate a buffer with the correct size,
2148 so we must read in the file a piece at the time and make it bigger. */
2149 int size;
2150 int bsize;
2151 int cnt;
2153 if (S_ISDIR (st.st_mode))
2154 fatal ("Input file `%s' is a directory", in_fname);
2156 bsize = 2000;
2157 size = 0;
2158 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2159 for (;;) {
2160 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2161 if (cnt < 0) goto perror; /* error! */
2162 size += cnt;
2163 if (size != bsize) break; /* End of file */
2164 bsize *= 2;
2165 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2167 fp->length = size;
2168 } else {
2169 /* Read a file whose size we can determine in advance.
2170 For the sake of VMS, st.st_size is just an upper bound. */
2171 size_t s = (size_t) st.st_size;
2172 if (s != st.st_size || s + 2 < s)
2173 memory_full ();
2174 fp->buf = (U_CHAR *) xmalloc (s + 2);
2175 fp->length = safe_read (f, (char *) fp->buf, s);
2176 if (fp->length < 0) goto perror;
2178 fp->bufp = fp->buf;
2179 fp->if_stack = if_stack;
2181 /* Make sure data ends with a newline. And put a null after it. */
2183 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2184 /* Backslash-newline at end is not good enough. */
2185 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2186 fp->buf[fp->length++] = '\n';
2187 missing_newline = 1;
2189 fp->buf[fp->length] = '\0';
2191 /* Unless inhibited, convert trigraphs in the input. */
2193 if (!no_trigraphs)
2194 trigraph_pcp (fp);
2196 /* Now that we know the input file is valid, open the output. */
2198 if (!out_fname || !strcmp (out_fname, ""))
2199 out_fname = "stdout";
2200 else if (! freopen (out_fname, "w", stdout))
2201 pfatal_with_name (out_fname);
2203 output_line_directive (fp, &outbuf, 0, same_file);
2205 /* Scan the -include files before the main input. */
2207 no_record_file++;
2208 for (i = 1; i < argc; i++)
2209 if (pend_includes[i]) {
2210 struct include_file *inc;
2211 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2212 if (fd < 0) {
2213 perror_with_name (pend_includes[i]);
2214 return FATAL_EXIT_CODE;
2216 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2218 no_record_file--;
2220 /* Scan the input, processing macros and directives. */
2222 rescan (&outbuf, 0);
2224 if (missing_newline)
2225 fp->lineno--;
2227 if (pedantic && missing_newline)
2228 pedwarn ("file does not end in newline");
2230 /* Now we have processed the entire input
2231 Write whichever kind of output has been requested. */
2233 if (dump_macros == dump_only)
2234 dump_all_macros ();
2235 else if (! inhibit_output) {
2236 write_output ();
2239 if (print_deps) {
2240 /* Don't actually write the deps file if compilation has failed. */
2241 if (errors == 0) {
2242 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2243 pfatal_with_name (deps_file);
2244 fputs (deps_buffer, deps_stream);
2245 putc ('\n', deps_stream);
2246 if (deps_file) {
2247 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2248 fatal ("I/O error on output");
2253 if (pcp_outfile && pcp_outfile != stdout
2254 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2255 fatal ("I/O error on `-pcp' output");
2257 if (ferror (stdout) || fclose (stdout) != 0)
2258 fatal ("I/O error on output");
2260 if (errors)
2261 exit (FATAL_EXIT_CODE);
2262 exit (SUCCESS_EXIT_CODE);
2264 perror:
2265 pfatal_with_name (in_fname);
2266 return 0;
2269 /* Given a colon-separated list of file names PATH,
2270 add all the names to the search path for include files. */
2272 static void
2273 path_include (path)
2274 char *path;
2276 char *p;
2278 p = path;
2280 if (*p)
2281 while (1) {
2282 char *q = p;
2283 char c;
2284 struct file_name_list *dirtmp;
2286 /* Find the end of this name. */
2287 while ((c = *q++) != PATH_SEPARATOR && c)
2288 continue;
2290 q[-1] = 0;
2291 dirtmp = new_include_prefix (last_include, NULL_PTR,
2292 "", p == q ? "." : p);
2293 q[-1] = c;
2294 append_include_chain (dirtmp, dirtmp);
2296 /* Advance past this name. */
2297 p = q;
2298 if (! c)
2299 break;
2303 /* Return the address of the first character in S that equals C.
2304 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2305 Return 0 if there is no such character. Assume that C itself is not '\0'.
2306 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2307 but unfortunately memchr isn't autoconfigured yet. */
2309 static U_CHAR *
2310 index0 (s, c, n)
2311 U_CHAR *s;
2312 int c;
2313 size_t n;
2315 char *p = (char *) s;
2316 for (;;) {
2317 char *q = index (p, c);
2318 if (q)
2319 return (U_CHAR *) q;
2320 else {
2321 size_t l = strlen (p);
2322 if (l == n)
2323 return 0;
2324 l++;
2325 p += l;
2326 n -= l;
2331 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2332 before main CCCP processing. Name `pcp' is also in honor of the
2333 drugs the trigraph designers must have been on.
2335 Using an extra pass through the buffer takes a little extra time,
2336 but is infinitely less hairy than trying to handle trigraphs inside
2337 strings, etc. everywhere, and also makes sure that trigraphs are
2338 only translated in the top level of processing. */
2340 static void
2341 trigraph_pcp (buf)
2342 FILE_BUF *buf;
2344 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2345 int len;
2347 fptr = bptr = sptr = buf->buf;
2348 lptr = fptr + buf->length;
2349 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2350 if (*++sptr != '?')
2351 continue;
2352 switch (*++sptr) {
2353 case '=':
2354 c = '#';
2355 break;
2356 case '(':
2357 c = '[';
2358 break;
2359 case '/':
2360 c = '\\';
2361 break;
2362 case ')':
2363 c = ']';
2364 break;
2365 case '\'':
2366 c = '^';
2367 break;
2368 case '<':
2369 c = '{';
2370 break;
2371 case '!':
2372 c = '|';
2373 break;
2374 case '>':
2375 c = '}';
2376 break;
2377 case '-':
2378 c = '~';
2379 break;
2380 case '?':
2381 sptr--;
2382 continue;
2383 default:
2384 continue;
2386 len = sptr - fptr - 2;
2388 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2389 C, this will be memmove (). */
2390 if (bptr != fptr && len > 0)
2391 bcopy ((char *) fptr, (char *) bptr, len);
2393 bptr += len;
2394 *bptr++ = c;
2395 fptr = ++sptr;
2397 len = buf->length - (fptr - buf->buf);
2398 if (bptr != fptr && len > 0)
2399 bcopy ((char *) fptr, (char *) bptr, len);
2400 buf->length -= fptr - bptr;
2401 buf->buf[buf->length] = '\0';
2402 if (warn_trigraphs && fptr != bptr)
2403 warning_with_line (0, "%lu trigraph(s) encountered",
2404 (unsigned long) (fptr - bptr) / 2);
2407 /* Move all backslash-newline pairs out of embarrassing places.
2408 Exchange all such pairs following BP
2409 with any potentially-embarrassing characters that follow them.
2410 Potentially-embarrassing characters are / and *
2411 (because a backslash-newline inside a comment delimiter
2412 would cause it not to be recognized). */
2414 static void
2415 newline_fix (bp)
2416 U_CHAR *bp;
2418 register U_CHAR *p = bp;
2420 /* First count the backslash-newline pairs here. */
2422 while (p[0] == '\\' && p[1] == '\n')
2423 p += 2;
2425 /* What follows the backslash-newlines is not embarrassing. */
2427 if (*p != '/' && *p != '*')
2428 return;
2430 /* Copy all potentially embarrassing characters
2431 that follow the backslash-newline pairs
2432 down to where the pairs originally started. */
2434 while (*p == '*' || *p == '/')
2435 *bp++ = *p++;
2437 /* Now write the same number of pairs after the embarrassing chars. */
2438 while (bp < p) {
2439 *bp++ = '\\';
2440 *bp++ = '\n';
2444 /* Like newline_fix but for use within a directive-name.
2445 Move any backslash-newlines up past any following symbol constituents. */
2447 static void
2448 name_newline_fix (bp)
2449 U_CHAR *bp;
2451 register U_CHAR *p = bp;
2453 /* First count the backslash-newline pairs here. */
2454 while (p[0] == '\\' && p[1] == '\n')
2455 p += 2;
2457 /* What follows the backslash-newlines is not embarrassing. */
2459 if (!is_idchar[*p])
2460 return;
2462 /* Copy all potentially embarrassing characters
2463 that follow the backslash-newline pairs
2464 down to where the pairs originally started. */
2466 while (is_idchar[*p])
2467 *bp++ = *p++;
2469 /* Now write the same number of pairs after the embarrassing chars. */
2470 while (bp < p) {
2471 *bp++ = '\\';
2472 *bp++ = '\n';
2476 /* Look for lint commands in comments.
2478 When we come in here, ibp points into a comment. Limit is as one expects.
2479 scan within the comment -- it should start, after lwsp, with a lint command.
2480 If so that command is returned as a (constant) string.
2482 Upon return, any arg will be pointed to with argstart and will be
2483 arglen long. Note that we don't parse that arg since it will just
2484 be printed out again. */
2486 static char *
2487 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2488 register U_CHAR *ibp;
2489 register U_CHAR *limit;
2490 U_CHAR **argstart; /* point to command arg */
2491 int *arglen, *cmdlen; /* how long they are */
2493 HOST_WIDE_INT linsize;
2494 register U_CHAR *numptr; /* temp for arg parsing */
2496 *arglen = 0;
2498 SKIP_WHITE_SPACE (ibp);
2500 if (ibp >= limit) return NULL;
2502 linsize = limit - ibp;
2504 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2505 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2506 *cmdlen = 10;
2507 return "NOTREACHED";
2509 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2510 *cmdlen = 8;
2511 return "ARGSUSED";
2513 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2514 *cmdlen = 11;
2515 return "LINTLIBRARY";
2517 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2518 *cmdlen = 7;
2519 ibp += 7; linsize -= 7;
2520 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2522 /* OK, read a number */
2523 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2524 numptr++);
2525 *arglen = numptr - *argstart;
2526 return "VARARGS";
2528 return NULL;
2532 * The main loop of the program.
2534 * Read characters from the input stack, transferring them to the
2535 * output buffer OP.
2537 * Macros are expanded and push levels on the input stack.
2538 * At the end of such a level it is popped off and we keep reading.
2539 * At the end of any other kind of level, we return.
2540 * #-directives are handled, except within macros.
2542 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2543 * and insert them when appropriate. This is set while scanning macro
2544 * arguments before substitution. It is zero when scanning for final output.
2545 * There are three types of Newline markers:
2546 * * Newline - follows a macro name that was not expanded
2547 * because it appeared inside an expansion of the same macro.
2548 * This marker prevents future expansion of that identifier.
2549 * When the input is rescanned into the final output, these are deleted.
2550 * These are also deleted by ## concatenation.
2551 * * Newline Space (or Newline and any other whitespace character)
2552 * stands for a place that tokens must be separated or whitespace
2553 * is otherwise desirable, but where the ANSI standard specifies there
2554 * is no whitespace. This marker turns into a Space (or whichever other
2555 * whitespace char appears in the marker) in the final output,
2556 * but it turns into nothing in an argument that is stringified with #.
2557 * Such stringified arguments are the only place where the ANSI standard
2558 * specifies with precision that whitespace may not appear.
2560 * During this function, IP->bufp is kept cached in IBP for speed of access.
2561 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2562 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2563 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2564 * explicitly, and before RECACHE, since RECACHE uses OBP.
2567 static void
2568 rescan (op, output_marks)
2569 FILE_BUF *op;
2570 int output_marks;
2572 /* Character being scanned in main loop. */
2573 register U_CHAR c;
2575 /* Length of pending accumulated identifier. */
2576 register int ident_length = 0;
2578 /* Hash code of pending accumulated identifier. */
2579 register int hash = 0;
2581 /* Current input level (&instack[indepth]). */
2582 FILE_BUF *ip;
2584 /* Pointer for scanning input. */
2585 register U_CHAR *ibp;
2587 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2588 register U_CHAR *limit;
2590 /* Pointer for storing output. */
2591 register U_CHAR *obp;
2593 /* REDO_CHAR is nonzero if we are processing an identifier
2594 after backing up over the terminating character.
2595 Sometimes we process an identifier without backing up over
2596 the terminating character, if the terminating character
2597 is not special. Backing up is done so that the terminating character
2598 will be dispatched on again once the identifier is dealt with. */
2599 int redo_char = 0;
2601 /* 1 if within an identifier inside of which a concatenation
2602 marker (Newline -) has been seen. */
2603 int concatenated = 0;
2605 /* While scanning a comment or a string constant,
2606 this records the line it started on, for error messages. */
2607 int start_line;
2609 /* Record position of last `real' newline. */
2610 U_CHAR *beg_of_line;
2612 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2614 #define POPMACRO \
2615 do { ip->macro->type = T_MACRO; \
2616 if (ip->free_ptr) free (ip->free_ptr); \
2617 --indepth; } while (0)
2619 /* Reload `rescan's local variables that describe the current
2620 level of the input stack. */
2622 #define RECACHE \
2623 do { ip = &instack[indepth]; \
2624 ibp = ip->bufp; \
2625 limit = ip->buf + ip->length; \
2626 op->bufp = obp; \
2627 check_expand (op, limit - ibp); \
2628 beg_of_line = 0; \
2629 obp = op->bufp; } while (0)
2631 if (no_output && instack[indepth].fname != 0)
2632 skip_if_group (&instack[indepth], 1, NULL);
2634 obp = op->bufp;
2635 RECACHE;
2637 beg_of_line = ibp;
2639 /* Our caller must always put a null after the end of
2640 the input at each input stack level. */
2641 if (*limit != 0)
2642 abort ();
2644 while (1) {
2645 c = *ibp++;
2646 *obp++ = c;
2648 switch (c) {
2649 case '\\':
2650 if (*ibp == '\n' && !ip->macro) {
2651 /* At the top level, always merge lines ending with backslash-newline,
2652 even in middle of identifier. But do not merge lines in a macro,
2653 since backslash might be followed by a newline-space marker. */
2654 ++ibp;
2655 ++ip->lineno;
2656 --obp; /* remove backslash from obuf */
2657 break;
2659 /* If ANSI, backslash is just another character outside a string. */
2660 if (!traditional)
2661 goto randomchar;
2662 /* Otherwise, backslash suppresses specialness of following char,
2663 so copy it here to prevent the switch from seeing it.
2664 But first get any pending identifier processed. */
2665 if (ident_length > 0)
2666 goto specialchar;
2667 if (ibp < limit)
2668 *obp++ = *ibp++;
2669 break;
2671 case '%':
2672 if (ident_length || ip->macro || traditional)
2673 goto randomchar;
2674 while (*ibp == '\\' && ibp[1] == '\n') {
2675 ibp += 2;
2676 ++ip->lineno;
2678 if (*ibp != ':')
2679 break;
2680 /* Treat this %: digraph as if it were #. */
2681 /* Fall through. */
2683 case '#':
2684 if (assertions_flag) {
2685 if (ident_length)
2686 goto specialchar;
2687 /* Copy #foo (bar lose) without macro expansion. */
2688 obp[-1] = '#'; /* In case it was '%'. */
2689 SKIP_WHITE_SPACE (ibp);
2690 while (is_idchar[*ibp])
2691 *obp++ = *ibp++;
2692 SKIP_WHITE_SPACE (ibp);
2693 if (*ibp == '(') {
2694 ip->bufp = ibp;
2695 skip_paren_group (ip);
2696 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2697 obp += ip->bufp - ibp;
2698 ibp = ip->bufp;
2700 break;
2703 /* If this is expanding a macro definition, don't recognize
2704 preprocessing directives. */
2705 if (ip->macro != 0)
2706 goto randomchar;
2707 /* If this is expand_into_temp_buffer,
2708 don't recognize them either. Warn about them
2709 only after an actual newline at this level,
2710 not at the beginning of the input level. */
2711 if (! ip->fname) {
2712 if (ip->buf != beg_of_line)
2713 warning ("preprocessing directive not recognized within macro arg");
2714 goto randomchar;
2716 if (ident_length)
2717 goto specialchar;
2720 /* # keyword: a # must be first nonblank char on the line */
2721 if (beg_of_line == 0)
2722 goto randomchar;
2724 U_CHAR *bp;
2726 /* Scan from start of line, skipping whitespace, comments
2727 and backslash-newlines, and see if we reach this #.
2728 If not, this # is not special. */
2729 bp = beg_of_line;
2730 /* If -traditional, require # to be at beginning of line. */
2731 if (!traditional) {
2732 while (1) {
2733 if (is_hor_space[*bp])
2734 bp++;
2735 else if (*bp == '\\' && bp[1] == '\n')
2736 bp += 2;
2737 else if (*bp == '/' && bp[1] == '*') {
2738 bp += 2;
2739 while (!(*bp == '*' && bp[1] == '/'))
2740 bp++;
2741 bp += 2;
2743 /* There is no point in trying to deal with C++ // comments here,
2744 because if there is one, then this # must be part of the
2745 comment and we would never reach here. */
2746 else break;
2748 if (c == '%') {
2749 if (bp[0] != '%')
2750 break;
2751 while (bp[1] == '\\' && bp[2] == '\n')
2752 bp += 2;
2753 if (bp + 1 != ibp)
2754 break;
2755 /* %: appears at start of line; skip past the ':' too. */
2756 bp++;
2757 ibp++;
2760 if (bp + 1 != ibp)
2761 goto randomchar;
2764 /* This # can start a directive. */
2766 --obp; /* Don't copy the '#' */
2768 ip->bufp = ibp;
2769 op->bufp = obp;
2770 if (! handle_directive (ip, op)) {
2771 #ifdef USE_C_ALLOCA
2772 alloca (0);
2773 #endif
2774 /* Not a known directive: treat it as ordinary text.
2775 IP, OP, IBP, etc. have not been changed. */
2776 if (no_output && instack[indepth].fname) {
2777 /* If not generating expanded output,
2778 what we do with ordinary text is skip it.
2779 Discard everything until next # directive. */
2780 skip_if_group (&instack[indepth], 1, 0);
2781 RECACHE;
2782 beg_of_line = ibp;
2783 break;
2785 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2786 /* Don't expand an identifier that could be a macro directive.
2787 (Section 3.8.3 of the ANSI C standard) */
2788 SKIP_WHITE_SPACE (ibp);
2789 if (is_idstart[*ibp])
2791 *obp++ = *ibp++;
2792 while (is_idchar[*ibp])
2793 *obp++ = *ibp++;
2795 goto randomchar;
2797 #ifdef USE_C_ALLOCA
2798 alloca (0);
2799 #endif
2800 /* A # directive has been successfully processed. */
2801 /* If not generating expanded output, ignore everything until
2802 next # directive. */
2803 if (no_output && instack[indepth].fname)
2804 skip_if_group (&instack[indepth], 1, 0);
2805 obp = op->bufp;
2806 RECACHE;
2807 beg_of_line = ibp;
2808 break;
2810 case '\"': /* skip quoted string */
2811 case '\'':
2812 /* A single quoted string is treated like a double -- some
2813 programs (e.g., troff) are perverse this way */
2815 /* Handle any pending identifier;
2816 but the L in L'...' or L"..." is not an identifier. */
2817 if (ident_length
2818 && ! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2819 goto specialchar;
2821 start_line = ip->lineno;
2823 /* Skip ahead to a matching quote. */
2825 while (1) {
2826 if (ibp >= limit) {
2827 if (ip->macro != 0) {
2828 /* try harder: this string crosses a macro expansion boundary.
2829 This can happen naturally if -traditional.
2830 Otherwise, only -D can make a macro with an unmatched quote. */
2831 POPMACRO;
2832 RECACHE;
2833 continue;
2835 if (!traditional) {
2836 error_with_line (line_for_error (start_line),
2837 "unterminated string or character constant");
2838 error_with_line (multiline_string_line,
2839 "possible real start of unterminated constant");
2840 multiline_string_line = 0;
2842 break;
2844 *obp++ = *ibp;
2845 switch (*ibp++) {
2846 case '\n':
2847 ++ip->lineno;
2848 ++op->lineno;
2849 /* Traditionally, end of line ends a string constant with no error.
2850 So exit the loop and record the new line. */
2851 if (traditional) {
2852 beg_of_line = ibp;
2853 goto while2end;
2855 if (c == '\'') {
2856 error_with_line (line_for_error (start_line),
2857 "unterminated character constant");
2858 goto while2end;
2860 if (multiline_string_line == 0) {
2861 if (pedantic)
2862 pedwarn_with_line (line_for_error (start_line),
2863 "string constant runs past end of line");
2864 multiline_string_line = ip->lineno - 1;
2866 break;
2868 case '\\':
2869 if (ibp >= limit)
2870 break;
2871 if (*ibp == '\n') {
2872 /* Backslash newline is replaced by nothing at all,
2873 but keep the line counts correct. */
2874 --obp;
2875 ++ibp;
2876 ++ip->lineno;
2877 } else {
2878 /* ANSI stupidly requires that in \\ the second \
2879 is *not* prevented from combining with a newline. */
2880 while (*ibp == '\\' && ibp[1] == '\n') {
2881 ibp += 2;
2882 ++ip->lineno;
2884 *obp++ = *ibp++;
2886 break;
2888 case '\"':
2889 case '\'':
2890 if (ibp[-1] == c)
2891 goto while2end;
2892 break;
2895 while2end:
2896 break;
2898 case '/':
2899 if (*ibp == '\\' && ibp[1] == '\n')
2900 newline_fix (ibp);
2902 if (*ibp != '*'
2903 && !(cplusplus_comments && *ibp == '/'))
2904 goto randomchar;
2905 if (ip->macro != 0)
2906 goto randomchar;
2907 if (ident_length)
2908 goto specialchar;
2910 if (*ibp == '/') {
2911 /* C++ style comment... */
2912 start_line = ip->lineno;
2914 /* Comments are equivalent to spaces. */
2915 if (! put_out_comments)
2916 obp[-1] = ' ';
2919 U_CHAR *before_bp = ibp;
2921 while (++ibp < limit) {
2922 if (*ibp == '\n') {
2923 if (ibp[-1] != '\\') {
2924 if (put_out_comments) {
2925 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2926 obp += ibp - before_bp;
2928 break;
2930 if (warn_comments)
2931 warning ("multiline `//' comment");
2932 ++ip->lineno;
2933 /* Copy the newline into the output buffer, in order to
2934 avoid the pain of a #line every time a multiline comment
2935 is seen. */
2936 if (!put_out_comments)
2937 *obp++ = '\n';
2938 ++op->lineno;
2941 break;
2945 /* Ordinary C comment. Skip it, optionally copying it to output. */
2947 start_line = ip->lineno;
2949 ++ibp; /* Skip the star. */
2951 /* If this cpp is for lint, we peek inside the comments: */
2952 if (for_lint) {
2953 U_CHAR *argbp;
2954 int cmdlen, arglen;
2955 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2957 if (lintcmd != NULL) {
2958 op->bufp = obp;
2959 check_expand (op, cmdlen + arglen + 14);
2960 obp = op->bufp;
2961 /* I believe it is always safe to emit this newline: */
2962 obp[-1] = '\n';
2963 bcopy ("#pragma lint ", (char *) obp, 13);
2964 obp += 13;
2965 bcopy (lintcmd, (char *) obp, cmdlen);
2966 obp += cmdlen;
2968 if (arglen != 0) {
2969 *(obp++) = ' ';
2970 bcopy (argbp, (char *) obp, arglen);
2971 obp += arglen;
2974 /* OK, now bring us back to the state we were in before we entered
2975 this branch. We need #line because the #pragma's newline always
2976 messes up the line count. */
2977 op->bufp = obp;
2978 output_line_directive (ip, op, 0, same_file);
2979 check_expand (op, limit - ibp + 2);
2980 obp = op->bufp;
2981 *(obp++) = '/';
2985 /* Comments are equivalent to spaces.
2986 Note that we already output the slash; we might not want it.
2987 For -traditional, a comment is equivalent to nothing. */
2988 if (! put_out_comments) {
2989 if (traditional)
2990 obp--;
2991 else
2992 obp[-1] = ' ';
2994 else
2995 *obp++ = '*';
2998 U_CHAR *before_bp = ibp;
3000 for (;;) {
3001 switch (*ibp++) {
3002 case '*':
3003 if (ibp[-2] == '/' && warn_comments)
3004 warning ("`/*' within comment");
3005 if (*ibp == '\\' && ibp[1] == '\n')
3006 newline_fix (ibp);
3007 if (*ibp == '/')
3008 goto comment_end;
3009 break;
3011 case '\n':
3012 ++ip->lineno;
3013 /* Copy the newline into the output buffer, in order to
3014 avoid the pain of a #line every time a multiline comment
3015 is seen. */
3016 if (!put_out_comments)
3017 *obp++ = '\n';
3018 ++op->lineno;
3019 break;
3021 case 0:
3022 if (limit < ibp) {
3023 error_with_line (line_for_error (start_line),
3024 "unterminated comment");
3025 goto limit_reached;
3027 break;
3030 comment_end:
3032 ibp++;
3033 if (put_out_comments) {
3034 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3035 obp += ibp - before_bp;
3038 break;
3040 case '$':
3041 if (! is_idchar['$'])
3042 goto randomchar;
3043 if (pedantic)
3044 pedwarn ("`$' in identifier");
3045 goto letter;
3047 case '0': case '1': case '2': case '3': case '4':
3048 case '5': case '6': case '7': case '8': case '9':
3049 /* If digit is not part of identifier, it starts a number,
3050 which means that following letters are not an identifier.
3051 "0x5" does not refer to an identifier "x5".
3052 So copy all alphanumerics that follow without accumulating
3053 as an identifier. Periods also, for sake of "3.e7". */
3055 if (ident_length == 0) {
3056 for (;;) {
3057 while (ibp[0] == '\\' && ibp[1] == '\n') {
3058 ++ip->lineno;
3059 ibp += 2;
3061 c = *ibp++;
3062 if (!is_idchar[c] && c != '.') {
3063 --ibp;
3064 break;
3066 *obp++ = c;
3067 /* A sign can be part of a preprocessing number
3068 if it follows an `e' or `p'. */
3069 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3070 while (ibp[0] == '\\' && ibp[1] == '\n') {
3071 ++ip->lineno;
3072 ibp += 2;
3074 if (*ibp == '+' || *ibp == '-') {
3075 *obp++ = *ibp++;
3076 /* But traditional C does not let the token go past the sign,
3077 and C89 does not allow `p'. */
3078 if (traditional || (c89 && (c == 'p' || c == 'P')))
3079 break;
3083 break;
3085 /* fall through */
3087 case '_':
3088 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3089 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3090 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3091 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3092 case 'y': case 'z':
3093 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3094 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3095 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3096 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3097 case 'Y': case 'Z':
3098 letter:
3099 ident_length++;
3100 /* Compute step of hash function, to avoid a proc call on every token */
3101 hash = HASHSTEP (hash, c);
3102 break;
3104 case '\n':
3105 if (ip->fname == 0 && *ibp == '-') {
3106 /* Newline - inhibits expansion of preceding token.
3107 If expanding a macro arg, we keep the newline -.
3108 In final output, it is deleted.
3109 We recognize Newline - in macro bodies and macro args. */
3110 if (! concatenated) {
3111 ident_length = 0;
3112 hash = 0;
3114 ibp++;
3115 if (!output_marks) {
3116 obp--;
3117 } else {
3118 /* If expanding a macro arg, keep the newline -. */
3119 *obp++ = '-';
3121 break;
3124 /* If reprocessing a macro expansion, newline is a special marker. */
3125 else if (ip->macro != 0) {
3126 /* Newline White is a "funny space" to separate tokens that are
3127 supposed to be separate but without space between.
3128 Here White means any whitespace character.
3129 Newline - marks a recursive macro use that is not
3130 supposed to be expandable. */
3132 if (is_space[*ibp]) {
3133 /* Newline Space does not prevent expansion of preceding token
3134 so expand the preceding token and then come back. */
3135 if (ident_length > 0)
3136 goto specialchar;
3138 /* If generating final output, newline space makes a space. */
3139 if (!output_marks) {
3140 obp[-1] = *ibp++;
3141 /* And Newline Newline makes a newline, so count it. */
3142 if (obp[-1] == '\n')
3143 op->lineno++;
3144 } else {
3145 /* If expanding a macro arg, keep the newline space.
3146 If the arg gets stringified, newline space makes nothing. */
3147 *obp++ = *ibp++;
3149 } else abort (); /* Newline followed by something random? */
3150 break;
3153 /* If there is a pending identifier, handle it and come back here. */
3154 if (ident_length > 0)
3155 goto specialchar;
3157 beg_of_line = ibp;
3159 /* Update the line counts and output a #line if necessary. */
3160 ++ip->lineno;
3161 ++op->lineno;
3162 if (ip->lineno != op->lineno) {
3163 op->bufp = obp;
3164 output_line_directive (ip, op, 1, same_file);
3165 check_expand (op, limit - ibp);
3166 obp = op->bufp;
3168 break;
3170 /* Come here either after (1) a null character that is part of the input
3171 or (2) at the end of the input, because there is a null there. */
3172 case 0:
3173 if (ibp <= limit)
3174 /* Our input really contains a null character. */
3175 goto randomchar;
3177 limit_reached:
3178 /* At end of a macro-expansion level, pop it and read next level. */
3179 if (ip->macro != 0) {
3180 obp--;
3181 ibp--;
3182 /* If traditional, and we have an identifier that ends here,
3183 process it now, so we get the right error for recursion. */
3184 if (traditional && ident_length
3185 && ! is_idchar[*instack[indepth - 1].bufp]) {
3186 redo_char = 1;
3187 goto randomchar;
3189 POPMACRO;
3190 RECACHE;
3191 break;
3194 /* If we don't have a pending identifier,
3195 return at end of input. */
3196 if (ident_length == 0) {
3197 obp--;
3198 ibp--;
3199 op->bufp = obp;
3200 ip->bufp = ibp;
3201 goto ending;
3204 /* If we do have a pending identifier, just consider this null
3205 a special character and arrange to dispatch on it again.
3206 The second time, IDENT_LENGTH will be zero so we will return. */
3208 /* Fall through */
3210 specialchar:
3212 /* Handle the case of a character such as /, ', " or null
3213 seen following an identifier. Back over it so that
3214 after the identifier is processed the special char
3215 will be dispatched on again. */
3217 ibp--;
3218 obp--;
3219 redo_char = 1;
3221 default:
3223 randomchar:
3225 if (ident_length > 0) {
3226 register HASHNODE *hp;
3228 /* We have just seen an identifier end. If it's a macro, expand it.
3230 IDENT_LENGTH is the length of the identifier
3231 and HASH is its hash code.
3233 The identifier has already been copied to the output,
3234 so if it is a macro we must remove it.
3236 If REDO_CHAR is 0, the char that terminated the identifier
3237 has been skipped in the output and the input.
3238 OBP-IDENT_LENGTH-1 points to the identifier.
3239 If the identifier is a macro, we must back over the terminator.
3241 If REDO_CHAR is 1, the terminating char has already been
3242 backed over. OBP-IDENT_LENGTH points to the identifier. */
3244 if (!pcp_outfile || pcp_inside_if) {
3245 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3246 hp = hp->next) {
3248 if (hp->length == ident_length) {
3249 int obufp_before_macroname;
3250 int op_lineno_before_macroname;
3251 register int i = ident_length;
3252 register U_CHAR *p = hp->name;
3253 register U_CHAR *q = obp - i;
3254 int disabled;
3256 if (! redo_char)
3257 q--;
3259 do { /* All this to avoid a strncmp () */
3260 if (*p++ != *q++)
3261 goto hashcollision;
3262 } while (--i);
3264 /* We found a use of a macro name.
3265 see if the context shows it is a macro call. */
3267 /* Back up over terminating character if not already done. */
3268 if (! redo_char) {
3269 ibp--;
3270 obp--;
3273 /* Save this as a displacement from the beginning of the output
3274 buffer. We can not save this as a position in the output
3275 buffer, because it may get realloc'ed by RECACHE. */
3276 obufp_before_macroname = (obp - op->buf) - ident_length;
3277 op_lineno_before_macroname = op->lineno;
3279 if (hp->type == T_PCSTRING) {
3280 pcstring_used (hp); /* Mark the definition of this key
3281 as needed, ensuring that it
3282 will be output. */
3283 break; /* Exit loop, since the key cannot have a
3284 definition any longer. */
3287 /* Record whether the macro is disabled. */
3288 disabled = hp->type == T_DISABLED;
3290 /* This looks like a macro ref, but if the macro was disabled,
3291 just copy its name and put in a marker if requested. */
3293 if (disabled) {
3294 #if 0
3295 /* This error check caught useful cases such as
3296 #define foo(x,y) bar (x (y,0), y)
3297 foo (foo, baz) */
3298 if (traditional)
3299 error ("recursive use of macro `%s'", hp->name);
3300 #endif
3302 if (output_marks) {
3303 check_expand (op, limit - ibp + 2);
3304 *obp++ = '\n';
3305 *obp++ = '-';
3307 break;
3310 /* If macro wants an arglist, verify that a '(' follows.
3311 first skip all whitespace, copying it to the output
3312 after the macro name. Then, if there is no '(',
3313 decide this is not a macro call and leave things that way. */
3314 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3315 && hp->value.defn->nargs >= 0)
3317 U_CHAR *old_ibp = ibp;
3318 U_CHAR *old_obp = obp;
3319 int old_iln = ip->lineno;
3320 int old_oln = op->lineno;
3322 while (1) {
3323 /* Scan forward over whitespace, copying it to the output. */
3324 if (ibp == limit && ip->macro != 0) {
3325 POPMACRO;
3326 RECACHE;
3327 old_ibp = ibp;
3328 old_obp = obp;
3329 old_iln = ip->lineno;
3330 old_oln = op->lineno;
3332 /* A comment: copy it unchanged or discard it. */
3333 else if (*ibp == '/' && ibp[1] == '*') {
3334 if (put_out_comments) {
3335 *obp++ = '/';
3336 *obp++ = '*';
3337 } else if (! traditional) {
3338 *obp++ = ' ';
3340 ibp += 2;
3341 while (ibp + 1 != limit
3342 && !(ibp[0] == '*' && ibp[1] == '/')) {
3343 /* We need not worry about newline-marks,
3344 since they are never found in comments. */
3345 if (*ibp == '\n') {
3346 /* Newline in a file. Count it. */
3347 ++ip->lineno;
3348 ++op->lineno;
3350 if (put_out_comments)
3351 *obp++ = *ibp++;
3352 else
3353 ibp++;
3355 ibp += 2;
3356 if (put_out_comments) {
3357 *obp++ = '*';
3358 *obp++ = '/';
3361 else if (is_space[*ibp]) {
3362 *obp++ = *ibp++;
3363 if (ibp[-1] == '\n') {
3364 if (ip->macro == 0) {
3365 /* Newline in a file. Count it. */
3366 ++ip->lineno;
3367 ++op->lineno;
3368 } else if (!output_marks) {
3369 /* A newline mark, and we don't want marks
3370 in the output. If it is newline-hyphen,
3371 discard it entirely. Otherwise, it is
3372 newline-whitechar, so keep the whitechar. */
3373 obp--;
3374 if (*ibp == '-')
3375 ibp++;
3376 else {
3377 if (*ibp == '\n')
3378 ++op->lineno;
3379 *obp++ = *ibp++;
3381 } else {
3382 /* A newline mark; copy both chars to the output. */
3383 *obp++ = *ibp++;
3387 else break;
3389 if (*ibp != '(') {
3390 /* It isn't a macro call.
3391 Put back the space that we just skipped. */
3392 ibp = old_ibp;
3393 obp = old_obp;
3394 ip->lineno = old_iln;
3395 op->lineno = old_oln;
3396 /* Exit the for loop. */
3397 break;
3401 /* This is now known to be a macro call.
3402 Discard the macro name from the output,
3403 along with any following whitespace just copied,
3404 but preserve newlines if not outputting marks since this
3405 is more likely to do the right thing with line numbers. */
3406 obp = op->buf + obufp_before_macroname;
3407 if (output_marks)
3408 op->lineno = op_lineno_before_macroname;
3409 else {
3410 int newlines = op->lineno - op_lineno_before_macroname;
3411 while (0 < newlines--)
3412 *obp++ = '\n';
3415 /* Prevent accidental token-pasting with a character
3416 before the macro call. */
3417 if (!traditional && obp != op->buf) {
3418 switch (obp[-1]) {
3419 case '!': case '%': case '&': case '*':
3420 case '+': case '-': case '.': case '/':
3421 case ':': case '<': case '=': case '>':
3422 case '^': case '|':
3423 /* If we are expanding a macro arg, make a newline marker
3424 to separate the tokens. If we are making real output,
3425 a plain space will do. */
3426 if (output_marks)
3427 *obp++ = '\n';
3428 *obp++ = ' ';
3432 /* Expand the macro, reading arguments as needed,
3433 and push the expansion on the input stack. */
3434 ip->bufp = ibp;
3435 op->bufp = obp;
3436 macroexpand (hp, op);
3438 /* Reexamine input stack, since macroexpand has pushed
3439 a new level on it. */
3440 obp = op->bufp;
3441 RECACHE;
3442 break;
3444 hashcollision:
3446 } /* End hash-table-search loop */
3448 ident_length = hash = 0; /* Stop collecting identifier */
3449 redo_char = 0;
3450 concatenated = 0;
3451 } /* End if (ident_length > 0) */
3452 } /* End switch */
3453 } /* End per-char loop */
3455 /* Come here to return -- but first give an error message
3456 if there was an unterminated successful conditional. */
3457 ending:
3458 if (if_stack != ip->if_stack)
3460 char *str;
3462 switch (if_stack->type)
3464 case T_IF:
3465 str = "if";
3466 break;
3467 case T_IFDEF:
3468 str = "ifdef";
3469 break;
3470 case T_IFNDEF:
3471 str = "ifndef";
3472 break;
3473 case T_ELSE:
3474 str = "else";
3475 break;
3476 case T_ELIF:
3477 str = "elif";
3478 break;
3479 default:
3480 abort ();
3483 error_with_line (line_for_error (if_stack->lineno),
3484 "unterminated `#%s' conditional", str);
3486 if_stack = ip->if_stack;
3490 * Rescan a string into a temporary buffer and return the result
3491 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3493 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3494 * and insert such markers when appropriate. See `rescan' for details.
3495 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3496 * before substitution; it is 0 for other uses.
3498 static FILE_BUF
3499 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3500 U_CHAR *buf, *limit;
3501 int output_marks, assertions;
3503 register FILE_BUF *ip;
3504 FILE_BUF obuf;
3505 int length = limit - buf;
3506 U_CHAR *buf1;
3507 int odepth = indepth;
3508 int save_assertions_flag = assertions_flag;
3510 assertions_flag = assertions;
3512 if (length < 0)
3513 abort ();
3515 /* Set up the input on the input stack. */
3517 buf1 = (U_CHAR *) alloca (length + 1);
3519 register U_CHAR *p1 = buf;
3520 register U_CHAR *p2 = buf1;
3522 while (p1 != limit)
3523 *p2++ = *p1++;
3525 buf1[length] = 0;
3527 /* Set up to receive the output. */
3529 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3530 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3531 obuf.nominal_fname = 0;
3532 obuf.inc = 0;
3533 obuf.dir = 0;
3534 obuf.fname = 0;
3535 obuf.macro = 0;
3536 obuf.if_stack = 0;
3537 obuf.free_ptr = 0;
3538 obuf.system_header_p = 0;
3540 CHECK_DEPTH ({return obuf;});
3542 ++indepth;
3544 ip = &instack[indepth];
3545 ip->fname = 0;
3546 ip->nominal_fname = 0;
3547 ip->inc = 0;
3548 ip->system_header_p = 0;
3549 ip->macro = 0;
3550 ip->free_ptr = 0;
3551 ip->length = length;
3552 ip->buf = ip->bufp = buf1;
3553 ip->if_stack = if_stack;
3555 ip->lineno = obuf.lineno = 1;
3557 /* Scan the input, create the output. */
3558 rescan (&obuf, output_marks);
3560 /* Pop input stack to original state. */
3561 --indepth;
3563 if (indepth != odepth)
3564 abort ();
3566 /* Record the output. */
3567 obuf.length = obuf.bufp - obuf.buf;
3569 assertions_flag = save_assertions_flag;
3570 return obuf;
3574 * Process a # directive. Expects IP->bufp to point after the '#', as in
3575 * `#define foo bar'. Passes to the directive handler
3576 * (do_define, do_include, etc.): the addresses of the 1st and
3577 * last chars of the directive (starting immediately after the #
3578 * keyword), plus op and the keyword table pointer. If the directive
3579 * contains comments it is copied into a temporary buffer sans comments
3580 * and the temporary buffer is passed to the directive handler instead.
3581 * Likewise for backslash-newlines.
3583 * Returns nonzero if this was a known # directive.
3584 * Otherwise, returns zero, without advancing the input pointer.
3587 static int
3588 handle_directive (ip, op)
3589 FILE_BUF *ip, *op;
3591 register U_CHAR *bp, *cp;
3592 register struct directive *kt;
3593 register int ident_length;
3594 U_CHAR *resume_p;
3596 /* Nonzero means we must copy the entire directive
3597 to get rid of comments or backslash-newlines. */
3598 int copy_directive = 0;
3600 U_CHAR *ident, *after_ident;
3602 bp = ip->bufp;
3604 /* Record where the directive started. do_xifdef needs this. */
3605 directive_start = bp - 1;
3607 /* Skip whitespace and \-newline. */
3608 while (1) {
3609 if (is_hor_space[*bp]) {
3610 if (*bp != ' ' && *bp != '\t' && pedantic)
3611 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3612 bp++;
3613 } else if (*bp == '/' && (bp[1] == '*'
3614 || (cplusplus_comments && bp[1] == '/'))) {
3615 ip->bufp = bp + 2;
3616 skip_to_end_of_comment (ip, &ip->lineno, 0);
3617 bp = ip->bufp;
3618 } else if (*bp == '\\' && bp[1] == '\n') {
3619 bp += 2; ip->lineno++;
3620 } else break;
3623 /* Now find end of directive name.
3624 If we encounter a backslash-newline, exchange it with any following
3625 symbol-constituents so that we end up with a contiguous name. */
3627 cp = bp;
3628 while (1) {
3629 if (is_idchar[*cp])
3630 cp++;
3631 else {
3632 if (*cp == '\\' && cp[1] == '\n')
3633 name_newline_fix (cp);
3634 if (is_idchar[*cp])
3635 cp++;
3636 else break;
3639 ident_length = cp - bp;
3640 ident = bp;
3641 after_ident = cp;
3643 /* A line of just `#' becomes blank. */
3645 if (ident_length == 0 && *after_ident == '\n') {
3646 ip->bufp = after_ident;
3647 return 1;
3650 if (ident_length == 0 || !is_idstart[*ident]) {
3651 U_CHAR *p = ident;
3652 while (is_idchar[*p]) {
3653 if (*p < '0' || *p > '9')
3654 break;
3655 p++;
3657 /* Handle # followed by a line number. */
3658 if (p != ident && !is_idchar[*p]) {
3659 static struct directive line_directive_table[] = {
3660 { 4, do_line, "line", T_LINE},
3662 if (pedantic)
3663 pedwarn ("`#' followed by integer");
3664 after_ident = ident;
3665 kt = line_directive_table;
3666 goto old_linenum;
3669 /* Avoid error for `###' and similar cases unless -pedantic. */
3670 if (p == ident) {
3671 while (*p == '#' || is_hor_space[*p]) p++;
3672 if (*p == '\n') {
3673 if (pedantic && !lang_asm)
3674 warning ("invalid preprocessing directive");
3675 return 0;
3679 if (!lang_asm)
3680 error ("invalid preprocessing directive name");
3682 return 0;
3686 * Decode the keyword and call the appropriate expansion
3687 * routine, after moving the input pointer up to the next line.
3689 for (kt = directive_table; kt->length > 0; kt++) {
3690 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3691 register U_CHAR *buf;
3692 register U_CHAR *limit;
3693 int unterminated;
3694 int junk;
3695 int *already_output;
3697 /* Nonzero means do not delete comments within the directive.
3698 #define needs this when -traditional. */
3699 int keep_comments;
3701 old_linenum:
3703 limit = ip->buf + ip->length;
3704 unterminated = 0;
3705 already_output = 0;
3706 keep_comments = traditional && kt->type == T_DEFINE;
3707 /* #import is defined only in Objective C, or when on the NeXT. */
3708 if (kt->type == T_IMPORT
3709 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3710 break;
3712 /* Find the end of this directive (first newline not backslashed
3713 and not in a string or comment).
3714 Set COPY_DIRECTIVE if the directive must be copied
3715 (it contains a backslash-newline or a comment). */
3717 buf = bp = after_ident;
3718 while (bp < limit) {
3719 register U_CHAR c = *bp++;
3720 switch (c) {
3721 case '\\':
3722 if (bp < limit) {
3723 if (*bp == '\n') {
3724 ip->lineno++;
3725 copy_directive = 1;
3726 bp++;
3727 } else if (traditional)
3728 bp++;
3730 break;
3732 case '\'':
3733 case '\"':
3734 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3735 /* Don't bother calling the directive if we already got an error
3736 message due to unterminated string. Skip everything and pretend
3737 we called the directive. */
3738 if (unterminated) {
3739 if (traditional) {
3740 /* Traditional preprocessing permits unterminated strings. */
3741 ip->bufp = bp;
3742 goto endloop1;
3744 ip->bufp = bp;
3745 return 1;
3747 break;
3749 /* <...> is special for #include. */
3750 case '<':
3751 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3752 break;
3753 while (bp < limit && *bp != '>' && *bp != '\n') {
3754 if (*bp == '\\' && bp[1] == '\n') {
3755 ip->lineno++;
3756 copy_directive = 1;
3757 bp++;
3759 bp++;
3761 break;
3763 case '/':
3764 if (*bp == '\\' && bp[1] == '\n')
3765 newline_fix (bp);
3766 if (*bp == '*'
3767 || (cplusplus_comments && *bp == '/')) {
3768 U_CHAR *obp = bp - 1;
3769 ip->bufp = bp + 1;
3770 skip_to_end_of_comment (ip, &ip->lineno, 0);
3771 bp = ip->bufp;
3772 /* No need to copy the directive because of a comment at the end;
3773 just don't include the comment in the directive. */
3774 if (!put_out_comments) {
3775 U_CHAR *p;
3776 for (p = bp; *p == ' ' || *p == '\t'; p++)
3777 continue;
3778 if (*p == '\n') {
3779 bp = obp;
3780 goto endloop1;
3783 /* Don't remove the comments if -traditional. */
3784 if (! keep_comments)
3785 copy_directive++;
3787 break;
3789 case '\f':
3790 case '\r':
3791 case '\v':
3792 if (pedantic)
3793 pedwarn ("%s in preprocessing directive", char_name[c]);
3794 break;
3796 case '\n':
3797 --bp; /* Point to the newline */
3798 ip->bufp = bp;
3799 goto endloop1;
3802 ip->bufp = bp;
3804 endloop1:
3805 resume_p = ip->bufp;
3806 /* BP is the end of the directive.
3807 RESUME_P is the next interesting data after the directive.
3808 A comment may come between. */
3810 /* If a directive should be copied through, and -C was given,
3811 pass it through before removing comments. */
3812 if (!no_output && put_out_comments
3813 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
3814 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3815 : kt->type == T_PRAGMA)) {
3816 int len;
3818 /* Output directive name. */
3819 check_expand (op, kt->length + 2);
3820 /* Make sure # is at the start of a line */
3821 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3822 op->lineno++;
3823 *op->bufp++ = '\n';
3825 *op->bufp++ = '#';
3826 bcopy (kt->name, op->bufp, kt->length);
3827 op->bufp += kt->length;
3829 /* Output arguments. */
3830 len = (bp - buf);
3831 check_expand (op, len);
3832 bcopy (buf, (char *) op->bufp, len);
3833 op->bufp += len;
3834 /* Take account of any (escaped) newlines just output. */
3835 while (--len >= 0)
3836 if (buf[len] == '\n')
3837 op->lineno++;
3839 already_output = &junk;
3840 } /* Don't we need a newline or #line? */
3842 if (copy_directive) {
3843 register U_CHAR *xp = buf;
3844 /* Need to copy entire directive into temp buffer before dispatching */
3846 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3847 some slop */
3848 buf = cp;
3850 /* Copy to the new buffer, deleting comments
3851 and backslash-newlines (and whitespace surrounding the latter). */
3853 while (xp < bp) {
3854 register U_CHAR c = *xp++;
3855 *cp++ = c;
3857 switch (c) {
3858 case '\n':
3859 abort (); /* A bare newline should never part of the line. */
3860 break;
3862 /* <...> is special for #include. */
3863 case '<':
3864 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3865 break;
3866 while (xp < bp && c != '>') {
3867 c = *xp++;
3868 if (c == '\\' && xp < bp && *xp == '\n')
3869 xp++;
3870 else
3871 *cp++ = c;
3873 break;
3875 case '\\':
3876 if (*xp == '\n') {
3877 xp++;
3878 cp--;
3879 if (cp != buf && is_hor_space[cp[-1]]) {
3880 while (cp - 1 != buf && is_hor_space[cp[-2]])
3881 cp--;
3882 SKIP_WHITE_SPACE (xp);
3883 } else if (is_hor_space[*xp]) {
3884 *cp++ = *xp++;
3885 SKIP_WHITE_SPACE (xp);
3887 } else if (traditional && xp < bp) {
3888 *cp++ = *xp++;
3890 break;
3892 case '\'':
3893 case '\"':
3895 register U_CHAR *bp1
3896 = skip_quoted_string (xp - 1, bp, ip->lineno,
3897 NULL_PTR, NULL_PTR, NULL_PTR);
3898 while (xp != bp1)
3899 if (*xp == '\\') {
3900 if (*++xp != '\n')
3901 *cp++ = '\\';
3902 else
3903 xp++;
3904 } else
3905 *cp++ = *xp++;
3907 break;
3909 case '/':
3910 if (*xp == '*'
3911 || (cplusplus_comments && *xp == '/')) {
3912 ip->bufp = xp + 1;
3913 /* If we already copied the directive through,
3914 already_output != 0 prevents outputting comment now. */
3915 skip_to_end_of_comment (ip, already_output, 0);
3916 if (keep_comments)
3917 while (xp != ip->bufp)
3918 *cp++ = *xp++;
3919 /* Delete or replace the slash. */
3920 else if (traditional)
3921 cp--;
3922 else
3923 cp[-1] = ' ';
3924 xp = ip->bufp;
3929 /* Null-terminate the copy. */
3931 *cp = 0;
3932 } else
3933 cp = bp;
3935 ip->bufp = resume_p;
3937 /* Some directives should be written out for cc1 to process,
3938 just as if they were not defined. And sometimes we're copying
3939 directives through. */
3941 if (!no_output && already_output == 0
3942 && (kt->type == T_DEFINE ? dump_names <= dump_macros
3943 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3944 : kt->type == T_PRAGMA)) {
3945 int len;
3947 /* Output directive name. */
3948 check_expand (op, kt->length + 1);
3949 *op->bufp++ = '#';
3950 bcopy (kt->name, (char *) op->bufp, kt->length);
3951 op->bufp += kt->length;
3953 if (kt->type == T_DEFINE && dump_macros == dump_names) {
3954 /* Output `#define name' only. */
3955 U_CHAR *xp = buf;
3956 U_CHAR *yp;
3957 SKIP_WHITE_SPACE (xp);
3958 yp = xp;
3959 while (is_idchar[*xp]) xp++;
3960 len = (xp - yp);
3961 check_expand (op, len + 1);
3962 *op->bufp++ = ' ';
3963 bcopy (yp, (char *) op->bufp, len);
3964 } else {
3965 /* Output entire directive. */
3966 len = (cp - buf);
3967 check_expand (op, len);
3968 bcopy (buf, (char *) op->bufp, len);
3970 op->bufp += len;
3971 } /* Don't we need a newline or #line? */
3973 /* Call the appropriate directive handler. buf now points to
3974 either the appropriate place in the input buffer, or to
3975 the temp buffer if it was necessary to make one. cp
3976 points to the first char after the contents of the (possibly
3977 copied) directive, in either case. */
3978 (*kt->func) (buf, cp, op, kt);
3979 check_expand (op, ip->length - (ip->bufp - ip->buf));
3981 return 1;
3985 /* It is deliberate that we don't warn about undefined directives.
3986 That is the responsibility of cc1. */
3987 return 0;
3990 static struct tm *
3991 timestamp ()
3993 static struct tm *timebuf;
3994 if (!timebuf) {
3995 time_t t = time ((time_t *) 0);
3996 timebuf = localtime (&t);
3998 return timebuf;
4001 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4002 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4006 * expand things like __FILE__. Place the expansion into the output
4007 * buffer *without* rescanning.
4010 static void
4011 special_symbol (hp, op)
4012 HASHNODE *hp;
4013 FILE_BUF *op;
4015 char *buf;
4016 int i, len;
4017 int true_indepth;
4018 FILE_BUF *ip = NULL;
4019 struct tm *timebuf;
4021 int paren = 0; /* For special `defined' keyword */
4023 if (pcp_outfile && pcp_inside_if
4024 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4025 error ("Predefined macro `%s' used inside `#if' during precompilation",
4026 hp->name);
4028 for (i = indepth; i >= 0; i--)
4029 if (instack[i].fname != NULL) {
4030 ip = &instack[i];
4031 break;
4033 if (ip == NULL) {
4034 error ("cccp error: not in any file?!");
4035 return; /* the show must go on */
4038 switch (hp->type) {
4039 case T_FILE:
4040 case T_BASE_FILE:
4042 char *string;
4043 if (hp->type == T_FILE)
4044 string = ip->nominal_fname;
4045 else
4046 string = instack[0].nominal_fname;
4048 if (string)
4050 buf = (char *) alloca (3 + 4 * strlen (string));
4051 quote_string (buf, string);
4053 else
4054 buf = "\"\"";
4056 break;
4059 case T_INCLUDE_LEVEL:
4060 true_indepth = 0;
4061 for (i = indepth; i >= 0; i--)
4062 if (instack[i].fname != NULL)
4063 true_indepth++;
4065 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4066 sprintf (buf, "%d", true_indepth - 1);
4067 break;
4069 case T_VERSION:
4070 buf = (char *) alloca (3 + strlen (version_string));
4071 sprintf (buf, "\"%s\"", version_string);
4072 break;
4074 #ifndef NO_BUILTIN_SIZE_TYPE
4075 case T_SIZE_TYPE:
4076 buf = SIZE_TYPE;
4077 break;
4078 #endif
4080 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4081 case T_PTRDIFF_TYPE:
4082 buf = PTRDIFF_TYPE;
4083 break;
4084 #endif
4086 case T_WCHAR_TYPE:
4087 buf = wchar_type;
4088 break;
4090 case T_USER_LABEL_PREFIX_TYPE:
4091 buf = USER_LABEL_PREFIX;
4092 break;
4094 case T_REGISTER_PREFIX_TYPE:
4095 buf = REGISTER_PREFIX;
4096 break;
4098 case T_IMMEDIATE_PREFIX_TYPE:
4099 buf = IMMEDIATE_PREFIX;
4100 break;
4102 case T_CONST:
4103 buf = hp->value.cpval;
4104 #ifdef STDC_0_IN_SYSTEM_HEADERS
4105 if (ip->system_header_p
4106 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4107 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4108 buf = "0";
4109 #endif
4110 if (pcp_inside_if && pcp_outfile)
4111 /* Output a precondition for this macro use */
4112 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4113 break;
4115 case T_SPECLINE:
4116 buf = (char *) alloca (10);
4117 sprintf (buf, "%d", ip->lineno);
4118 break;
4120 case T_DATE:
4121 case T_TIME:
4122 buf = (char *) alloca (20);
4123 timebuf = timestamp ();
4124 if (hp->type == T_DATE)
4125 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4126 timebuf->tm_mday, timebuf->tm_year + 1900);
4127 else
4128 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4129 timebuf->tm_sec);
4130 break;
4132 case T_SPEC_DEFINED:
4133 buf = " 0 "; /* Assume symbol is not defined */
4134 ip = &instack[indepth];
4135 SKIP_WHITE_SPACE (ip->bufp);
4136 if (*ip->bufp == '(') {
4137 paren++;
4138 ip->bufp++; /* Skip over the paren */
4139 SKIP_WHITE_SPACE (ip->bufp);
4142 if (!is_idstart[*ip->bufp])
4143 goto oops;
4144 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4145 goto oops;
4146 if ((hp = lookup (ip->bufp, -1, -1))) {
4147 if (pcp_outfile && pcp_inside_if
4148 && (hp->type == T_CONST
4149 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4150 /* Output a precondition for this macro use. */
4151 fprintf (pcp_outfile, "#define %s\n", hp->name);
4152 buf = " 1 ";
4154 else
4155 if (pcp_outfile && pcp_inside_if) {
4156 /* Output a precondition for this macro use */
4157 U_CHAR *cp = ip->bufp;
4158 fprintf (pcp_outfile, "#undef ");
4159 while (is_idchar[*cp]) /* Ick! */
4160 fputc (*cp++, pcp_outfile);
4161 putc ('\n', pcp_outfile);
4163 while (is_idchar[*ip->bufp])
4164 ++ip->bufp;
4165 SKIP_WHITE_SPACE (ip->bufp);
4166 if (paren) {
4167 if (*ip->bufp != ')')
4168 goto oops;
4169 ++ip->bufp;
4171 break;
4173 oops:
4175 error ("`defined' without an identifier");
4176 break;
4178 default:
4179 error ("cccp error: invalid special hash type"); /* time for gdb */
4180 abort ();
4182 len = strlen (buf);
4183 check_expand (op, len);
4184 bcopy (buf, (char *) op->bufp, len);
4185 op->bufp += len;
4187 return;
4191 /* Routines to handle #directives */
4193 /* Handle #include and #import.
4194 This function expects to see "fname" or <fname> on the input. */
4196 static int
4197 do_include (buf, limit, op, keyword)
4198 U_CHAR *buf, *limit;
4199 FILE_BUF *op;
4200 struct directive *keyword;
4202 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4203 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4204 static int import_warning = 0;
4205 char *fname; /* Dynamically allocated fname buffer */
4206 char *pcftry;
4207 char *pcfname;
4208 char *fbeg, *fend; /* Beginning and end of fname */
4209 U_CHAR *fin;
4211 struct file_name_list *search_start = include; /* Chain of dirs to search */
4212 struct file_name_list *dsp; /* First in chain, if #include "..." */
4213 struct file_name_list *searchptr = 0;
4214 size_t flen;
4216 int f = -3; /* file number */
4217 struct include_file *inc = 0;
4219 int retried = 0; /* Have already tried macro
4220 expanding the include line*/
4221 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4222 #ifdef VMS
4223 int vaxc_include = 0; /* 1 for token without punctuation */
4224 #endif
4225 int pcf = -1;
4226 char *pcfbuf;
4227 char *pcfbuflimit;
4228 int pcfnum;
4230 if (pedantic && !instack[indepth].system_header_p)
4232 if (importing)
4233 pedwarn ("ANSI C does not allow `#import'");
4234 if (skip_dirs)
4235 pedwarn ("ANSI C does not allow `#include_next'");
4238 if (importing && warn_import && !inhibit_warnings
4239 && !instack[indepth].system_header_p && !import_warning) {
4240 import_warning = 1;
4241 warning ("using `#import' is not recommended");
4242 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4243 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4244 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4245 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4246 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4247 fprintf (stderr, " ... <real contents of file> ...\n");
4248 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4249 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4250 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4251 fprintf (stderr, "when it is equipped with such a conditional.\n");
4254 get_filename:
4256 fin = buf;
4257 SKIP_WHITE_SPACE (fin);
4258 /* Discard trailing whitespace so we can easily see
4259 if we have parsed all the significant chars we were given. */
4260 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4261 fbeg = fend = (char *) alloca (limit - fin);
4263 switch (*fin++) {
4264 case '\"':
4266 FILE_BUF *fp;
4267 /* Copy the operand text, concatenating the strings. */
4269 while (fin != limit) {
4270 while (fin != limit && *fin != '\"')
4271 *fend++ = *fin++;
4272 fin++;
4273 if (fin == limit)
4274 break;
4275 /* If not at the end, there had better be another string. */
4276 /* Skip just horiz space, and don't go past limit. */
4277 while (fin != limit && is_hor_space[*fin]) fin++;
4278 if (fin != limit && *fin == '\"')
4279 fin++;
4280 else
4281 goto fail;
4285 /* We have "filename". Figure out directory this source
4286 file is coming from and put it on the front of the list. */
4288 /* If -I- was specified, don't search current dir, only spec'd ones. */
4289 if (ignore_srcdir) break;
4291 for (fp = &instack[indepth]; fp >= instack; fp--)
4293 int n;
4294 char *nam;
4296 if ((nam = fp->nominal_fname) != NULL) {
4297 /* Found a named file. Figure out dir of the file,
4298 and put it in front of the search list. */
4299 dsp = ((struct file_name_list *)
4300 alloca (sizeof (struct file_name_list) + strlen (nam)));
4301 strcpy (dsp->fname, nam);
4302 simplify_filename (dsp->fname);
4303 nam = base_name (dsp->fname);
4304 *nam = 0;
4305 /* But for efficiency's sake, do not insert the dir
4306 if it matches the search list's first dir. */
4307 dsp->next = search_start;
4308 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4309 search_start = dsp;
4310 n = nam - dsp->fname;
4311 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4312 max_include_len = n + INCLUDE_LEN_FUDGE;
4314 dsp[0].got_name_map = 0;
4315 break;
4318 break;
4321 case '<':
4322 while (fin != limit && *fin != '>')
4323 *fend++ = *fin++;
4324 if (*fin == '>' && fin + 1 == limit) {
4325 angle_brackets = 1;
4326 /* If -I-, start with the first -I dir after the -I-. */
4327 search_start = first_bracket_include;
4328 break;
4330 goto fail;
4332 default:
4333 #ifdef VMS
4335 * Support '#include xyz' like VAX-C to allow for easy use of all the
4336 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4337 * code from case '<' is repeated here) and generates a warning.
4338 * (Note: macro expansion of `xyz' takes precedence.)
4340 if (retried && isalpha(*(U_CHAR *) (--fbeg))) {
4341 while (fin != limit && (!isspace(*fin)))
4342 *fend++ = *fin++;
4343 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4344 vaxc_include = 1;
4345 if (fin == limit) {
4346 angle_brackets = 1;
4347 /* If -I-, start with the first -I dir after the -I-. */
4348 search_start = first_bracket_include;
4349 break;
4352 #endif
4354 fail:
4355 if (retried) {
4356 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4357 return 0;
4358 } else {
4359 /* Expand buffer and then remove any newline markers.
4360 We can't just tell expand_to_temp_buffer to omit the markers,
4361 since it would put extra spaces in include file names. */
4362 FILE_BUF trybuf;
4363 U_CHAR *src;
4364 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4365 src = trybuf.buf;
4366 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4367 limit = buf;
4368 while (src != trybuf.bufp) {
4369 switch ((*limit++ = *src++)) {
4370 case '\n':
4371 limit--;
4372 src++;
4373 break;
4375 case '\'':
4376 case '\"':
4378 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4379 NULL_PTR, NULL_PTR, NULL_PTR);
4380 while (src != src1)
4381 *limit++ = *src++;
4383 break;
4386 *limit = 0;
4387 free (trybuf.buf);
4388 retried++;
4389 goto get_filename;
4393 /* For #include_next, skip in the search path
4394 past the dir in which the containing file was found. */
4395 if (skip_dirs) {
4396 FILE_BUF *fp;
4397 for (fp = &instack[indepth]; fp >= instack; fp--)
4398 if (fp->fname != NULL) {
4399 /* fp->dir is null if the containing file was specified
4400 with an absolute file name. In that case, don't skip anything. */
4401 if (fp->dir)
4402 search_start = fp->dir->next;
4403 break;
4407 *fend = 0;
4408 flen = simplify_filename (fbeg);
4410 if (flen == 0)
4412 error ("empty file name in `#%s'", keyword->name);
4413 return 0;
4416 /* Allocate this permanently, because it gets stored in the definitions
4417 of macros. */
4418 fname = xmalloc (max_include_len + flen + 1);
4419 /* + 1 above for terminating null. */
4421 system_include_depth += angle_brackets;
4423 /* If specified file name is absolute, just open it. */
4425 if (absolute_filename (fbeg)) {
4426 strcpy (fname, fbeg);
4427 f = open_include_file (fname, NULL_PTR, importing, &inc);
4428 } else {
4430 struct bypass_dir {
4431 struct bypass_dir *next;
4432 char *fname;
4433 struct file_name_list *searchptr;
4434 } **bypass_slot = 0;
4436 /* Search directory path, trying to open the file.
4437 Copy each filename tried into FNAME. */
4439 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4441 if (searchptr == first_bracket_include) {
4442 /* Go to bypass directory if we know we've seen this file before. */
4443 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4444 struct bypass_dir *p;
4445 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4446 INCLUDE_HASHSIZE)];
4447 for (p = *bypass_slot; p; p = p->next)
4448 if (!strcmp (fbeg, p->fname)) {
4449 searchptr = p->searchptr;
4450 bypass_slot = 0;
4451 break;
4455 strcpy (fname, searchptr->fname);
4456 strcat (fname, fbeg);
4457 #ifdef VMS
4458 /* Change this 1/2 Unix 1/2 VMS file specification into a
4459 full VMS file specification */
4460 if (searchptr->fname[0]) {
4461 /* Fix up the filename */
4462 hack_vms_include_specification (fname, vaxc_include);
4463 } else {
4464 /* This is a normal VMS filespec, so use it unchanged. */
4465 strcpy (fname, fbeg);
4466 /* if it's '#include filename', add the missing .h */
4467 if (vaxc_include && index(fname,'.')==NULL) {
4468 strcat (fname, ".h");
4471 #endif /* VMS */
4472 f = open_include_file (fname, searchptr, importing, &inc);
4473 if (f != -1) {
4474 if (bypass_slot && searchptr != first_bracket_include) {
4475 /* This is the first time we found this include file,
4476 and we found it after first_bracket_include.
4477 Record its location so that we can bypass to here next time. */
4478 struct bypass_dir *p
4479 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4480 p->next = *bypass_slot;
4481 p->fname = fname + strlen (searchptr->fname);
4482 p->searchptr = searchptr;
4483 *bypass_slot = p;
4485 break;
4487 #ifdef VMS
4488 /* Our VMS hacks can produce invalid filespecs, so don't worry
4489 about errors other than EACCES. */
4490 if (errno == EACCES)
4491 break;
4492 #else
4493 if (errno != ENOENT && errno != ENOTDIR)
4494 break;
4495 #endif
4500 if (f < 0) {
4502 if (f == -2) {
4503 /* The file was already included. */
4505 /* If generating dependencies and -MG was specified, we assume missing
4506 files are leaf files, living in the same directory as the source file
4507 or other similar place; these missing files may be generated from
4508 other files and may not exist yet (eg: y.tab.h). */
4509 } else if (print_deps_missing_files
4510 && (system_include_depth != 0) < print_deps)
4512 /* If it was requested as a system header file,
4513 then assume it belongs in the first place to look for such. */
4514 if (angle_brackets)
4516 if (search_start) {
4517 char *p = (char *) alloca (strlen (search_start->fname)
4518 + strlen (fbeg) + 1);
4519 strcpy (p, search_start->fname);
4520 strcat (p, fbeg);
4521 deps_output (p, ' ');
4524 else
4526 /* Otherwise, omit the directory, as if the file existed
4527 in the directory with the source. */
4528 deps_output (fbeg, ' ');
4531 /* If -M was specified, and this header file won't be added to the
4532 dependency list, then don't count this as an error, because we can
4533 still produce correct output. Otherwise, we can't produce correct
4534 output, because there may be dependencies we need inside the missing
4535 file, and we don't know what directory this missing file exists in. */
4536 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4537 warning ("No include path in which to find %s", fbeg);
4538 else if (f != -3)
4539 error_from_errno (fbeg);
4540 else
4541 error ("No include path in which to find %s", fbeg);
4543 } else {
4545 /* Actually process the file. */
4547 pcftry = (char *) alloca (strlen (fname) + 30);
4548 pcfbuf = 0;
4549 pcfnum = 0;
4551 if (!no_precomp)
4553 do {
4554 sprintf (pcftry, "%s%d", fname, pcfnum++);
4556 pcf = open (pcftry, O_RDONLY, 0666);
4557 if (pcf != -1)
4559 struct stat s;
4561 if (fstat (pcf, &s) != 0)
4562 pfatal_with_name (pcftry);
4563 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4564 || inc->st.st_dev != s.st_dev)
4566 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4567 /* Don't need it any more. */
4568 close (pcf);
4570 else
4572 /* Don't need it at all. */
4573 close (pcf);
4574 break;
4577 } while (pcf != -1 && !pcfbuf);
4580 /* Actually process the file */
4581 if (pcfbuf) {
4582 pcfname = xmalloc (strlen (pcftry) + 1);
4583 strcpy (pcfname, pcftry);
4584 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4585 (U_CHAR *) fname, op);
4587 else
4588 finclude (f, inc, op, is_system_include (fname), searchptr);
4591 system_include_depth -= angle_brackets;
4593 return 0;
4596 /* Return nonzero if the given FILENAME is an absolute pathname which
4597 designates a file within one of the known "system" include file
4598 directories. We assume here that if the given FILENAME looks like
4599 it is the name of a file which resides either directly in a "system"
4600 include file directory, or within any subdirectory thereof, then the
4601 given file must be a "system" include file. This function tells us
4602 if we should suppress pedantic errors/warnings for the given FILENAME.
4604 The value is 2 if the file is a C-language system header file
4605 for which C++ should (on most systems) assume `extern "C"'. */
4607 static int
4608 is_system_include (filename)
4609 register char *filename;
4611 struct file_name_list *searchptr;
4613 for (searchptr = first_system_include; searchptr;
4614 searchptr = searchptr->next)
4615 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4616 return searchptr->c_system_include_path + 1;
4617 return 0;
4620 /* Yield the non-directory suffix of a file name. */
4622 static char *
4623 base_name (fname)
4624 char *fname;
4626 char *s = fname;
4627 char *p;
4628 #if defined (__MSDOS__) || defined (_WIN32)
4629 if (isalpha (s[0]) && s[1] == ':') s += 2;
4630 #endif
4631 #ifdef VMS
4632 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4633 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4634 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4635 if (s != fname)
4636 return s;
4637 #endif
4638 if ((p = rindex (s, '/'))) s = p + 1;
4639 #ifdef DIR_SEPARATOR
4640 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4641 #endif
4642 return s;
4645 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4647 static int
4648 absolute_filename (filename)
4649 char *filename;
4651 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4652 if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4653 #endif
4654 #if defined (__CYGWIN32__)
4655 /* At present, any path that begins with a drive spec is absolute. */
4656 if (isalpha (filename[0]) && filename[1] == ':') return 1;
4657 #endif
4658 if (filename[0] == '/') return 1;
4659 #ifdef DIR_SEPARATOR
4660 if (filename[0] == DIR_SEPARATOR) return 1;
4661 #endif
4662 return 0;
4665 /* Remove unnecessary characters from FILENAME in place,
4666 to avoid unnecessary filename aliasing.
4667 Return the length of the resulting string.
4669 Do only the simplifications allowed by Posix.
4670 It is OK to miss simplifications on non-Posix hosts,
4671 since this merely leads to suboptimal results. */
4673 static size_t
4674 simplify_filename (filename)
4675 char *filename;
4677 register char *from = filename;
4678 register char *to = filename;
4679 char *to0;
4681 /* Remove redundant initial /s. */
4682 if (*from == '/') {
4683 *to++ = '/';
4684 if (*++from == '/') {
4685 if (*++from == '/') {
4686 /* 3 or more initial /s are equivalent to 1 /. */
4687 while (*++from == '/')
4688 continue;
4689 } else {
4690 /* On some hosts // differs from /; Posix allows this. */
4691 static int slashslash_vs_slash;
4692 if (slashslash_vs_slash == 0) {
4693 struct stat s1, s2;
4694 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4695 && INO_T_EQ (s1.st_ino, s2.st_ino)
4696 && s1.st_dev == s2.st_dev)
4697 ? 1 : -1);
4699 if (slashslash_vs_slash < 0)
4700 *to++ = '/';
4704 to0 = to;
4706 for (;;) {
4707 if (from[0] == '.' && from[1] == '/')
4708 from += 2;
4709 else {
4710 /* Copy this component and trailing /, if any. */
4711 while ((*to++ = *from++) != '/') {
4712 if (!to[-1]) {
4713 /* Trim . component at end of nonempty name. */
4714 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4716 /* Trim unnecessary trailing /s. */
4717 while (to0 < --to && to[-1] == '/')
4718 continue;
4720 *to = 0;
4721 return to - filename;
4726 /* Skip /s after a /. */
4727 while (*from == '/')
4728 from++;
4732 /* The file_name_map structure holds a mapping of file names for a
4733 particular directory. This mapping is read from the file named
4734 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4735 map filenames on a file system with severe filename restrictions,
4736 such as DOS. The format of the file name map file is just a series
4737 of lines with two tokens on each line. The first token is the name
4738 to map, and the second token is the actual name to use. */
4740 struct file_name_map
4742 struct file_name_map *map_next;
4743 char *map_from;
4744 char *map_to;
4747 #define FILE_NAME_MAP_FILE "header.gcc"
4749 /* Read a space delimited string of unlimited length from a stdio
4750 file. */
4752 static char *
4753 read_filename_string (ch, f)
4754 int ch;
4755 FILE *f;
4757 char *alloc, *set;
4758 int len;
4760 len = 20;
4761 set = alloc = xmalloc (len + 1);
4762 if (! is_space[ch])
4764 *set++ = ch;
4765 while ((ch = getc (f)) != EOF && ! is_space[ch])
4767 if (set - alloc == len)
4769 len *= 2;
4770 alloc = xrealloc (alloc, len + 1);
4771 set = alloc + len / 2;
4773 *set++ = ch;
4776 *set = '\0';
4777 ungetc (ch, f);
4778 return alloc;
4781 /* Read the file name map file for DIRNAME.
4782 If DIRNAME is empty, read the map file for the working directory;
4783 otherwise DIRNAME must end in '/'. */
4785 static struct file_name_map *
4786 read_name_map (dirname)
4787 char *dirname;
4789 /* This structure holds a linked list of file name maps, one per
4790 directory. */
4791 struct file_name_map_list
4793 struct file_name_map_list *map_list_next;
4794 char *map_list_name;
4795 struct file_name_map *map_list_map;
4797 static struct file_name_map_list *map_list;
4798 register struct file_name_map_list *map_list_ptr;
4799 char *name;
4800 FILE *f;
4801 size_t dirlen;
4803 for (map_list_ptr = map_list; map_list_ptr;
4804 map_list_ptr = map_list_ptr->map_list_next)
4805 if (! strcmp (map_list_ptr->map_list_name, dirname))
4806 return map_list_ptr->map_list_map;
4808 map_list_ptr = ((struct file_name_map_list *)
4809 xmalloc (sizeof (struct file_name_map_list)));
4810 map_list_ptr->map_list_name = savestring (dirname);
4811 map_list_ptr->map_list_map = NULL;
4813 dirlen = strlen (dirname);
4814 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4815 strcpy (name, dirname);
4816 strcat (name, FILE_NAME_MAP_FILE);
4817 f = fopen (name, "r");
4818 if (!f)
4819 map_list_ptr->map_list_map = NULL;
4820 else
4822 int ch;
4824 while ((ch = getc (f)) != EOF)
4826 char *from, *to;
4827 struct file_name_map *ptr;
4828 size_t tolen;
4830 if (is_space[ch])
4831 continue;
4832 from = read_filename_string (ch, f);
4833 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4835 to = read_filename_string (ch, f);
4837 simplify_filename (from);
4838 tolen = simplify_filename (to);
4840 ptr = ((struct file_name_map *)
4841 xmalloc (sizeof (struct file_name_map)));
4842 ptr->map_from = from;
4844 /* Make the real filename absolute. */
4845 if (absolute_filename (to))
4846 ptr->map_to = to;
4847 else
4849 ptr->map_to = xmalloc (dirlen + tolen + 1);
4850 strcpy (ptr->map_to, dirname);
4851 strcat (ptr->map_to, to);
4852 free (to);
4855 ptr->map_next = map_list_ptr->map_list_map;
4856 map_list_ptr->map_list_map = ptr;
4858 while ((ch = getc (f)) != '\n')
4859 if (ch == EOF)
4860 break;
4862 fclose (f);
4865 map_list_ptr->map_list_next = map_list;
4866 map_list = map_list_ptr;
4868 return map_list_ptr->map_list_map;
4871 /* Try to open include file FILENAME. SEARCHPTR is the directory
4872 being tried from the include file search path.
4873 IMPORTING is "" if we are importing, null otherwise.
4874 Return -2 if found, either a matching name or a matching inode.
4875 Otherwise, open the file and return a file descriptor if successful
4876 or -1 if unsuccessful.
4877 Unless unsuccessful, put a descriptor of the included file into *PINC.
4878 This function maps filenames on file systems based on information read by
4879 read_name_map. */
4881 static int
4882 open_include_file (filename, searchptr, importing, pinc)
4883 char *filename;
4884 struct file_name_list *searchptr;
4885 U_CHAR *importing;
4886 struct include_file **pinc;
4888 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
4889 int fd = -2;
4891 /* Look up FNAME in include_hashtab. */
4892 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4893 strlen (fname),
4894 INCLUDE_HASHSIZE)];
4895 struct include_file *inc, *head = *phead;
4896 for (inc = head; inc; inc = inc->next)
4897 if (!strcmp (fname, inc->fname))
4898 break;
4900 if (!inc
4901 || ! inc->control_macro
4902 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4904 fd = open (fname, O_RDONLY, 0);
4906 if (fd < 0)
4907 return fd;
4909 if (!inc) {
4910 /* FNAME was not in include_hashtab; insert a new entry. */
4911 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4912 inc->next = head;
4913 inc->fname = fname;
4914 inc->control_macro = 0;
4915 inc->deps_output = 0;
4916 if (fstat (fd, &inc->st) != 0)
4917 pfatal_with_name (fname);
4918 *phead = inc;
4920 /* Look for another file with the same inode and device. */
4921 if (lookup_ino_include (inc)
4922 && inc->control_macro
4923 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4924 close (fd);
4925 fd = -2;
4929 /* For -M, add this file to the dependencies. */
4930 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4931 inc->deps_output = 1;
4932 deps_output (fname, ' ');
4935 /* Handle -H option. */
4936 if (print_include_names)
4937 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4940 if (importing)
4941 inc->control_macro = importing;
4943 *pinc = inc;
4944 return fd;
4947 /* Return the remapped name of the the include file FILENAME.
4948 SEARCHPTR is the directory being tried from the include file path. */
4950 static char *
4951 remap_include_file (filename, searchptr)
4952 char *filename;
4953 struct file_name_list *searchptr;
4955 register struct file_name_map *map;
4956 register char *from;
4958 if (searchptr)
4960 if (! searchptr->got_name_map)
4962 searchptr->name_map = read_name_map (searchptr->fname);
4963 searchptr->got_name_map = 1;
4966 /* Check the mapping for the directory we are using. */
4967 from = filename + strlen (searchptr->fname);
4968 for (map = searchptr->name_map; map; map = map->map_next)
4969 if (! strcmp (map->map_from, from))
4970 return map->map_to;
4973 from = base_name (filename);
4975 if (from != filename || !searchptr)
4977 /* Try to find a mapping file for the particular directory we are
4978 looking in. Thus #include <sys/types.h> will look up sys/types.h
4979 in /usr/include/header.gcc and look up types.h in
4980 /usr/include/sys/header.gcc. */
4982 char *dir = (char *) alloca (from - filename + 1);
4983 bcopy (filename, dir, from - filename);
4984 dir[from - filename] = '\0';
4986 for (map = read_name_map (dir); map; map = map->map_next)
4987 if (! strcmp (map->map_from, from))
4988 return map->map_to;
4991 return filename;
4994 /* Insert INC into the include file table, hashed by device and inode number.
4995 If a file with different name but same dev+ino was already in the table,
4996 return 1 and set INC's control macro to the already-known macro. */
4998 static int
4999 lookup_ino_include (inc)
5000 struct include_file *inc;
5002 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5003 % INCLUDE_HASHSIZE);
5004 struct include_file *i = include_ino_hashtab[hash];
5005 inc->next_ino = i;
5006 include_ino_hashtab[hash] = inc;
5008 for (; i; i = i->next_ino)
5009 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5010 && inc->st.st_dev == i->st.st_dev) {
5011 inc->control_macro = i->control_macro;
5012 return 1;
5015 return 0;
5018 /* Process file descriptor F, which corresponds to include file INC,
5019 with output to OP.
5020 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5021 "system" include directories (as decided by the `is_system_include'
5022 function above).
5023 DIRPTR is the link in the dir path through which this file was found,
5024 or 0 if the file name was absolute. */
5026 static void
5027 finclude (f, inc, op, system_header_p, dirptr)
5028 int f;
5029 struct include_file *inc;
5030 FILE_BUF *op;
5031 int system_header_p;
5032 struct file_name_list *dirptr;
5034 char *fname = inc->fname;
5035 int i;
5036 FILE_BUF *fp; /* For input stack frame */
5037 int missing_newline = 0;
5039 CHECK_DEPTH (return;);
5041 fp = &instack[indepth + 1];
5042 bzero ((char *) fp, sizeof (FILE_BUF));
5043 fp->nominal_fname = fp->fname = fname;
5044 fp->inc = inc;
5045 fp->length = 0;
5046 fp->lineno = 1;
5047 fp->if_stack = if_stack;
5048 fp->system_header_p = system_header_p;
5049 fp->dir = dirptr;
5051 if (S_ISREG (inc->st.st_mode)) {
5052 size_t s = (size_t) inc->st.st_size;
5053 if (s != inc->st.st_size || s + 2 < s)
5054 memory_full ();
5055 fp->buf = (U_CHAR *) xmalloc (s + 2);
5056 fp->bufp = fp->buf;
5058 /* Read the file contents, knowing that s is an upper bound
5059 on the number of bytes we can read. */
5060 fp->length = safe_read (f, (char *) fp->buf, s);
5061 if (fp->length < 0) goto nope;
5063 else if (S_ISDIR (inc->st.st_mode)) {
5064 error ("directory `%s' specified in #include", fname);
5065 close (f);
5066 return;
5067 } else {
5068 /* Cannot count its file size before reading.
5069 First read the entire file into heap and
5070 copy them into buffer on stack. */
5072 int bsize = 2000;
5073 int st_size = 0;
5075 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5077 for (;;) {
5078 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5079 if (i < 0)
5080 goto nope; /* error! */
5081 st_size += i;
5082 if (st_size != bsize)
5083 break; /* End of file */
5084 bsize *= 2;
5085 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5087 fp->bufp = fp->buf;
5088 fp->length = st_size;
5091 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5092 /* Backslash-newline at end is not good enough. */
5093 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5094 fp->buf[fp->length++] = '\n';
5095 missing_newline = 1;
5097 fp->buf[fp->length] = '\0';
5099 /* Close descriptor now, so nesting does not use lots of descriptors. */
5100 close (f);
5102 /* Must do this before calling trigraph_pcp, so that the correct file name
5103 will be printed in warning messages. */
5105 indepth++;
5106 input_file_stack_tick++;
5108 if (!no_trigraphs)
5109 trigraph_pcp (fp);
5111 output_line_directive (fp, op, 0, enter_file);
5112 rescan (op, 0);
5114 if (missing_newline)
5115 fp->lineno--;
5117 if (pedantic && missing_newline)
5118 pedwarn ("file does not end in newline");
5120 indepth--;
5121 input_file_stack_tick++;
5122 output_line_directive (&instack[indepth], op, 0, leave_file);
5123 free (fp->buf);
5124 return;
5126 nope:
5128 perror_with_name (fname);
5129 close (f);
5130 free (fp->buf);
5133 /* Record that inclusion of the include file INC
5134 should be controlled by the macro named MACRO_NAME.
5135 This means that trying to include the file again
5136 will do something if that macro is defined. */
5138 static void
5139 record_control_macro (inc, macro_name)
5140 struct include_file *inc;
5141 U_CHAR *macro_name;
5143 if (!inc->control_macro || inc->control_macro[0])
5144 inc->control_macro = macro_name;
5147 /* Load the specified precompiled header into core, and verify its
5148 preconditions. PCF indicates the file descriptor to read, which must
5149 be a regular file. *ST is its file status.
5150 FNAME indicates the file name of the original header.
5151 *LIMIT will be set to an address one past the end of the file.
5152 If the preconditions of the file are not satisfied, the buffer is
5153 freed and we return 0. If the preconditions are satisfied, return
5154 the address of the buffer following the preconditions. The buffer, in
5155 this case, should never be freed because various pieces of it will
5156 be referred to until all precompiled strings are output at the end of
5157 the run. */
5159 static char *
5160 check_precompiled (pcf, st, fname, limit)
5161 int pcf;
5162 struct stat *st;
5163 char *fname;
5164 char **limit;
5166 int length = 0;
5167 char *buf;
5168 char *cp;
5170 if (pcp_outfile)
5171 return 0;
5173 if (S_ISREG (st->st_mode))
5175 size_t s = (size_t) st->st_size;
5176 if (s != st->st_size || s + 2 < s)
5177 memory_full ();
5178 buf = xmalloc (s + 2);
5179 length = safe_read (pcf, buf, s);
5180 if (length < 0)
5181 goto nope;
5183 else
5184 abort ();
5186 if (length > 0 && buf[length-1] != '\n')
5187 buf[length++] = '\n';
5188 buf[length] = '\0';
5190 *limit = buf + length;
5192 /* File is in core. Check the preconditions. */
5193 if (!check_preconditions (buf))
5194 goto nope;
5195 for (cp = buf; *cp; cp++)
5197 #ifdef DEBUG_PCP
5198 fprintf (stderr, "Using preinclude %s\n", fname);
5199 #endif
5200 return cp + 1;
5202 nope:
5203 #ifdef DEBUG_PCP
5204 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5205 #endif
5206 free (buf);
5207 return 0;
5210 /* PREC (null terminated) points to the preconditions of a
5211 precompiled header. These are a series of #define and #undef
5212 lines which must match the current contents of the hash
5213 table. */
5215 static int
5216 check_preconditions (prec)
5217 char *prec;
5219 MACRODEF mdef;
5220 char *lineend;
5222 while (*prec) {
5223 lineend = index (prec, '\n');
5225 if (*prec++ != '#') {
5226 error ("Bad format encountered while reading precompiled file");
5227 return 0;
5229 if (!strncmp (prec, "define", 6)) {
5230 HASHNODE *hp;
5232 prec += 6;
5233 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5235 if (mdef.defn == 0)
5236 abort ();
5238 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5239 || (hp->type != T_MACRO && hp->type != T_CONST)
5240 || (hp->type == T_MACRO
5241 && !compare_defs (mdef.defn, hp->value.defn)
5242 && (mdef.defn->length != 2
5243 || mdef.defn->expansion[0] != '\n'
5244 || mdef.defn->expansion[1] != ' ')))
5245 return 0;
5246 } else if (!strncmp (prec, "undef", 5)) {
5247 char *name;
5248 int len;
5250 prec += 5;
5251 while (is_hor_space[(U_CHAR) *prec])
5252 prec++;
5253 name = prec;
5254 while (is_idchar[(U_CHAR) *prec])
5255 prec++;
5256 len = prec - name;
5258 if (lookup ((U_CHAR *) name, len, -1))
5259 return 0;
5260 } else {
5261 error ("Bad format encountered while reading precompiled file");
5262 return 0;
5264 prec = lineend + 1;
5266 /* They all passed successfully */
5267 return 1;
5270 /* Process the main body of a precompiled file. BUF points to the
5271 string section of the file, following the preconditions. LIMIT is one
5272 character past the end. NAME is the name of the file being read
5273 in. OP is the main output buffer. */
5275 static void
5276 pcfinclude (buf, limit, name, op)
5277 U_CHAR *buf, *limit, *name;
5278 FILE_BUF *op;
5280 FILE_BUF tmpbuf;
5281 int nstrings;
5282 U_CHAR *cp = buf;
5284 /* First in the file comes 4 bytes indicating the number of strings, */
5285 /* in network byte order. (MSB first). */
5286 nstrings = *cp++;
5287 nstrings = (nstrings << 8) | *cp++;
5288 nstrings = (nstrings << 8) | *cp++;
5289 nstrings = (nstrings << 8) | *cp++;
5291 /* Looping over each string... */
5292 while (nstrings--) {
5293 U_CHAR *string_start;
5294 U_CHAR *endofthiskey;
5295 STRINGDEF *str;
5296 int nkeys;
5298 /* Each string starts with a STRINGDEF structure (str), followed */
5299 /* by the text of the string (string_start) */
5301 /* First skip to a longword boundary */
5302 /* ??? Why a 4-byte boundary? On all machines? */
5303 /* NOTE: This works correctly even if size_t
5304 is narrower than a pointer.
5305 Do not try risky measures here to get another type to use!
5306 Do not include stddef.h--it will fail! */
5307 if ((size_t) cp & 3)
5308 cp += 4 - ((size_t) cp & 3);
5310 /* Now get the string. */
5311 str = (STRINGDEF *) (GENERIC_PTR) cp;
5312 string_start = cp += sizeof (STRINGDEF);
5314 for (; *cp; cp++) /* skip the string */
5317 /* We need to macro expand the string here to ensure that the
5318 proper definition environment is in place. If it were only
5319 expanded when we find out it is needed, macros necessary for
5320 its proper expansion might have had their definitions changed. */
5321 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5322 /* Lineno is already set in the precompiled file */
5323 str->contents = tmpbuf.buf;
5324 str->len = tmpbuf.length;
5325 str->writeflag = 0;
5326 str->filename = name;
5327 str->output_mark = outbuf.bufp - outbuf.buf;
5329 str->chain = 0;
5330 *stringlist_tailp = str;
5331 stringlist_tailp = &str->chain;
5333 /* Next comes a fourbyte number indicating the number of keys
5334 for this string. */
5335 nkeys = *cp++;
5336 nkeys = (nkeys << 8) | *cp++;
5337 nkeys = (nkeys << 8) | *cp++;
5338 nkeys = (nkeys << 8) | *cp++;
5340 /* If this number is -1, then the string is mandatory. */
5341 if (nkeys == -1)
5342 str->writeflag = 1;
5343 else
5344 /* Otherwise, for each key, */
5345 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5346 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5347 HASHNODE *hp;
5349 /* It starts with a KEYDEF structure */
5350 cp += sizeof (KEYDEF);
5352 /* Find the end of the key. At the end of this for loop we
5353 advance CP to the start of the next key using this variable. */
5354 endofthiskey = cp + strlen ((char *) cp);
5355 kp->str = str;
5357 /* Expand the key, and enter it into the hash table. */
5358 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5359 tmpbuf.bufp = tmpbuf.buf;
5361 while (is_hor_space[*tmpbuf.bufp])
5362 tmpbuf.bufp++;
5363 if (!is_idstart[*tmpbuf.bufp]
5364 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5365 str->writeflag = 1;
5366 continue;
5369 hp = lookup (tmpbuf.bufp, -1, -1);
5370 if (hp == NULL) {
5371 kp->chain = 0;
5372 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5374 else if (hp->type == T_PCSTRING) {
5375 kp->chain = hp->value.keydef;
5376 hp->value.keydef = kp;
5378 else
5379 str->writeflag = 1;
5382 /* This output_line_directive serves to switch us back to the current
5383 input file in case some of these strings get output (which will
5384 result in line directives for the header file being output). */
5385 output_line_directive (&instack[indepth], op, 0, enter_file);
5388 /* Called from rescan when it hits a key for strings. Mark them all
5389 used and clean up. */
5391 static void
5392 pcstring_used (hp)
5393 HASHNODE *hp;
5395 KEYDEF *kp;
5397 for (kp = hp->value.keydef; kp; kp = kp->chain)
5398 kp->str->writeflag = 1;
5399 delete_macro (hp);
5402 /* Write the output, interspersing precompiled strings in their
5403 appropriate places. */
5405 static void
5406 write_output ()
5408 STRINGDEF *next_string;
5409 U_CHAR *cur_buf_loc;
5410 int line_directive_len = 80;
5411 char *line_directive = xmalloc (line_directive_len);
5412 int len;
5414 /* In each run through the loop, either cur_buf_loc ==
5415 next_string_loc, in which case we print a series of strings, or
5416 it is less than next_string_loc, in which case we write some of
5417 the buffer. */
5418 cur_buf_loc = outbuf.buf;
5419 next_string = stringlist;
5421 while (cur_buf_loc < outbuf.bufp || next_string) {
5422 if (next_string
5423 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5424 if (next_string->writeflag) {
5425 len = 4 * strlen ((char *) next_string->filename) + 32;
5426 while (len > line_directive_len)
5427 line_directive = xrealloc (line_directive,
5428 line_directive_len *= 2);
5429 sprintf (line_directive, "\n# %d ", next_string->lineno);
5430 strcpy (quote_string (line_directive + strlen (line_directive),
5431 (char *) next_string->filename),
5432 "\n");
5433 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5434 safe_write (fileno (stdout),
5435 (char *) next_string->contents, next_string->len);
5437 next_string = next_string->chain;
5439 else {
5440 len = (next_string
5441 ? (next_string->output_mark
5442 - (cur_buf_loc - outbuf.buf))
5443 : outbuf.bufp - cur_buf_loc);
5445 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5446 cur_buf_loc += len;
5449 free (line_directive);
5452 /* Pass a directive through to the output file.
5453 BUF points to the contents of the directive, as a contiguous string.
5454 LIMIT points to the first character past the end of the directive.
5455 KEYWORD is the keyword-table entry for the directive. */
5457 static void
5458 pass_thru_directive (buf, limit, op, keyword)
5459 U_CHAR *buf, *limit;
5460 FILE_BUF *op;
5461 struct directive *keyword;
5463 register unsigned keyword_length = keyword->length;
5465 check_expand (op, 1 + keyword_length + (limit - buf));
5466 *op->bufp++ = '#';
5467 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5468 op->bufp += keyword_length;
5469 if (limit != buf && buf[0] != ' ')
5470 *op->bufp++ = ' ';
5471 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5472 op->bufp += (limit - buf);
5473 #if 0
5474 *op->bufp++ = '\n';
5475 /* Count the line we have just made in the output,
5476 to get in sync properly. */
5477 op->lineno++;
5478 #endif
5481 /* The arglist structure is built by do_define to tell
5482 collect_definition where the argument names begin. That
5483 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5484 would contain pointers to the strings x, y, and z.
5485 Collect_definition would then build a DEFINITION node,
5486 with reflist nodes pointing to the places x, y, and z had
5487 appeared. So the arglist is just convenience data passed
5488 between these two routines. It is not kept around after
5489 the current #define has been processed and entered into the
5490 hash table. */
5492 struct arglist {
5493 struct arglist *next;
5494 U_CHAR *name;
5495 int length;
5496 int argno;
5497 char rest_args;
5500 /* Create a DEFINITION node from a #define directive. Arguments are
5501 as for do_define. */
5503 static MACRODEF
5504 create_definition (buf, limit, op)
5505 U_CHAR *buf, *limit;
5506 FILE_BUF *op;
5508 U_CHAR *bp; /* temp ptr into input buffer */
5509 U_CHAR *symname; /* remember where symbol name starts */
5510 int sym_length; /* and how long it is */
5511 int line = instack[indepth].lineno;
5512 char *file = instack[indepth].nominal_fname;
5513 int rest_args = 0;
5515 DEFINITION *defn;
5516 int arglengths = 0; /* Accumulate lengths of arg names
5517 plus number of args. */
5518 MACRODEF mdef;
5520 bp = buf;
5522 while (is_hor_space[*bp])
5523 bp++;
5525 symname = bp; /* remember where it starts */
5526 sym_length = check_macro_name (bp, "macro");
5527 bp += sym_length;
5529 /* Lossage will occur if identifiers or control keywords are broken
5530 across lines using backslash. This is not the right place to take
5531 care of that. */
5533 if (*bp == '(') {
5534 struct arglist *arg_ptrs = NULL;
5535 int argno = 0;
5537 bp++; /* skip '(' */
5538 SKIP_WHITE_SPACE (bp);
5540 /* Loop over macro argument names. */
5541 while (*bp != ')') {
5542 struct arglist *temp;
5544 temp = (struct arglist *) alloca (sizeof (struct arglist));
5545 temp->name = bp;
5546 temp->next = arg_ptrs;
5547 temp->argno = argno++;
5548 temp->rest_args = 0;
5549 arg_ptrs = temp;
5551 if (rest_args)
5552 pedwarn ("another parameter follows `%s'",
5553 rest_extension);
5555 if (!is_idstart[*bp])
5556 pedwarn ("invalid character in macro parameter name");
5558 /* Find the end of the arg name. */
5559 while (is_idchar[*bp]) {
5560 bp++;
5561 /* do we have a "special" rest-args extension here? */
5562 if (limit - bp > REST_EXTENSION_LENGTH
5563 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5564 rest_args = 1;
5565 temp->rest_args = 1;
5566 break;
5569 temp->length = bp - temp->name;
5570 if (rest_args == 1)
5571 bp += REST_EXTENSION_LENGTH;
5572 arglengths += temp->length + 2;
5573 SKIP_WHITE_SPACE (bp);
5574 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5575 error ("badly punctuated parameter list in `#define'");
5576 goto nope;
5578 if (*bp == ',') {
5579 bp++;
5580 SKIP_WHITE_SPACE (bp);
5581 /* A comma at this point can only be followed by an identifier. */
5582 if (!is_idstart[*bp]) {
5583 error ("badly punctuated parameter list in `#define'");
5584 goto nope;
5587 if (bp >= limit) {
5588 error ("unterminated parameter list in `#define'");
5589 goto nope;
5592 struct arglist *otemp;
5594 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5595 if (temp->length == otemp->length
5596 && bcmp (temp->name, otemp->name, temp->length) == 0) {
5597 error ("duplicate argument name `%.*s' in `#define'",
5598 temp->length, temp->name);
5599 goto nope;
5604 ++bp; /* skip paren */
5605 SKIP_WHITE_SPACE (bp);
5606 /* now everything from bp before limit is the definition. */
5607 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5608 defn->rest_args = rest_args;
5610 /* Now set defn->args.argnames to the result of concatenating
5611 the argument names in reverse order
5612 with comma-space between them. */
5613 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5615 struct arglist *temp;
5616 int i = 0;
5617 for (temp = arg_ptrs; temp; temp = temp->next) {
5618 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5619 i += temp->length;
5620 if (temp->next != 0) {
5621 defn->args.argnames[i++] = ',';
5622 defn->args.argnames[i++] = ' ';
5625 defn->args.argnames[i] = 0;
5627 } else {
5628 /* Simple expansion or empty definition. */
5630 if (bp < limit)
5632 if (is_hor_space[*bp]) {
5633 bp++;
5634 SKIP_WHITE_SPACE (bp);
5635 } else if (sym_length) {
5636 switch (*bp) {
5637 case '!': case '"': case '#': case '%': case '&': case '\'':
5638 case ')': case '*': case '+': case ',': case '-': case '.':
5639 case '/': case ':': case ';': case '<': case '=': case '>':
5640 case '?': case '[': case '\\': case ']': case '^': case '{':
5641 case '|': case '}': case '~':
5642 warning ("missing white space after `#define %.*s'",
5643 sym_length, symname);
5644 break;
5646 default:
5647 pedwarn ("missing white space after `#define %.*s'",
5648 sym_length, symname);
5649 break;
5653 /* Now everything from bp before limit is the definition. */
5654 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5655 defn->args.argnames = (U_CHAR *) "";
5658 defn->line = line;
5659 defn->file = file;
5661 /* OP is null if this is a predefinition */
5662 defn->predefined = !op;
5663 mdef.defn = defn;
5664 mdef.symnam = symname;
5665 mdef.symlen = sym_length;
5667 return mdef;
5669 nope:
5670 mdef.defn = 0;
5671 return mdef;
5674 /* Process a #define directive.
5675 BUF points to the contents of the #define directive, as a contiguous string.
5676 LIMIT points to the first character past the end of the definition.
5677 KEYWORD is the keyword-table entry for #define. */
5679 static int
5680 do_define (buf, limit, op, keyword)
5681 U_CHAR *buf, *limit;
5682 FILE_BUF *op;
5683 struct directive *keyword;
5685 int hashcode;
5686 MACRODEF mdef;
5688 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5689 if (pcp_outfile && op)
5690 pass_thru_directive (buf, limit, op, keyword);
5692 mdef = create_definition (buf, limit, op);
5693 if (mdef.defn == 0)
5694 goto nope;
5696 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5699 HASHNODE *hp;
5700 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5701 int ok = 0;
5702 /* Redefining a precompiled key is ok. */
5703 if (hp->type == T_PCSTRING)
5704 ok = 1;
5705 /* Redefining a macro is ok if the definitions are the same. */
5706 else if (hp->type == T_MACRO)
5707 ok = ! compare_defs (mdef.defn, hp->value.defn);
5708 /* Redefining a constant is ok with -D. */
5709 else if (hp->type == T_CONST)
5710 ok = ! done_initializing;
5711 /* Print the warning if it's not ok. */
5712 if (!ok) {
5713 /* If we are passing through #define and #undef directives, do
5714 that for this re-definition now. */
5715 if (debug_output && op)
5716 pass_thru_directive (buf, limit, op, keyword);
5718 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5719 if (hp->type == T_MACRO)
5720 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5721 "this is the location of the previous definition");
5723 /* Replace the old definition. */
5724 hp->type = T_MACRO;
5725 hp->value.defn = mdef.defn;
5726 } else {
5727 /* If we are passing through #define and #undef directives, do
5728 that for this new definition now. */
5729 if (debug_output && op)
5730 pass_thru_directive (buf, limit, op, keyword);
5731 install (mdef.symnam, mdef.symlen, T_MACRO,
5732 (char *) mdef.defn, hashcode);
5736 return 0;
5738 nope:
5740 return 1;
5743 /* Check a purported macro name SYMNAME, and yield its length.
5744 USAGE is the kind of name this is intended for. */
5746 static int
5747 check_macro_name (symname, usage)
5748 U_CHAR *symname;
5749 char *usage;
5751 U_CHAR *p;
5752 int sym_length;
5754 for (p = symname; is_idchar[*p]; p++)
5756 sym_length = p - symname;
5757 if (sym_length == 0
5758 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5759 error ("invalid %s name", usage);
5760 else if (!is_idstart[*symname]
5761 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5762 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5763 return sym_length;
5766 /* Return zero if two DEFINITIONs are isomorphic. */
5768 static int
5769 compare_defs (d1, d2)
5770 DEFINITION *d1, *d2;
5772 register struct reflist *a1, *a2;
5773 register U_CHAR *p1 = d1->expansion;
5774 register U_CHAR *p2 = d2->expansion;
5775 int first = 1;
5777 if (d1->nargs != d2->nargs)
5778 return 1;
5779 if (pedantic
5780 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5781 return 1;
5782 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5783 a1 = a1->next, a2 = a2->next) {
5784 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5785 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5786 || a1->argno != a2->argno
5787 || a1->stringify != a2->stringify
5788 || a1->raw_before != a2->raw_before
5789 || a1->raw_after != a2->raw_after)
5790 return 1;
5791 first = 0;
5792 p1 += a1->nchars;
5793 p2 += a2->nchars;
5795 if (a1 != a2)
5796 return 1;
5797 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5798 p2, d2->length - (p2 - d2->expansion), 1))
5799 return 1;
5800 return 0;
5803 /* Return 1 if two parts of two macro definitions are effectively different.
5804 One of the parts starts at BEG1 and has LEN1 chars;
5805 the other has LEN2 chars at BEG2.
5806 Any sequence of whitespace matches any other sequence of whitespace.
5807 FIRST means these parts are the first of a macro definition;
5808 so ignore leading whitespace entirely.
5809 LAST means these parts are the last of a macro definition;
5810 so ignore trailing whitespace entirely. */
5812 static int
5813 comp_def_part (first, beg1, len1, beg2, len2, last)
5814 int first;
5815 U_CHAR *beg1, *beg2;
5816 int len1, len2;
5817 int last;
5819 register U_CHAR *end1 = beg1 + len1;
5820 register U_CHAR *end2 = beg2 + len2;
5821 if (first) {
5822 while (beg1 != end1 && is_space[*beg1]) beg1++;
5823 while (beg2 != end2 && is_space[*beg2]) beg2++;
5825 if (last) {
5826 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5827 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5829 while (beg1 != end1 && beg2 != end2) {
5830 if (is_space[*beg1] && is_space[*beg2]) {
5831 while (beg1 != end1 && is_space[*beg1]) beg1++;
5832 while (beg2 != end2 && is_space[*beg2]) beg2++;
5833 } else if (*beg1 == *beg2) {
5834 beg1++; beg2++;
5835 } else break;
5837 return (beg1 != end1) || (beg2 != end2);
5840 /* Read a replacement list for a macro with parameters.
5841 Build the DEFINITION structure.
5842 Reads characters of text starting at BUF until END.
5843 ARGLIST specifies the formal parameters to look for
5844 in the text of the definition; NARGS is the number of args
5845 in that list, or -1 for a macro name that wants no argument list.
5846 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5847 and NAMELEN is its length in characters.
5849 Note that comments, backslash-newlines, and leading white space
5850 have already been deleted from the argument. */
5852 /* If there is no trailing whitespace, a Newline Space is added at the end
5853 to prevent concatenation that would be contrary to the standard. */
5855 static DEFINITION *
5856 collect_expansion (buf, end, nargs, arglist)
5857 U_CHAR *buf, *end;
5858 int nargs;
5859 struct arglist *arglist;
5861 DEFINITION *defn;
5862 register U_CHAR *p, *limit, *lastp, *exp_p;
5863 struct reflist *endpat = NULL;
5864 /* Pointer to first nonspace after last ## seen. */
5865 U_CHAR *concat = 0;
5866 /* Pointer to first nonspace after last single-# seen. */
5867 U_CHAR *stringify = 0;
5868 /* How those tokens were spelled. */
5869 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5870 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5871 int maxsize;
5872 int expected_delimiter = '\0';
5874 /* Scan thru the replacement list, ignoring comments and quoted
5875 strings, picking up on the macro calls. It does a linear search
5876 thru the arg list on every potential symbol. Profiling might say
5877 that something smarter should happen. */
5879 if (end < buf)
5880 abort ();
5882 /* Find the beginning of the trailing whitespace. */
5883 limit = end;
5884 p = buf;
5885 while (p < limit && is_space[limit[-1]]) limit--;
5887 /* Allocate space for the text in the macro definition.
5888 Each input char may or may not need 1 byte,
5889 so this is an upper bound.
5890 The extra 3 are for invented trailing newline-marker and final null. */
5891 maxsize = (sizeof (DEFINITION)
5892 + (limit - p) + 3);
5893 defn = (DEFINITION *) xcalloc (1, maxsize);
5895 defn->nargs = nargs;
5896 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5897 lastp = exp_p;
5899 if (p[0] == '#'
5900 ? p[1] == '#'
5901 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5902 error ("`##' at start of macro definition");
5903 p += p[0] == '#' ? 2 : 4;
5906 /* Process the main body of the definition. */
5907 while (p < limit) {
5908 int skipped_arg = 0;
5909 register U_CHAR c = *p++;
5911 *exp_p++ = c;
5913 if (!traditional) {
5914 switch (c) {
5915 case '\'':
5916 case '\"':
5917 if (expected_delimiter != '\0') {
5918 if (c == expected_delimiter)
5919 expected_delimiter = '\0';
5920 } else
5921 expected_delimiter = c;
5922 break;
5924 case '\\':
5925 if (p < limit && expected_delimiter) {
5926 /* In a string, backslash goes through
5927 and makes next char ordinary. */
5928 *exp_p++ = *p++;
5930 break;
5932 case '%':
5933 if (!expected_delimiter && *p == ':') {
5934 /* %: is not a digraph if preceded by an odd number of '<'s. */
5935 U_CHAR *p0 = p - 1;
5936 while (buf < p0 && p0[-1] == '<')
5937 p0--;
5938 if ((p - p0) & 1) {
5939 /* Treat %:%: as ## and %: as #. */
5940 if (p[1] == '%' && p[2] == ':') {
5941 p += 2;
5942 goto sharp_sharp_token;
5944 if (nargs >= 0) {
5945 p++;
5946 goto sharp_token;
5950 break;
5952 case '#':
5953 /* # is ordinary inside a string. */
5954 if (expected_delimiter)
5955 break;
5956 if (*p == '#') {
5957 sharp_sharp_token:
5958 /* ##: concatenate preceding and following tokens. */
5959 /* Take out the first #, discard preceding whitespace. */
5960 exp_p--;
5961 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5962 --exp_p;
5963 /* Skip the second #. */
5964 p++;
5965 concat_sharp_token_type = c;
5966 if (is_hor_space[*p]) {
5967 concat_sharp_token_type = c + 1;
5968 p++;
5969 SKIP_WHITE_SPACE (p);
5971 concat = p;
5972 if (p == limit)
5973 error ("`##' at end of macro definition");
5974 } else if (nargs >= 0) {
5975 /* Single #: stringify following argument ref.
5976 Don't leave the # in the expansion. */
5977 sharp_token:
5978 exp_p--;
5979 stringify_sharp_token_type = c;
5980 if (is_hor_space[*p]) {
5981 stringify_sharp_token_type = c + 1;
5982 p++;
5983 SKIP_WHITE_SPACE (p);
5985 if (! is_idstart[*p] || nargs == 0
5986 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
5987 error ("`#' operator is not followed by a macro argument name");
5988 else
5989 stringify = p;
5991 break;
5993 } else {
5994 /* In -traditional mode, recognize arguments inside strings and
5995 and character constants, and ignore special properties of #.
5996 Arguments inside strings are considered "stringified", but no
5997 extra quote marks are supplied. */
5998 switch (c) {
5999 case '\'':
6000 case '\"':
6001 if (expected_delimiter != '\0') {
6002 if (c == expected_delimiter)
6003 expected_delimiter = '\0';
6004 } else
6005 expected_delimiter = c;
6006 break;
6008 case '\\':
6009 /* Backslash quotes delimiters and itself, but not macro args. */
6010 if (expected_delimiter != 0 && p < limit
6011 && (*p == expected_delimiter || *p == '\\')) {
6012 *exp_p++ = *p++;
6013 continue;
6015 break;
6017 case '/':
6018 if (expected_delimiter != '\0') /* No comments inside strings. */
6019 break;
6020 if (*p == '*') {
6021 /* If we find a comment that wasn't removed by handle_directive,
6022 this must be -traditional. So replace the comment with
6023 nothing at all. */
6024 exp_p--;
6025 while (++p < limit) {
6026 if (p[0] == '*' && p[1] == '/') {
6027 p += 2;
6028 break;
6031 #if 0
6032 /* Mark this as a concatenation-point, as if it had been ##. */
6033 concat = p;
6034 #endif
6036 break;
6040 /* Handle the start of a symbol. */
6041 if (is_idchar[c] && nargs > 0) {
6042 U_CHAR *id_beg = p - 1;
6043 int id_len;
6045 --exp_p;
6046 while (p != limit && is_idchar[*p]) p++;
6047 id_len = p - id_beg;
6049 if (is_idstart[c]
6050 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6051 register struct arglist *arg;
6053 for (arg = arglist; arg != NULL; arg = arg->next) {
6054 struct reflist *tpat;
6056 if (arg->name[0] == c
6057 && arg->length == id_len
6058 && bcmp (arg->name, id_beg, id_len) == 0) {
6059 enum sharp_token_type tpat_stringify;
6060 if (expected_delimiter) {
6061 if (warn_stringify) {
6062 if (traditional) {
6063 warning ("macro argument `%.*s' is stringified.",
6064 id_len, arg->name);
6065 } else {
6066 warning ("macro arg `%.*s' would be stringified with -traditional.",
6067 id_len, arg->name);
6070 /* If ANSI, don't actually substitute inside a string. */
6071 if (!traditional)
6072 break;
6073 tpat_stringify = SHARP_TOKEN;
6074 } else {
6075 tpat_stringify
6076 = (stringify == id_beg
6077 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6079 /* make a pat node for this arg and append it to the end of
6080 the pat list */
6081 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6082 tpat->next = NULL;
6083 tpat->raw_before
6084 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6085 tpat->raw_after = NO_SHARP_TOKEN;
6086 tpat->rest_args = arg->rest_args;
6087 tpat->stringify = tpat_stringify;
6089 if (endpat == NULL)
6090 defn->pattern = tpat;
6091 else
6092 endpat->next = tpat;
6093 endpat = tpat;
6095 tpat->argno = arg->argno;
6096 tpat->nchars = exp_p - lastp;
6098 register U_CHAR *p1 = p;
6099 SKIP_WHITE_SPACE (p1);
6100 if (p1[0]=='#'
6101 ? p1[1]=='#'
6102 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6103 tpat->raw_after = p1[0] + (p != p1);
6105 lastp = exp_p; /* place to start copying from next time */
6106 skipped_arg = 1;
6107 break;
6112 /* If this was not a macro arg, copy it into the expansion. */
6113 if (! skipped_arg) {
6114 register U_CHAR *lim1 = p;
6115 p = id_beg;
6116 while (p != lim1)
6117 *exp_p++ = *p++;
6118 if (stringify == id_beg)
6119 error ("`#' operator should be followed by a macro argument name");
6124 if (!traditional && expected_delimiter == 0) {
6125 /* If ANSI, put in a newline-space marker to prevent token pasting.
6126 But not if "inside a string" (which in ANSI mode happens only for
6127 -D option). */
6128 *exp_p++ = '\n';
6129 *exp_p++ = ' ';
6132 *exp_p = '\0';
6134 defn->length = exp_p - defn->expansion;
6136 /* Crash now if we overrun the allocated size. */
6137 if (defn->length + 1 > maxsize)
6138 abort ();
6140 #if 0
6141 /* This isn't worth the time it takes. */
6142 /* give back excess storage */
6143 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6144 #endif
6146 return defn;
6149 static int
6150 do_assert (buf, limit, op, keyword)
6151 U_CHAR *buf, *limit;
6152 FILE_BUF *op;
6153 struct directive *keyword;
6155 U_CHAR *bp; /* temp ptr into input buffer */
6156 U_CHAR *symname; /* remember where symbol name starts */
6157 int sym_length; /* and how long it is */
6158 struct arglist *tokens = NULL;
6160 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6161 pedwarn ("ANSI C does not allow `#assert'");
6163 bp = buf;
6165 while (is_hor_space[*bp])
6166 bp++;
6168 symname = bp; /* remember where it starts */
6169 sym_length = check_macro_name (bp, "assertion");
6170 bp += sym_length;
6171 /* #define doesn't do this, but we should. */
6172 SKIP_WHITE_SPACE (bp);
6174 /* Lossage will occur if identifiers or control tokens are broken
6175 across lines using backslash. This is not the right place to take
6176 care of that. */
6178 if (*bp != '(') {
6179 error ("missing token-sequence in `#assert'");
6180 return 1;
6184 int error_flag = 0;
6186 bp++; /* skip '(' */
6187 SKIP_WHITE_SPACE (bp);
6189 tokens = read_token_list (&bp, limit, &error_flag);
6190 if (error_flag)
6191 return 1;
6192 if (tokens == 0) {
6193 error ("empty token-sequence in `#assert'");
6194 return 1;
6197 ++bp; /* skip paren */
6198 SKIP_WHITE_SPACE (bp);
6201 /* If this name isn't already an assertion name, make it one.
6202 Error if it was already in use in some other way. */
6205 ASSERTION_HASHNODE *hp;
6206 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6207 struct tokenlist_list *value
6208 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6210 hp = assertion_lookup (symname, sym_length, hashcode);
6211 if (hp == NULL) {
6212 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6213 error ("`defined' redefined as assertion");
6214 hp = assertion_install (symname, sym_length, hashcode);
6217 /* Add the spec'd token-sequence to the list of such. */
6218 value->tokens = tokens;
6219 value->next = hp->value;
6220 hp->value = value;
6223 return 0;
6226 static int
6227 do_unassert (buf, limit, op, keyword)
6228 U_CHAR *buf, *limit;
6229 FILE_BUF *op;
6230 struct directive *keyword;
6232 U_CHAR *bp; /* temp ptr into input buffer */
6233 U_CHAR *symname; /* remember where symbol name starts */
6234 int sym_length; /* and how long it is */
6236 struct arglist *tokens = NULL;
6237 int tokens_specified = 0;
6239 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6240 pedwarn ("ANSI C does not allow `#unassert'");
6242 bp = buf;
6244 while (is_hor_space[*bp])
6245 bp++;
6247 symname = bp; /* remember where it starts */
6248 sym_length = check_macro_name (bp, "assertion");
6249 bp += sym_length;
6250 /* #define doesn't do this, but we should. */
6251 SKIP_WHITE_SPACE (bp);
6253 /* Lossage will occur if identifiers or control tokens are broken
6254 across lines using backslash. This is not the right place to take
6255 care of that. */
6257 if (*bp == '(') {
6258 int error_flag = 0;
6260 bp++; /* skip '(' */
6261 SKIP_WHITE_SPACE (bp);
6263 tokens = read_token_list (&bp, limit, &error_flag);
6264 if (error_flag)
6265 return 1;
6266 if (tokens == 0) {
6267 error ("empty token list in `#unassert'");
6268 return 1;
6271 tokens_specified = 1;
6273 ++bp; /* skip paren */
6274 SKIP_WHITE_SPACE (bp);
6278 ASSERTION_HASHNODE *hp;
6279 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6280 struct tokenlist_list *tail, *prev;
6282 hp = assertion_lookup (symname, sym_length, hashcode);
6283 if (hp == NULL)
6284 return 1;
6286 /* If no token list was specified, then eliminate this assertion
6287 entirely. */
6288 if (! tokens_specified) {
6289 struct tokenlist_list *next;
6290 for (tail = hp->value; tail; tail = next) {
6291 next = tail->next;
6292 free_token_list (tail->tokens);
6293 free (tail);
6295 delete_assertion (hp);
6296 } else {
6297 /* If a list of tokens was given, then delete any matching list. */
6299 tail = hp->value;
6300 prev = 0;
6301 while (tail) {
6302 struct tokenlist_list *next = tail->next;
6303 if (compare_token_lists (tail->tokens, tokens)) {
6304 if (prev)
6305 prev->next = next;
6306 else
6307 hp->value = tail->next;
6308 free_token_list (tail->tokens);
6309 free (tail);
6310 } else {
6311 prev = tail;
6313 tail = next;
6318 return 0;
6321 /* Test whether there is an assertion named NAME
6322 and optionally whether it has an asserted token list TOKENS.
6323 NAME is not null terminated; its length is SYM_LENGTH.
6324 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6327 check_assertion (name, sym_length, tokens_specified, tokens)
6328 U_CHAR *name;
6329 int sym_length;
6330 int tokens_specified;
6331 struct arglist *tokens;
6333 ASSERTION_HASHNODE *hp;
6334 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6336 if (pedantic && !instack[indepth].system_header_p)
6337 pedwarn ("ANSI C does not allow testing assertions");
6339 hp = assertion_lookup (name, sym_length, hashcode);
6340 if (hp == NULL)
6341 /* It is not an assertion; just return false. */
6342 return 0;
6344 /* If no token list was specified, then value is 1. */
6345 if (! tokens_specified)
6346 return 1;
6349 struct tokenlist_list *tail;
6351 tail = hp->value;
6353 /* If a list of tokens was given,
6354 then succeed if the assertion records a matching list. */
6356 while (tail) {
6357 if (compare_token_lists (tail->tokens, tokens))
6358 return 1;
6359 tail = tail->next;
6362 /* Fail if the assertion has no matching list. */
6363 return 0;
6367 /* Compare two lists of tokens for equality including order of tokens. */
6369 static int
6370 compare_token_lists (l1, l2)
6371 struct arglist *l1, *l2;
6373 while (l1 && l2) {
6374 if (l1->length != l2->length)
6375 return 0;
6376 if (bcmp (l1->name, l2->name, l1->length))
6377 return 0;
6378 l1 = l1->next;
6379 l2 = l2->next;
6382 /* Succeed if both lists end at the same time. */
6383 return l1 == l2;
6386 /* Read a space-separated list of tokens ending in a close parenthesis.
6387 Return a list of strings, in the order they were written.
6388 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6389 Parse the text starting at *BPP, and update *BPP.
6390 Don't parse beyond LIMIT. */
6392 static struct arglist *
6393 read_token_list (bpp, limit, error_flag)
6394 U_CHAR **bpp;
6395 U_CHAR *limit;
6396 int *error_flag;
6398 struct arglist *token_ptrs = 0;
6399 U_CHAR *bp = *bpp;
6400 int depth = 1;
6402 *error_flag = 0;
6404 /* Loop over the assertion value tokens. */
6405 while (depth > 0) {
6406 struct arglist *temp;
6407 int eofp = 0;
6408 U_CHAR *beg = bp;
6410 /* Find the end of the token. */
6411 if (*bp == '(') {
6412 bp++;
6413 depth++;
6414 } else if (*bp == ')') {
6415 depth--;
6416 if (depth == 0)
6417 break;
6418 bp++;
6419 } else if (*bp == '"' || *bp == '\'')
6420 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6421 else
6422 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6423 && *bp != '"' && *bp != '\'' && bp != limit)
6424 bp++;
6426 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6427 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6428 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6429 temp->name[bp - beg] = 0;
6430 temp->next = token_ptrs;
6431 token_ptrs = temp;
6432 temp->length = bp - beg;
6434 SKIP_WHITE_SPACE (bp);
6436 if (bp >= limit) {
6437 error ("unterminated token sequence in `#assert' or `#unassert'");
6438 *error_flag = -1;
6439 return 0;
6442 *bpp = bp;
6444 /* We accumulated the names in reverse order.
6445 Now reverse them to get the proper order. */
6447 register struct arglist *prev = 0, *this, *next;
6448 for (this = token_ptrs; this; this = next) {
6449 next = this->next;
6450 this->next = prev;
6451 prev = this;
6453 return prev;
6457 static void
6458 free_token_list (tokens)
6459 struct arglist *tokens;
6461 while (tokens) {
6462 struct arglist *next = tokens->next;
6463 free (tokens->name);
6464 free (tokens);
6465 tokens = next;
6469 /* Install a name in the assertion hash table.
6471 If LEN is >= 0, it is the length of the name.
6472 Otherwise, compute the length by scanning the entire name.
6474 If HASH is >= 0, it is the precomputed hash code.
6475 Otherwise, compute the hash code. */
6477 static ASSERTION_HASHNODE *
6478 assertion_install (name, len, hash)
6479 U_CHAR *name;
6480 int len;
6481 int hash;
6483 register ASSERTION_HASHNODE *hp;
6484 register int i, bucket;
6485 register U_CHAR *p, *q;
6487 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6488 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6489 bucket = hash;
6490 hp->bucket_hdr = &assertion_hashtab[bucket];
6491 hp->next = assertion_hashtab[bucket];
6492 assertion_hashtab[bucket] = hp;
6493 hp->prev = NULL;
6494 if (hp->next != NULL)
6495 hp->next->prev = hp;
6496 hp->length = len;
6497 hp->value = 0;
6498 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6499 p = hp->name;
6500 q = name;
6501 for (i = 0; i < len; i++)
6502 *p++ = *q++;
6503 hp->name[len] = 0;
6504 return hp;
6507 /* Find the most recent hash node for name name (ending with first
6508 non-identifier char) installed by install
6510 If LEN is >= 0, it is the length of the name.
6511 Otherwise, compute the length by scanning the entire name.
6513 If HASH is >= 0, it is the precomputed hash code.
6514 Otherwise, compute the hash code. */
6516 static ASSERTION_HASHNODE *
6517 assertion_lookup (name, len, hash)
6518 U_CHAR *name;
6519 int len;
6520 int hash;
6522 register ASSERTION_HASHNODE *bucket;
6524 bucket = assertion_hashtab[hash];
6525 while (bucket) {
6526 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6527 return bucket;
6528 bucket = bucket->next;
6530 return NULL;
6533 static void
6534 delete_assertion (hp)
6535 ASSERTION_HASHNODE *hp;
6538 if (hp->prev != NULL)
6539 hp->prev->next = hp->next;
6540 if (hp->next != NULL)
6541 hp->next->prev = hp->prev;
6543 /* Make sure that the bucket chain header that the deleted guy was
6544 on points to the right thing afterwards. */
6545 if (hp == *hp->bucket_hdr)
6546 *hp->bucket_hdr = hp->next;
6548 free (hp);
6552 * interpret #line directive. Remembers previously seen fnames
6553 * in its very own hash table.
6555 #define FNAME_HASHSIZE 37
6557 static int
6558 do_line (buf, limit, op, keyword)
6559 U_CHAR *buf, *limit;
6560 FILE_BUF *op;
6561 struct directive *keyword;
6563 register U_CHAR *bp;
6564 FILE_BUF *ip = &instack[indepth];
6565 FILE_BUF tem;
6566 int new_lineno;
6567 enum file_change_code file_change = same_file;
6569 /* Expand any macros. */
6570 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6572 /* Point to macroexpanded line, which is null-terminated now. */
6573 bp = tem.buf;
6574 SKIP_WHITE_SPACE (bp);
6576 if (!isdigit (*bp)) {
6577 error ("invalid format `#line' directive");
6578 return 0;
6581 /* The Newline at the end of this line remains to be processed.
6582 To put the next line at the specified line number,
6583 we must store a line number now that is one less. */
6584 new_lineno = atoi ((char *) bp) - 1;
6586 /* NEW_LINENO is one less than the actual line number here. */
6587 if (pedantic && new_lineno < 0)
6588 pedwarn ("line number out of range in `#line' directive");
6590 /* skip over the line number. */
6591 while (isdigit (*bp))
6592 bp++;
6594 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6595 if (*bp && !is_space[*bp]) {
6596 error ("invalid format `#line' directive");
6597 return;
6599 #endif
6601 SKIP_WHITE_SPACE (bp);
6603 if (*bp == '\"') {
6604 static HASHNODE *fname_table[FNAME_HASHSIZE];
6605 HASHNODE *hp, **hash_bucket;
6606 U_CHAR *fname, *p;
6607 int fname_length;
6609 fname = ++bp;
6611 /* Turn the file name, which is a character string literal,
6612 into a null-terminated string. Do this in place. */
6613 p = bp;
6614 for (;;)
6615 switch ((*p++ = *bp++)) {
6616 case '\0':
6617 error ("invalid format `#line' directive");
6618 return 0;
6620 case '\\':
6622 char *bpc = (char *) bp;
6623 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6624 bp = (U_CHAR *) bpc;
6625 if (c < 0)
6626 p--;
6627 else
6628 p[-1] = c;
6630 break;
6632 case '\"':
6633 p[-1] = 0;
6634 goto fname_done;
6636 fname_done:
6637 fname_length = p - fname;
6639 SKIP_WHITE_SPACE (bp);
6640 if (*bp) {
6641 if (pedantic)
6642 pedwarn ("garbage at end of `#line' directive");
6643 if (*bp == '1')
6644 file_change = enter_file;
6645 else if (*bp == '2')
6646 file_change = leave_file;
6647 else if (*bp == '3')
6648 ip->system_header_p = 1;
6649 else if (*bp == '4')
6650 ip->system_header_p = 2;
6651 else {
6652 error ("invalid format `#line' directive");
6653 return 0;
6656 bp++;
6657 SKIP_WHITE_SPACE (bp);
6658 if (*bp == '3') {
6659 ip->system_header_p = 1;
6660 bp++;
6661 SKIP_WHITE_SPACE (bp);
6663 if (*bp == '4') {
6664 ip->system_header_p = 2;
6665 bp++;
6666 SKIP_WHITE_SPACE (bp);
6668 if (*bp) {
6669 error ("invalid format `#line' directive");
6670 return 0;
6674 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6675 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6676 if (hp->length == fname_length &&
6677 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6678 ip->nominal_fname = hp->value.cpval;
6679 break;
6681 if (hp == 0) {
6682 /* Didn't find it; cons up a new one. */
6683 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6684 hp->next = *hash_bucket;
6685 *hash_bucket = hp;
6687 hp->length = fname_length;
6688 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6689 bcopy (fname, hp->value.cpval, fname_length);
6691 } else if (*bp) {
6692 error ("invalid format `#line' directive");
6693 return 0;
6696 ip->lineno = new_lineno;
6697 output_line_directive (ip, op, 0, file_change);
6698 check_expand (op, ip->length - (ip->bufp - ip->buf));
6699 return 0;
6702 /* Remove the definition of a symbol from the symbol table.
6703 according to un*x /lib/cpp, it is not an error to undef
6704 something that has no definitions, so it isn't one here either. */
6706 static int
6707 do_undef (buf, limit, op, keyword)
6708 U_CHAR *buf, *limit;
6709 FILE_BUF *op;
6710 struct directive *keyword;
6712 int sym_length;
6713 HASHNODE *hp;
6714 U_CHAR *orig_buf = buf;
6716 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6717 if (pcp_outfile && op)
6718 pass_thru_directive (buf, limit, op, keyword);
6720 SKIP_WHITE_SPACE (buf);
6721 sym_length = check_macro_name (buf, "macro");
6723 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6724 /* If we are generating additional info for debugging (with -g) we
6725 need to pass through all effective #undef directives. */
6726 if (debug_output && op)
6727 pass_thru_directive (orig_buf, limit, op, keyword);
6728 if (hp->type != T_MACRO)
6729 warning ("undefining `%s'", hp->name);
6730 delete_macro (hp);
6733 if (pedantic) {
6734 buf += sym_length;
6735 SKIP_WHITE_SPACE (buf);
6736 if (buf != limit)
6737 pedwarn ("garbage after `#undef' directive");
6739 return 0;
6742 /* Report an error detected by the program we are processing.
6743 Use the text of the line in the error message.
6744 (We use error because it prints the filename & line#.) */
6746 static int
6747 do_error (buf, limit, op, keyword)
6748 U_CHAR *buf, *limit;
6749 FILE_BUF *op;
6750 struct directive *keyword;
6752 int length = limit - buf;
6753 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6754 bcopy ((char *) buf, (char *) copy, length);
6755 copy[length] = 0;
6756 SKIP_WHITE_SPACE (copy);
6757 error ("#error %s", copy);
6758 return 0;
6761 /* Report a warning detected by the program we are processing.
6762 Use the text of the line in the warning message, then continue.
6763 (We use error because it prints the filename & line#.) */
6765 static int
6766 do_warning (buf, limit, op, keyword)
6767 U_CHAR *buf, *limit;
6768 FILE_BUF *op;
6769 struct directive *keyword;
6771 int length = limit - buf;
6772 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6773 bcopy ((char *) buf, (char *) copy, length);
6774 copy[length] = 0;
6775 SKIP_WHITE_SPACE (copy);
6776 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
6777 if -pedantic-errors is given, #warning should cause an error. */
6778 pedwarn ("#warning %s", copy);
6779 return 0;
6782 /* Remember the name of the current file being read from so that we can
6783 avoid ever including it again. */
6785 static void
6786 do_once ()
6788 int i;
6790 for (i = indepth; i >= 0; i--)
6791 if (instack[i].inc) {
6792 record_control_macro (instack[i].inc, (U_CHAR *) "");
6793 break;
6797 /* Report program identification. */
6799 static int
6800 do_ident (buf, limit, op, keyword)
6801 U_CHAR *buf, *limit;
6802 FILE_BUF *op;
6803 struct directive *keyword;
6805 FILE_BUF trybuf;
6806 int len;
6808 /* Allow #ident in system headers, since that's not user's fault. */
6809 if (pedantic && !instack[indepth].system_header_p)
6810 pedwarn ("ANSI C does not allow `#ident'");
6812 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6813 buf = trybuf.buf;
6814 len = trybuf.bufp - buf;
6816 /* Output expanded directive. */
6817 check_expand (op, 7 + len);
6818 bcopy ("#ident ", (char *) op->bufp, 7);
6819 op->bufp += 7;
6820 bcopy ((char *) buf, (char *) op->bufp, len);
6821 op->bufp += len;
6823 free (buf);
6824 return 0;
6827 /* #pragma and its argument line have already been copied to the output file.
6828 Just check for some recognized pragmas that need validation here. */
6830 static int
6831 do_pragma (buf, limit, op, keyword)
6832 U_CHAR *buf, *limit;
6833 FILE_BUF *op;
6834 struct directive *keyword;
6836 SKIP_WHITE_SPACE (buf);
6837 if (!strncmp ((char *) buf, "once", 4)) {
6838 /* Allow #pragma once in system headers, since that's not the user's
6839 fault. */
6840 if (!instack[indepth].system_header_p)
6841 warning ("`#pragma once' is obsolete");
6842 do_once ();
6845 if (!strncmp ((char *) buf, "implementation", 14)) {
6846 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6847 been included yet. */
6849 int h;
6850 U_CHAR *p = buf + 14, *fname;
6851 SKIP_WHITE_SPACE (p);
6852 if (*p != '\"')
6853 return 0;
6855 fname = p + 1;
6856 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6857 *p = '\0';
6859 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6860 struct include_file *inc;
6861 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6862 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6863 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6864 return 0;
6869 return 0;
6872 #if 0
6873 /* This was a fun hack, but #pragma seems to start to be useful.
6874 By failing to recognize it, we pass it through unchanged to cc1. */
6876 /* The behavior of the #pragma directive is implementation defined.
6877 this implementation defines it as follows. */
6879 static int
6880 do_pragma ()
6882 close (0);
6883 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6884 goto nope;
6885 close (1);
6886 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6887 goto nope;
6888 execl ("/usr/games/hack", "#pragma", 0);
6889 execl ("/usr/games/rogue", "#pragma", 0);
6890 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6891 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6892 nope:
6893 fatal ("You are in a maze of twisty compiler features, all different");
6895 #endif
6897 #ifdef SCCS_DIRECTIVE
6899 /* Just ignore #sccs, on systems where we define it at all. */
6901 static int
6902 do_sccs (buf, limit, op, keyword)
6903 U_CHAR *buf, *limit;
6904 FILE_BUF *op;
6905 struct directive *keyword;
6907 if (pedantic)
6908 pedwarn ("ANSI C does not allow `#sccs'");
6909 return 0;
6912 #endif /* defined (SCCS_DIRECTIVE) */
6914 /* Handle #if directive by
6915 1) inserting special `defined' keyword into the hash table
6916 that gets turned into 0 or 1 by special_symbol (thus,
6917 if the luser has a symbol called `defined' already, it won't
6918 work inside the #if directive)
6919 2) rescan the input into a temporary output buffer
6920 3) pass the output buffer to the yacc parser and collect a value
6921 4) clean up the mess left from steps 1 and 2.
6922 5) call conditional_skip to skip til the next #endif (etc.),
6923 or not, depending on the value from step 3. */
6925 static int
6926 do_if (buf, limit, op, keyword)
6927 U_CHAR *buf, *limit;
6928 FILE_BUF *op;
6929 struct directive *keyword;
6931 HOST_WIDE_INT value;
6932 FILE_BUF *ip = &instack[indepth];
6934 value = eval_if_expression (buf, limit - buf);
6935 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6936 return 0;
6939 /* Handle a #elif directive by not changing if_stack either.
6940 see the comment above do_else. */
6942 static int
6943 do_elif (buf, limit, op, keyword)
6944 U_CHAR *buf, *limit;
6945 FILE_BUF *op;
6946 struct directive *keyword;
6948 HOST_WIDE_INT value;
6949 FILE_BUF *ip = &instack[indepth];
6951 if (if_stack == instack[indepth].if_stack) {
6952 error ("`#elif' not within a conditional");
6953 return 0;
6954 } else {
6955 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6956 error ("`#elif' after `#else'");
6957 fprintf (stderr, " (matches line %d", if_stack->lineno);
6958 if (if_stack->fname != NULL && ip->fname != NULL
6959 && strcmp (if_stack->fname, ip->nominal_fname) != 0)
6960 fprintf (stderr, ", file %s", if_stack->fname);
6961 fprintf (stderr, ")\n");
6963 if_stack->type = T_ELIF;
6966 if (if_stack->if_succeeded)
6967 skip_if_group (ip, 0, op);
6968 else {
6969 value = eval_if_expression (buf, limit - buf);
6970 if (value == 0)
6971 skip_if_group (ip, 0, op);
6972 else {
6973 ++if_stack->if_succeeded; /* continue processing input */
6974 output_line_directive (ip, op, 1, same_file);
6977 return 0;
6980 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
6981 result as a C expression and return the value as an int. */
6983 static HOST_WIDE_INT
6984 eval_if_expression (buf, length)
6985 U_CHAR *buf;
6986 int length;
6988 FILE_BUF temp_obuf;
6989 HASHNODE *save_defined;
6990 HOST_WIDE_INT value;
6992 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
6993 NULL_PTR, -1);
6994 pcp_inside_if = 1;
6995 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6996 pcp_inside_if = 0;
6997 delete_macro (save_defined); /* clean up special symbol */
6999 temp_obuf.buf[temp_obuf.length] = '\n';
7000 value = parse_c_expression ((char *) temp_obuf.buf,
7001 warn_undef && !instack[indepth].system_header_p);
7003 free (temp_obuf.buf);
7005 return value;
7008 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7009 or don't skip to the #endif/#else/#elif depending on what directive
7010 is actually being processed. */
7012 static int
7013 do_xifdef (buf, limit, op, keyword)
7014 U_CHAR *buf, *limit;
7015 FILE_BUF *op;
7016 struct directive *keyword;
7018 int skip;
7019 FILE_BUF *ip = &instack[indepth];
7020 U_CHAR *end;
7021 int start_of_file = 0;
7022 U_CHAR *control_macro = 0;
7024 /* Detect a #ifndef at start of file (not counting comments). */
7025 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7026 U_CHAR *p = ip->buf;
7027 while (p != directive_start) {
7028 U_CHAR c = *p++;
7029 if (is_space[c])
7031 /* Make no special provision for backslash-newline here; this is
7032 slower if backslash-newlines are present, but it's correct,
7033 and it's not worth it to tune for the rare backslash-newline. */
7034 else if (c == '/'
7035 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7036 /* Skip this comment. */
7037 int junk = 0;
7038 U_CHAR *save_bufp = ip->bufp;
7039 ip->bufp = p + 1;
7040 p = skip_to_end_of_comment (ip, &junk, 1);
7041 ip->bufp = save_bufp;
7042 } else {
7043 goto fail;
7046 /* If we get here, this conditional is the beginning of the file. */
7047 start_of_file = 1;
7048 fail: ;
7051 /* Discard leading and trailing whitespace. */
7052 SKIP_WHITE_SPACE (buf);
7053 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7055 /* Find the end of the identifier at the beginning. */
7056 for (end = buf; is_idchar[*end]; end++);
7058 if (end == buf) {
7059 skip = (keyword->type == T_IFDEF);
7060 if (! traditional)
7061 pedwarn (end == limit ? "`#%s' with no argument"
7062 : "`#%s' argument starts with punctuation",
7063 keyword->name);
7064 } else {
7065 HASHNODE *hp;
7067 if (! traditional) {
7068 if (isdigit (buf[0]))
7069 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7070 else if (end != limit)
7071 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7074 hp = lookup (buf, end-buf, -1);
7076 if (pcp_outfile) {
7077 /* Output a precondition for this macro. */
7078 if (hp
7079 && (hp->type == T_CONST
7080 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7081 fprintf (pcp_outfile, "#define %s\n", hp->name);
7082 else {
7083 U_CHAR *cp = buf;
7084 fprintf (pcp_outfile, "#undef ");
7085 while (is_idchar[*cp]) /* Ick! */
7086 fputc (*cp++, pcp_outfile);
7087 putc ('\n', pcp_outfile);
7091 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7092 if (start_of_file && !skip) {
7093 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7094 bcopy ((char *) buf, (char *) control_macro, end - buf);
7095 control_macro[end - buf] = 0;
7099 conditional_skip (ip, skip, T_IF, control_macro, op);
7100 return 0;
7103 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7104 If this is a #ifndef starting at the beginning of a file,
7105 CONTROL_MACRO is the macro name tested by the #ifndef.
7106 Otherwise, CONTROL_MACRO is 0. */
7108 static void
7109 conditional_skip (ip, skip, type, control_macro, op)
7110 FILE_BUF *ip;
7111 int skip;
7112 enum node_type type;
7113 U_CHAR *control_macro;
7114 FILE_BUF *op;
7116 IF_STACK_FRAME *temp;
7118 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7119 temp->fname = ip->nominal_fname;
7120 temp->lineno = ip->lineno;
7121 temp->next = if_stack;
7122 temp->control_macro = control_macro;
7123 if_stack = temp;
7125 if_stack->type = type;
7127 if (skip != 0) {
7128 skip_if_group (ip, 0, op);
7129 return;
7130 } else {
7131 ++if_stack->if_succeeded;
7132 output_line_directive (ip, &outbuf, 1, same_file);
7136 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7137 Leaves input ptr at the sharp sign found.
7138 If ANY is nonzero, return at next directive of any sort. */
7140 static void
7141 skip_if_group (ip, any, op)
7142 FILE_BUF *ip;
7143 int any;
7144 FILE_BUF *op;
7146 register U_CHAR *bp = ip->bufp, *cp;
7147 register U_CHAR *endb = ip->buf + ip->length;
7148 struct directive *kt;
7149 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7150 U_CHAR *beg_of_line = bp;
7151 register int ident_length;
7152 U_CHAR *ident, *after_ident;
7153 /* Save info about where the group starts. */
7154 U_CHAR *beg_of_group = bp;
7155 int beg_lineno = ip->lineno;
7157 if (output_conditionals && op != 0) {
7158 char *ptr = "#failed\n";
7159 int len = strlen (ptr);
7161 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7163 *op->bufp++ = '\n';
7164 op->lineno++;
7166 check_expand (op, len);
7167 bcopy (ptr, (char *) op->bufp, len);
7168 op->bufp += len;
7169 op->lineno++;
7170 output_line_directive (ip, op, 1, 0);
7173 while (bp < endb) {
7174 switch (*bp++) {
7175 case '/': /* possible comment */
7176 if (*bp == '\\' && bp[1] == '\n')
7177 newline_fix (bp);
7178 if (*bp == '*'
7179 || (cplusplus_comments && *bp == '/')) {
7180 ip->bufp = ++bp;
7181 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7183 break;
7184 case '\"':
7185 case '\'':
7186 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7187 NULL_PTR, NULL_PTR);
7188 break;
7189 case '\\':
7190 /* Char after backslash loses its special meaning. */
7191 if (bp < endb) {
7192 if (*bp == '\n')
7193 ++ip->lineno; /* But do update the line-count. */
7194 bp++;
7196 break;
7197 case '\n':
7198 ++ip->lineno;
7199 beg_of_line = bp;
7200 break;
7201 case '%':
7202 if (beg_of_line == 0 || traditional)
7203 break;
7204 ip->bufp = bp - 1;
7205 while (bp[0] == '\\' && bp[1] == '\n')
7206 bp += 2;
7207 if (*bp == ':')
7208 goto sharp_token;
7209 break;
7210 case '#':
7211 /* # keyword: a # must be first nonblank char on the line */
7212 if (beg_of_line == 0)
7213 break;
7214 ip->bufp = bp - 1;
7215 sharp_token:
7216 /* Scan from start of line, skipping whitespace, comments
7217 and backslash-newlines, and see if we reach this #.
7218 If not, this # is not special. */
7219 bp = beg_of_line;
7220 /* If -traditional, require # to be at beginning of line. */
7221 if (!traditional) {
7222 while (1) {
7223 if (is_hor_space[*bp])
7224 bp++;
7225 else if (*bp == '\\' && bp[1] == '\n')
7226 bp += 2;
7227 else if (*bp == '/' && bp[1] == '*') {
7228 bp += 2;
7229 while (!(*bp == '*' && bp[1] == '/'))
7230 bp++;
7231 bp += 2;
7233 /* There is no point in trying to deal with C++ // comments here,
7234 because if there is one, then this # must be part of the
7235 comment and we would never reach here. */
7236 else break;
7239 if (bp != ip->bufp) {
7240 bp = ip->bufp + 1; /* Reset bp to after the #. */
7241 break;
7244 bp = ip->bufp + 1; /* Point after the '#' */
7245 if (ip->bufp[0] == '%') {
7246 /* Skip past the ':' again. */
7247 while (*bp == '\\') {
7248 ip->lineno++;
7249 bp += 2;
7251 bp++;
7254 /* Skip whitespace and \-newline. */
7255 while (1) {
7256 if (is_hor_space[*bp])
7257 bp++;
7258 else if (*bp == '\\' && bp[1] == '\n')
7259 bp += 2;
7260 else if (*bp == '/') {
7261 if (bp[1] == '*') {
7262 for (bp += 2; ; bp++) {
7263 if (*bp == '\n')
7264 ip->lineno++;
7265 else if (*bp == '*') {
7266 if (bp[-1] == '/' && warn_comments)
7267 warning ("`/*' within comment");
7268 if (bp[1] == '/')
7269 break;
7272 bp += 2;
7273 } else if (bp[1] == '/' && cplusplus_comments) {
7274 for (bp += 2; ; bp++) {
7275 if (*bp == '\n') {
7276 if (bp[-1] != '\\')
7277 break;
7278 if (warn_comments)
7279 warning ("multiline `//' comment");
7280 ip->lineno++;
7283 } else
7284 break;
7285 } else
7286 break;
7289 cp = bp;
7291 /* Now find end of directive name.
7292 If we encounter a backslash-newline, exchange it with any following
7293 symbol-constituents so that we end up with a contiguous name. */
7295 while (1) {
7296 if (is_idchar[*bp])
7297 bp++;
7298 else {
7299 if (*bp == '\\' && bp[1] == '\n')
7300 name_newline_fix (bp);
7301 if (is_idchar[*bp])
7302 bp++;
7303 else break;
7306 ident_length = bp - cp;
7307 ident = cp;
7308 after_ident = bp;
7310 /* A line of just `#' becomes blank. */
7312 if (ident_length == 0 && *after_ident == '\n') {
7313 continue;
7316 if (ident_length == 0 || !is_idstart[*ident]) {
7317 U_CHAR *p = ident;
7318 while (is_idchar[*p]) {
7319 if (*p < '0' || *p > '9')
7320 break;
7321 p++;
7323 /* Handle # followed by a line number. */
7324 if (p != ident && !is_idchar[*p]) {
7325 if (pedantic)
7326 pedwarn ("`#' followed by integer");
7327 continue;
7330 /* Avoid error for `###' and similar cases unless -pedantic. */
7331 if (p == ident) {
7332 while (*p == '#' || is_hor_space[*p]) p++;
7333 if (*p == '\n') {
7334 if (pedantic && !lang_asm)
7335 pedwarn ("invalid preprocessing directive");
7336 continue;
7340 if (!lang_asm && pedantic)
7341 pedwarn ("invalid preprocessing directive name");
7342 continue;
7345 for (kt = directive_table; kt->length >= 0; kt++) {
7346 IF_STACK_FRAME *temp;
7347 if (ident_length == kt->length
7348 && bcmp (cp, kt->name, kt->length) == 0) {
7349 /* If we are asked to return on next directive, do so now. */
7350 if (any)
7351 goto done;
7353 switch (kt->type) {
7354 case T_IF:
7355 case T_IFDEF:
7356 case T_IFNDEF:
7357 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7358 temp->next = if_stack;
7359 if_stack = temp;
7360 temp->lineno = ip->lineno;
7361 temp->fname = ip->nominal_fname;
7362 temp->type = kt->type;
7363 break;
7364 case T_ELSE:
7365 case T_ENDIF:
7366 if (pedantic && if_stack != save_if_stack)
7367 validate_else (bp, endb);
7368 case T_ELIF:
7369 if (if_stack == instack[indepth].if_stack) {
7370 error ("`#%s' not within a conditional", kt->name);
7371 break;
7373 else if (if_stack == save_if_stack)
7374 goto done; /* found what we came for */
7376 if (kt->type != T_ENDIF) {
7377 if (if_stack->type == T_ELSE)
7378 error ("`#else' or `#elif' after `#else'");
7379 if_stack->type = kt->type;
7380 break;
7383 temp = if_stack;
7384 if_stack = if_stack->next;
7385 free (temp);
7386 break;
7388 default:
7389 break;
7391 break;
7394 /* Don't let erroneous code go by. */
7395 if (kt->length < 0 && !lang_asm && pedantic)
7396 pedwarn ("invalid preprocessing directive name");
7400 ip->bufp = bp;
7401 /* after this returns, rescan will exit because ip->bufp
7402 now points to the end of the buffer.
7403 rescan is responsible for the error message also. */
7405 done:
7406 if (output_conditionals && op != 0) {
7407 char *ptr = "#endfailed\n";
7408 int len = strlen (ptr);
7410 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7412 *op->bufp++ = '\n';
7413 op->lineno++;
7415 check_expand (op, beg_of_line - beg_of_group);
7416 bcopy ((char *) beg_of_group, (char *) op->bufp,
7417 beg_of_line - beg_of_group);
7418 op->bufp += beg_of_line - beg_of_group;
7419 op->lineno += ip->lineno - beg_lineno;
7420 check_expand (op, len);
7421 bcopy (ptr, (char *) op->bufp, len);
7422 op->bufp += len;
7423 op->lineno++;
7427 /* Handle a #else directive. Do this by just continuing processing
7428 without changing if_stack ; this is so that the error message
7429 for missing #endif's etc. will point to the original #if. It
7430 is possible that something different would be better. */
7432 static int
7433 do_else (buf, limit, op, keyword)
7434 U_CHAR *buf, *limit;
7435 FILE_BUF *op;
7436 struct directive *keyword;
7438 FILE_BUF *ip = &instack[indepth];
7440 if (pedantic) {
7441 SKIP_WHITE_SPACE (buf);
7442 if (buf != limit)
7443 pedwarn ("text following `#else' violates ANSI standard");
7446 if (if_stack == instack[indepth].if_stack) {
7447 error ("`#else' not within a conditional");
7448 return 0;
7449 } else {
7450 /* #ifndef can't have its special treatment for containing the whole file
7451 if it has a #else clause. */
7452 if_stack->control_macro = 0;
7454 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7455 error ("`#else' after `#else'");
7456 fprintf (stderr, " (matches line %d", if_stack->lineno);
7457 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7458 fprintf (stderr, ", file %s", if_stack->fname);
7459 fprintf (stderr, ")\n");
7461 if_stack->type = T_ELSE;
7464 if (if_stack->if_succeeded)
7465 skip_if_group (ip, 0, op);
7466 else {
7467 ++if_stack->if_succeeded; /* continue processing input */
7468 output_line_directive (ip, op, 1, same_file);
7470 return 0;
7473 /* Unstack after #endif directive. */
7475 static int
7476 do_endif (buf, limit, op, keyword)
7477 U_CHAR *buf, *limit;
7478 FILE_BUF *op;
7479 struct directive *keyword;
7481 if (pedantic) {
7482 SKIP_WHITE_SPACE (buf);
7483 if (buf != limit)
7484 pedwarn ("text following `#endif' violates ANSI standard");
7487 if (if_stack == instack[indepth].if_stack)
7488 error ("unbalanced `#endif'");
7489 else {
7490 IF_STACK_FRAME *temp = if_stack;
7491 if_stack = if_stack->next;
7492 if (temp->control_macro != 0) {
7493 /* This #endif matched a #ifndef at the start of the file.
7494 See if it is at the end of the file. */
7495 FILE_BUF *ip = &instack[indepth];
7496 U_CHAR *p = ip->bufp;
7497 U_CHAR *ep = ip->buf + ip->length;
7499 while (p != ep) {
7500 U_CHAR c = *p++;
7501 if (!is_space[c]) {
7502 if (c == '/'
7503 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7504 /* Skip this comment. */
7505 int junk = 0;
7506 U_CHAR *save_bufp = ip->bufp;
7507 ip->bufp = p + 1;
7508 p = skip_to_end_of_comment (ip, &junk, 1);
7509 ip->bufp = save_bufp;
7510 } else
7511 goto fail;
7514 /* If we get here, this #endif ends a #ifndef
7515 that contains all of the file (aside from whitespace).
7516 Arrange not to include the file again
7517 if the macro that was tested is defined.
7519 Do not do this for the top-level file in a -include or any
7520 file in a -imacros. */
7521 if (indepth != 0
7522 && ! (indepth == 1 && no_record_file)
7523 && ! (no_record_file && no_output))
7524 record_control_macro (ip->inc, temp->control_macro);
7525 fail: ;
7527 free (temp);
7528 output_line_directive (&instack[indepth], op, 1, same_file);
7530 return 0;
7533 /* When an #else or #endif is found while skipping failed conditional,
7534 if -pedantic was specified, this is called to warn about text after
7535 the directive name. P points to the first char after the directive
7536 name. */
7538 static void
7539 validate_else (p, limit)
7540 register U_CHAR *p;
7541 register U_CHAR *limit;
7543 /* Advance P over whitespace and comments. */
7544 while (1) {
7545 while (*p == '\\' && p[1] == '\n')
7546 p += 2;
7547 if (is_hor_space[*p])
7548 p++;
7549 else if (*p == '/') {
7550 while (p[1] == '\\' && p[2] == '\n')
7551 p += 2;
7552 if (p[1] == '*') {
7553 /* Don't bother warning about unterminated comments
7554 since that will happen later. Just be sure to exit. */
7555 for (p += 2; ; p++) {
7556 if (p == limit)
7557 return;
7558 if (*p == '*') {
7559 while (p[1] == '\\' && p[2] == '\n')
7560 p += 2;
7561 if (p[1] == '/') {
7562 p += 2;
7563 break;
7568 else if (cplusplus_comments && p[1] == '/')
7569 return;
7570 else break;
7571 } else break;
7573 if (*p != '\n')
7574 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7577 /* Skip a comment, assuming the input ptr immediately follows the
7578 initial slash-star. Bump *LINE_COUNTER for each newline.
7579 (The canonical line counter is &ip->lineno.)
7580 Don't use this routine (or the next one) if bumping the line
7581 counter is not sufficient to deal with newlines in the string.
7583 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7584 This feature is useful when processing a comment that is going to
7585 be processed or was processed at another point in the preprocessor,
7586 to avoid a duplicate warning. Likewise for unterminated comment
7587 errors. */
7589 static U_CHAR *
7590 skip_to_end_of_comment (ip, line_counter, nowarn)
7591 register FILE_BUF *ip;
7592 int *line_counter; /* place to remember newlines, or NULL */
7593 int nowarn;
7595 register U_CHAR *limit = ip->buf + ip->length;
7596 register U_CHAR *bp = ip->bufp;
7597 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7598 int start_line = line_counter ? *line_counter : 0;
7600 /* JF this line_counter stuff is a crock to make sure the
7601 comment is only put out once, no matter how many times
7602 the comment is skipped. It almost works */
7603 if (op) {
7604 *op->bufp++ = '/';
7605 *op->bufp++ = bp[-1];
7607 if (cplusplus_comments && bp[-1] == '/') {
7608 for (; bp < limit; bp++) {
7609 if (*bp == '\n') {
7610 if (bp[-1] != '\\')
7611 break;
7612 if (!nowarn && warn_comments)
7613 warning ("multiline `//' comment");
7614 if (line_counter)
7615 ++*line_counter;
7616 if (op)
7617 ++op->lineno;
7619 if (op)
7620 *op->bufp++ = *bp;
7622 ip->bufp = bp;
7623 return bp;
7625 while (bp < limit) {
7626 if (op)
7627 *op->bufp++ = *bp;
7628 switch (*bp++) {
7629 case '\n':
7630 /* If this is the end of the file, we have an unterminated comment.
7631 Don't swallow the newline. We are guaranteed that there will be a
7632 trailing newline and various pieces assume it's there. */
7633 if (bp == limit)
7635 --bp;
7636 --limit;
7637 break;
7639 if (line_counter != NULL)
7640 ++*line_counter;
7641 if (op)
7642 ++op->lineno;
7643 break;
7644 case '*':
7645 if (bp[-2] == '/' && !nowarn && warn_comments)
7646 warning ("`/*' within comment");
7647 if (*bp == '\\' && bp[1] == '\n')
7648 newline_fix (bp);
7649 if (*bp == '/') {
7650 if (op)
7651 *op->bufp++ = '/';
7652 ip->bufp = ++bp;
7653 return bp;
7655 break;
7659 if (!nowarn)
7660 error_with_line (line_for_error (start_line), "unterminated comment");
7661 ip->bufp = bp;
7662 return bp;
7665 /* Skip over a quoted string. BP points to the opening quote.
7666 Returns a pointer after the closing quote. Don't go past LIMIT.
7667 START_LINE is the line number of the starting point (but it need
7668 not be valid if the starting point is inside a macro expansion).
7670 The input stack state is not changed.
7672 If COUNT_NEWLINES is nonzero, it points to an int to increment
7673 for each newline passed.
7675 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7676 if we pass a backslash-newline.
7678 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
7680 static U_CHAR *
7681 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7682 register U_CHAR *bp;
7683 register U_CHAR *limit;
7684 int start_line;
7685 int *count_newlines;
7686 int *backslash_newlines_p;
7687 int *eofp;
7689 register U_CHAR c, match;
7691 match = *bp++;
7692 while (1) {
7693 if (bp >= limit) {
7694 error_with_line (line_for_error (start_line),
7695 "unterminated string or character constant");
7696 error_with_line (multiline_string_line,
7697 "possible real start of unterminated constant");
7698 multiline_string_line = 0;
7699 if (eofp)
7700 *eofp = 1;
7701 break;
7703 c = *bp++;
7704 if (c == '\\') {
7705 while (*bp == '\\' && bp[1] == '\n') {
7706 if (backslash_newlines_p)
7707 *backslash_newlines_p = 1;
7708 if (count_newlines)
7709 ++*count_newlines;
7710 bp += 2;
7712 if (*bp == '\n' && count_newlines) {
7713 if (backslash_newlines_p)
7714 *backslash_newlines_p = 1;
7715 ++*count_newlines;
7717 bp++;
7718 } else if (c == '\n') {
7719 if (traditional) {
7720 /* Unterminated strings and character constants are 'valid'. */
7721 bp--; /* Don't consume the newline. */
7722 if (eofp)
7723 *eofp = 1;
7724 break;
7726 if (match == '\'') {
7727 error_with_line (line_for_error (start_line),
7728 "unterminated string or character constant");
7729 bp--;
7730 if (eofp)
7731 *eofp = 1;
7732 break;
7734 /* If not traditional, then allow newlines inside strings. */
7735 if (count_newlines)
7736 ++*count_newlines;
7737 if (multiline_string_line == 0) {
7738 if (pedantic)
7739 pedwarn_with_line (line_for_error (start_line),
7740 "string constant runs past end of line");
7741 multiline_string_line = start_line;
7743 } else if (c == match)
7744 break;
7746 return bp;
7749 /* Place into DST a quoted string representing the string SRC.
7750 Return the address of DST's terminating null. */
7752 static char *
7753 quote_string (dst, src)
7754 char *dst, *src;
7756 U_CHAR c;
7758 *dst++ = '\"';
7759 for (;;)
7760 switch ((c = *src++))
7762 default:
7763 if (isprint (c))
7764 *dst++ = c;
7765 else
7767 sprintf (dst, "\\%03o", c);
7768 dst += 4;
7770 break;
7772 case '\"':
7773 case '\\':
7774 *dst++ = '\\';
7775 *dst++ = c;
7776 break;
7778 case '\0':
7779 *dst++ = '\"';
7780 *dst = '\0';
7781 return dst;
7785 /* Skip across a group of balanced parens, starting from IP->bufp.
7786 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7788 This does not handle newlines, because it's used for the arg of #if,
7789 where there aren't any newlines. Also, backslash-newline can't appear. */
7791 static U_CHAR *
7792 skip_paren_group (ip)
7793 register FILE_BUF *ip;
7795 U_CHAR *limit = ip->buf + ip->length;
7796 U_CHAR *p = ip->bufp;
7797 int depth = 0;
7798 int lines_dummy = 0;
7800 while (p != limit) {
7801 int c = *p++;
7802 switch (c) {
7803 case '(':
7804 depth++;
7805 break;
7807 case ')':
7808 depth--;
7809 if (depth == 0)
7810 return ip->bufp = p;
7811 break;
7813 case '/':
7814 if (*p == '*') {
7815 ip->bufp = p;
7816 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7817 p = ip->bufp;
7820 case '"':
7821 case '\'':
7823 int eofp = 0;
7824 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7825 if (eofp)
7826 return ip->bufp = p;
7828 break;
7832 ip->bufp = p;
7833 return p;
7836 /* Write out a #line directive, for instance, after an #include file.
7837 If CONDITIONAL is nonzero, we can omit the #line if it would
7838 appear to be a no-op, and we can output a few newlines instead
7839 if we want to increase the line number by a small amount.
7840 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
7842 static void
7843 output_line_directive (ip, op, conditional, file_change)
7844 FILE_BUF *ip, *op;
7845 int conditional;
7846 enum file_change_code file_change;
7848 int len;
7849 char *line_directive_buf, *line_end;
7851 if (no_line_directives
7852 || ip->fname == NULL
7853 || no_output) {
7854 op->lineno = ip->lineno;
7855 return;
7858 if (conditional) {
7859 if (ip->lineno == op->lineno)
7860 return;
7862 /* If the inherited line number is a little too small,
7863 output some newlines instead of a #line directive. */
7864 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7865 check_expand (op, 10);
7866 while (ip->lineno > op->lineno) {
7867 *op->bufp++ = '\n';
7868 op->lineno++;
7870 return;
7874 /* Output a positive line number if possible. */
7875 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
7876 && *ip->bufp == '\n') {
7877 ip->lineno++;
7878 ip->bufp++;
7881 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7882 sprintf (line_directive_buf, "# %d ", ip->lineno);
7883 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7884 ip->nominal_fname);
7885 if (file_change != same_file) {
7886 *line_end++ = ' ';
7887 *line_end++ = file_change == enter_file ? '1' : '2';
7889 /* Tell cc1 if following text comes from a system header file. */
7890 if (ip->system_header_p) {
7891 *line_end++ = ' ';
7892 *line_end++ = '3';
7894 #ifndef NO_IMPLICIT_EXTERN_C
7895 /* Tell cc1plus if following text should be treated as C. */
7896 if (ip->system_header_p == 2 && cplusplus) {
7897 *line_end++ = ' ';
7898 *line_end++ = '4';
7900 #endif
7901 *line_end++ = '\n';
7902 len = line_end - line_directive_buf;
7903 check_expand (op, len + 1);
7904 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7905 *op->bufp++ = '\n';
7906 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7907 op->bufp += len;
7908 op->lineno = ip->lineno;
7911 /* This structure represents one parsed argument in a macro call.
7912 `raw' points to the argument text as written (`raw_length' is its length).
7913 `expanded' points to the argument's macro-expansion
7914 (its length is `expand_length').
7915 `stringified_length' is the length the argument would have
7916 if stringified.
7917 `use_count' is the number of times this macro arg is substituted
7918 into the macro. If the actual use count exceeds 10,
7919 the value stored is 10.
7920 `free1' and `free2', if nonzero, point to blocks to be freed
7921 when the macro argument data is no longer needed. */
7923 struct argdata {
7924 U_CHAR *raw, *expanded;
7925 int raw_length, expand_length;
7926 int stringified_length;
7927 U_CHAR *free1, *free2;
7928 char newlines;
7929 char use_count;
7932 /* Expand a macro call.
7933 HP points to the symbol that is the macro being called.
7934 Put the result of expansion onto the input stack
7935 so that subsequent input by our caller will use it.
7937 If macro wants arguments, caller has already verified that
7938 an argument list follows; arguments come from the input stack. */
7940 static void
7941 macroexpand (hp, op)
7942 HASHNODE *hp;
7943 FILE_BUF *op;
7945 int nargs;
7946 DEFINITION *defn = hp->value.defn;
7947 register U_CHAR *xbuf;
7948 int xbuf_len;
7949 int start_line = instack[indepth].lineno;
7950 int rest_args, rest_zero;
7952 CHECK_DEPTH (return;);
7954 /* it might not actually be a macro. */
7955 if (hp->type != T_MACRO) {
7956 special_symbol (hp, op);
7957 return;
7960 /* This macro is being used inside a #if, which means it must be */
7961 /* recorded as a precondition. */
7962 if (pcp_inside_if && pcp_outfile && defn->predefined)
7963 dump_single_macro (hp, pcp_outfile);
7965 nargs = defn->nargs;
7967 if (nargs >= 0) {
7968 register int i;
7969 struct argdata *args;
7970 char *parse_error = 0;
7972 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7974 for (i = 0; i < nargs; i++) {
7975 args[i].raw = (U_CHAR *) "";
7976 args[i].expanded = 0;
7977 args[i].raw_length = args[i].expand_length
7978 = args[i].stringified_length = 0;
7979 args[i].free1 = args[i].free2 = 0;
7980 args[i].use_count = 0;
7983 /* Parse all the macro args that are supplied. I counts them.
7984 The first NARGS args are stored in ARGS.
7985 The rest are discarded.
7986 If rest_args is set then we assume macarg absorbed the rest of the args.
7988 i = 0;
7989 rest_args = 0;
7990 do {
7991 /* Discard the open-parenthesis or comma before the next arg. */
7992 ++instack[indepth].bufp;
7993 if (rest_args)
7994 continue;
7995 if (i < nargs || (nargs == 0 && i == 0)) {
7996 /* If we are working on last arg which absorbs rest of args... */
7997 if (i == nargs - 1 && defn->rest_args)
7998 rest_args = 1;
7999 parse_error = macarg (&args[i], rest_args);
8001 else
8002 parse_error = macarg (NULL_PTR, 0);
8003 if (parse_error) {
8004 error_with_line (line_for_error (start_line), parse_error);
8005 break;
8007 i++;
8008 } while (*instack[indepth].bufp != ')');
8010 /* If we got one arg but it was just whitespace, call that 0 args. */
8011 if (i == 1) {
8012 register U_CHAR *bp = args[0].raw;
8013 register U_CHAR *lim = bp + args[0].raw_length;
8014 /* cpp.texi says for foo ( ) we provide one argument.
8015 However, if foo wants just 0 arguments, treat this as 0. */
8016 if (nargs == 0)
8017 while (bp != lim && is_space[*bp]) bp++;
8018 if (bp == lim)
8019 i = 0;
8022 /* Don't output an error message if we have already output one for
8023 a parse error above. */
8024 rest_zero = 0;
8025 if (nargs == 0 && i > 0) {
8026 if (! parse_error)
8027 error ("arguments given to macro `%s'", hp->name);
8028 } else if (i < nargs) {
8029 /* traditional C allows foo() if foo wants one argument. */
8030 if (nargs == 1 && i == 0 && traditional)
8032 /* the rest args token is allowed to absorb 0 tokens */
8033 else if (i == nargs - 1 && defn->rest_args)
8034 rest_zero = 1;
8035 else if (parse_error)
8037 else if (i == 0)
8038 error ("macro `%s' used without args", hp->name);
8039 else if (i == 1)
8040 error ("macro `%s' used with just one arg", hp->name);
8041 else
8042 error ("macro `%s' used with only %d args", hp->name, i);
8043 } else if (i > nargs) {
8044 if (! parse_error)
8045 error ("macro `%s' used with too many (%d) args", hp->name, i);
8048 /* Swallow the closeparen. */
8049 ++instack[indepth].bufp;
8051 /* If macro wants zero args, we parsed the arglist for checking only.
8052 Read directly from the macro definition. */
8053 if (nargs == 0) {
8054 xbuf = defn->expansion;
8055 xbuf_len = defn->length;
8056 } else {
8057 register U_CHAR *exp = defn->expansion;
8058 register int offset; /* offset in expansion,
8059 copied a piece at a time */
8060 register int totlen; /* total amount of exp buffer filled so far */
8062 register struct reflist *ap, *last_ap;
8064 /* Macro really takes args. Compute the expansion of this call. */
8066 /* Compute length in characters of the macro's expansion.
8067 Also count number of times each arg is used. */
8068 xbuf_len = defn->length;
8069 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8070 if (ap->stringify)
8071 xbuf_len += args[ap->argno].stringified_length;
8072 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8073 /* Add 4 for two newline-space markers to prevent
8074 token concatenation. */
8075 xbuf_len += args[ap->argno].raw_length + 4;
8076 else {
8077 /* We have an ordinary (expanded) occurrence of the arg.
8078 So compute its expansion, if we have not already. */
8079 if (args[ap->argno].expanded == 0) {
8080 FILE_BUF obuf;
8081 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8082 args[ap->argno].raw + args[ap->argno].raw_length,
8083 1, 0);
8085 args[ap->argno].expanded = obuf.buf;
8086 args[ap->argno].expand_length = obuf.length;
8087 args[ap->argno].free2 = obuf.buf;
8090 /* Add 4 for two newline-space markers to prevent
8091 token concatenation. */
8092 xbuf_len += args[ap->argno].expand_length + 4;
8094 if (args[ap->argno].use_count < 10)
8095 args[ap->argno].use_count++;
8098 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8100 /* Generate in XBUF the complete expansion
8101 with arguments substituted in.
8102 TOTLEN is the total size generated so far.
8103 OFFSET is the index in the definition
8104 of where we are copying from. */
8105 offset = totlen = 0;
8106 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8107 last_ap = ap, ap = ap->next) {
8108 register struct argdata *arg = &args[ap->argno];
8109 int count_before = totlen;
8111 /* Add chars to XBUF. */
8112 for (i = 0; i < ap->nchars; i++, offset++)
8113 xbuf[totlen++] = exp[offset];
8115 /* If followed by an empty rest arg with concatenation,
8116 delete the last run of nonwhite chars. */
8117 if (rest_zero && totlen > count_before
8118 && ((ap->rest_args && ap->raw_before != 0)
8119 || (last_ap != NULL && last_ap->rest_args
8120 && last_ap->raw_after != 0))) {
8121 /* Delete final whitespace. */
8122 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8123 totlen--;
8126 /* Delete the nonwhites before them. */
8127 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8128 totlen--;
8132 if (ap->stringify != 0) {
8133 int arglen = arg->raw_length;
8134 int escaped = 0;
8135 int in_string = 0;
8136 int c;
8137 i = 0;
8138 while (i < arglen
8139 && (c = arg->raw[i], is_space[c]))
8140 i++;
8141 while (i < arglen
8142 && (c = arg->raw[arglen - 1], is_space[c]))
8143 arglen--;
8144 if (!traditional)
8145 xbuf[totlen++] = '\"'; /* insert beginning quote */
8146 for (; i < arglen; i++) {
8147 c = arg->raw[i];
8149 /* Special markers Newline Space
8150 generate nothing for a stringified argument. */
8151 if (c == '\n' && arg->raw[i+1] != '\n') {
8152 i++;
8153 continue;
8156 /* Internal sequences of whitespace are replaced by one space
8157 except within an string or char token. */
8158 if (! in_string
8159 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8160 while (1) {
8161 /* Note that Newline Space does occur within whitespace
8162 sequences; consider it part of the sequence. */
8163 if (c == '\n' && is_space[arg->raw[i+1]])
8164 i += 2;
8165 else if (c != '\n' && is_space[c])
8166 i++;
8167 else break;
8168 c = arg->raw[i];
8170 i--;
8171 c = ' ';
8174 if (escaped)
8175 escaped = 0;
8176 else {
8177 if (c == '\\')
8178 escaped = 1;
8179 if (in_string) {
8180 if (c == in_string)
8181 in_string = 0;
8182 } else if (c == '\"' || c == '\'')
8183 in_string = c;
8186 /* Escape these chars */
8187 if (c == '\"' || (in_string && c == '\\'))
8188 xbuf[totlen++] = '\\';
8189 if (isprint (c))
8190 xbuf[totlen++] = c;
8191 else {
8192 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8193 totlen += 4;
8196 if (!traditional)
8197 xbuf[totlen++] = '\"'; /* insert ending quote */
8198 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8199 U_CHAR *p1 = arg->raw;
8200 U_CHAR *l1 = p1 + arg->raw_length;
8201 if (ap->raw_before != 0) {
8202 while (p1 != l1 && is_space[*p1]) p1++;
8203 while (p1 != l1 && is_idchar[*p1])
8204 xbuf[totlen++] = *p1++;
8205 /* Delete any no-reexpansion marker that follows
8206 an identifier at the beginning of the argument
8207 if the argument is concatenated with what precedes it. */
8208 if (p1[0] == '\n' && p1[1] == '-')
8209 p1 += 2;
8210 } else if (!traditional) {
8211 /* Ordinary expanded use of the argument.
8212 Put in newline-space markers to prevent token pasting. */
8213 xbuf[totlen++] = '\n';
8214 xbuf[totlen++] = ' ';
8216 if (ap->raw_after != 0) {
8217 /* Arg is concatenated after: delete trailing whitespace,
8218 whitespace markers, and no-reexpansion markers. */
8219 while (p1 != l1) {
8220 if (is_space[l1[-1]]) l1--;
8221 else if (l1[-1] == '-') {
8222 U_CHAR *p2 = l1 - 1;
8223 /* If a `-' is preceded by an odd number of newlines then it
8224 and the last newline are a no-reexpansion marker. */
8225 while (p2 != p1 && p2[-1] == '\n') p2--;
8226 if ((l1 - 1 - p2) & 1) {
8227 l1 -= 2;
8229 else break;
8231 else break;
8235 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8236 totlen += l1 - p1;
8237 if (!traditional && ap->raw_after == 0) {
8238 /* Ordinary expanded use of the argument.
8239 Put in newline-space markers to prevent token pasting. */
8240 xbuf[totlen++] = '\n';
8241 xbuf[totlen++] = ' ';
8243 } else {
8244 /* Ordinary expanded use of the argument.
8245 Put in newline-space markers to prevent token pasting. */
8246 if (!traditional) {
8247 xbuf[totlen++] = '\n';
8248 xbuf[totlen++] = ' ';
8250 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8251 arg->expand_length);
8252 totlen += arg->expand_length;
8253 if (!traditional) {
8254 xbuf[totlen++] = '\n';
8255 xbuf[totlen++] = ' ';
8257 /* If a macro argument with newlines is used multiple times,
8258 then only expand the newlines once. This avoids creating output
8259 lines which don't correspond to any input line, which confuses
8260 gdb and gcov. */
8261 if (arg->use_count > 1 && arg->newlines > 0) {
8262 /* Don't bother doing change_newlines for subsequent
8263 uses of arg. */
8264 arg->use_count = 1;
8265 arg->expand_length
8266 = change_newlines (arg->expanded, arg->expand_length);
8270 if (totlen > xbuf_len)
8271 abort ();
8274 /* If there is anything left of the definition after handling
8275 the arg list, copy that in too. */
8277 for (i = offset; i < defn->length; i++) {
8278 /* if we've reached the end of the macro */
8279 if (exp[i] == ')')
8280 rest_zero = 0;
8281 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8282 && last_ap->raw_after != 0))
8283 xbuf[totlen++] = exp[i];
8286 xbuf[totlen] = 0;
8287 xbuf_len = totlen;
8289 for (i = 0; i < nargs; i++) {
8290 if (args[i].free1 != 0)
8291 free (args[i].free1);
8292 if (args[i].free2 != 0)
8293 free (args[i].free2);
8296 } else {
8297 xbuf = defn->expansion;
8298 xbuf_len = defn->length;
8301 /* Now put the expansion on the input stack
8302 so our caller will commence reading from it. */
8304 register FILE_BUF *ip2;
8306 ip2 = &instack[++indepth];
8308 ip2->fname = 0;
8309 ip2->nominal_fname = 0;
8310 ip2->inc = 0;
8311 /* This may not be exactly correct, but will give much better error
8312 messages for nested macro calls than using a line number of zero. */
8313 ip2->lineno = start_line;
8314 ip2->buf = xbuf;
8315 ip2->length = xbuf_len;
8316 ip2->bufp = xbuf;
8317 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8318 ip2->macro = hp;
8319 ip2->if_stack = if_stack;
8320 ip2->system_header_p = 0;
8322 /* Recursive macro use sometimes works traditionally.
8323 #define foo(x,y) bar (x (y,0), y)
8324 foo (foo, baz) */
8326 if (!traditional)
8327 hp->type = T_DISABLED;
8331 /* Parse a macro argument and store the info on it into *ARGPTR.
8332 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8333 Return nonzero to indicate a syntax error. */
8335 static char *
8336 macarg (argptr, rest_args)
8337 register struct argdata *argptr;
8338 int rest_args;
8340 FILE_BUF *ip = &instack[indepth];
8341 int paren = 0;
8342 int newlines = 0;
8343 int comments = 0;
8344 char *result = 0;
8346 /* Try to parse as much of the argument as exists at this
8347 input stack level. */
8348 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8349 &paren, &newlines, &comments, rest_args);
8351 /* If we find the end of the argument at this level,
8352 set up *ARGPTR to point at it in the input stack. */
8353 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8354 && bp != ip->buf + ip->length) {
8355 if (argptr != 0) {
8356 argptr->raw = ip->bufp;
8357 argptr->raw_length = bp - ip->bufp;
8358 argptr->newlines = newlines;
8360 ip->bufp = bp;
8361 } else {
8362 /* This input stack level ends before the macro argument does.
8363 We must pop levels and keep parsing.
8364 Therefore, we must allocate a temporary buffer and copy
8365 the macro argument into it. */
8366 int bufsize = bp - ip->bufp;
8367 int extra = newlines;
8368 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8369 int final_start = 0;
8371 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8372 ip->bufp = bp;
8373 ip->lineno += newlines;
8375 while (bp == ip->buf + ip->length) {
8376 if (instack[indepth].macro == 0) {
8377 result = "unterminated macro call";
8378 break;
8380 ip->macro->type = T_MACRO;
8381 if (ip->free_ptr)
8382 free (ip->free_ptr);
8383 ip = &instack[--indepth];
8384 newlines = 0;
8385 comments = 0;
8386 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8387 &newlines, &comments, rest_args);
8388 final_start = bufsize;
8389 bufsize += bp - ip->bufp;
8390 extra += newlines;
8391 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8392 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8393 bp - ip->bufp);
8394 ip->bufp = bp;
8395 ip->lineno += newlines;
8398 /* Now, if arg is actually wanted, record its raw form,
8399 discarding comments and duplicating newlines in whatever
8400 part of it did not come from a macro expansion.
8401 EXTRA space has been preallocated for duplicating the newlines.
8402 FINAL_START is the index of the start of that part. */
8403 if (argptr != 0) {
8404 argptr->raw = buffer;
8405 argptr->raw_length = bufsize;
8406 argptr->free1 = buffer;
8407 argptr->newlines = newlines;
8408 if ((newlines || comments) && ip->fname != 0)
8409 argptr->raw_length
8410 = final_start +
8411 discard_comments (argptr->raw + final_start,
8412 argptr->raw_length - final_start,
8413 newlines);
8414 argptr->raw[argptr->raw_length] = 0;
8415 if (argptr->raw_length > bufsize + extra)
8416 abort ();
8420 /* If we are not discarding this argument,
8421 macroexpand it and compute its length as stringified.
8422 All this info goes into *ARGPTR. */
8424 if (argptr != 0) {
8425 register U_CHAR *buf, *lim;
8426 register int totlen;
8428 buf = argptr->raw;
8429 lim = buf + argptr->raw_length;
8431 while (buf != lim && is_space[*buf])
8432 buf++;
8433 while (buf != lim && is_space[lim[-1]])
8434 lim--;
8435 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8436 while (buf != lim) {
8437 register U_CHAR c = *buf++;
8438 totlen++;
8439 /* Internal sequences of whitespace are replaced by one space
8440 in most cases, but not always. So count all the whitespace
8441 in case we need to keep it all. */
8442 #if 0
8443 if (is_space[c])
8444 SKIP_ALL_WHITE_SPACE (buf);
8445 else
8446 #endif
8447 if (c == '\"' || c == '\\') /* escape these chars */
8448 totlen++;
8449 else if (!isprint (c))
8450 totlen += 3;
8452 argptr->stringified_length = totlen;
8454 return result;
8457 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8458 counting parens in *DEPTHPTR,
8459 and return if reach LIMIT
8460 or before a `)' that would make *DEPTHPTR negative
8461 or before a comma when *DEPTHPTR is zero.
8462 Single and double quotes are matched and termination
8463 is inhibited within them. Comments also inhibit it.
8464 Value returned is pointer to stopping place.
8466 Increment *NEWLINES each time a newline is passed.
8467 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8468 Set *COMMENTS to 1 if a comment is seen. */
8470 static U_CHAR *
8471 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8472 U_CHAR *start;
8473 register U_CHAR *limit;
8474 int *depthptr, *newlines, *comments;
8475 int rest_args;
8477 register U_CHAR *bp = start;
8479 while (bp < limit) {
8480 switch (*bp) {
8481 case '(':
8482 (*depthptr)++;
8483 break;
8484 case ')':
8485 if (--(*depthptr) < 0)
8486 return bp;
8487 break;
8488 case '\\':
8489 /* Traditionally, backslash makes following char not special. */
8490 if (bp + 1 < limit && traditional)
8492 bp++;
8493 /* But count source lines anyway. */
8494 if (*bp == '\n')
8495 ++*newlines;
8497 break;
8498 case '\n':
8499 ++*newlines;
8500 break;
8501 case '/':
8502 if (bp[1] == '\\' && bp[2] == '\n')
8503 newline_fix (bp + 1);
8504 if (bp[1] == '*') {
8505 *comments = 1;
8506 for (bp += 2; bp < limit; bp++) {
8507 if (*bp == '\n')
8508 ++*newlines;
8509 else if (*bp == '*') {
8510 if (bp[-1] == '/' && warn_comments)
8511 warning ("`/*' within comment");
8512 if (bp[1] == '\\' && bp[2] == '\n')
8513 newline_fix (bp + 1);
8514 if (bp[1] == '/') {
8515 bp++;
8516 break;
8520 } else if (bp[1] == '/' && cplusplus_comments) {
8521 *comments = 1;
8522 for (bp += 2; bp < limit; bp++) {
8523 if (*bp == '\n') {
8524 ++*newlines;
8525 if (bp[-1] != '\\')
8526 break;
8527 if (warn_comments)
8528 warning ("multiline `//' comment");
8532 break;
8533 case '\'':
8534 case '\"':
8536 int quotec;
8537 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8538 if (*bp == '\\') {
8539 bp++;
8540 if (*bp == '\n')
8541 ++*newlines;
8542 while (*bp == '\\' && bp[1] == '\n') {
8543 bp += 2;
8545 } else if (*bp == '\n') {
8546 ++*newlines;
8547 if (quotec == '\'')
8548 break;
8552 break;
8553 case ',':
8554 /* if we've returned to lowest level and we aren't absorbing all args */
8555 if ((*depthptr) == 0 && rest_args == 0)
8556 return bp;
8557 break;
8559 bp++;
8562 return bp;
8565 /* Discard comments and duplicate newlines
8566 in the string of length LENGTH at START,
8567 except inside of string constants.
8568 The string is copied into itself with its beginning staying fixed.
8570 NEWLINES is the number of newlines that must be duplicated.
8571 We assume that that much extra space is available past the end
8572 of the string. */
8574 static int
8575 discard_comments (start, length, newlines)
8576 U_CHAR *start;
8577 int length;
8578 int newlines;
8580 register U_CHAR *ibp;
8581 register U_CHAR *obp;
8582 register U_CHAR *limit;
8583 register int c;
8585 /* If we have newlines to duplicate, copy everything
8586 that many characters up. Then, in the second part,
8587 we will have room to insert the newlines
8588 while copying down.
8589 NEWLINES may actually be too large, because it counts
8590 newlines in string constants, and we don't duplicate those.
8591 But that does no harm. */
8592 if (newlines > 0) {
8593 ibp = start + length;
8594 obp = ibp + newlines;
8595 limit = start;
8596 while (limit != ibp)
8597 *--obp = *--ibp;
8600 ibp = start + newlines;
8601 limit = start + length + newlines;
8602 obp = start;
8604 while (ibp < limit) {
8605 *obp++ = c = *ibp++;
8606 switch (c) {
8607 case '\n':
8608 /* Duplicate the newline. */
8609 *obp++ = '\n';
8610 break;
8612 case '\\':
8613 if (*ibp == '\n') {
8614 obp--;
8615 ibp++;
8617 break;
8619 case '/':
8620 if (*ibp == '\\' && ibp[1] == '\n')
8621 newline_fix (ibp);
8622 /* Delete any comment. */
8623 if (cplusplus_comments && ibp[0] == '/') {
8624 /* Comments are equivalent to spaces. */
8625 obp[-1] = ' ';
8626 ibp++;
8627 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8628 ibp++;
8629 break;
8631 if (ibp[0] != '*' || ibp + 1 >= limit)
8632 break;
8633 /* Comments are equivalent to spaces.
8634 For -traditional, a comment is equivalent to nothing. */
8635 if (traditional)
8636 obp--;
8637 else
8638 obp[-1] = ' ';
8639 ibp++;
8640 while (ibp + 1 < limit) {
8641 if (ibp[0] == '*'
8642 && ibp[1] == '\\' && ibp[2] == '\n')
8643 newline_fix (ibp + 1);
8644 if (ibp[0] == '*' && ibp[1] == '/')
8645 break;
8646 ibp++;
8648 ibp += 2;
8649 break;
8651 case '\'':
8652 case '\"':
8653 /* Notice and skip strings, so that we don't
8654 think that comments start inside them,
8655 and so we don't duplicate newlines in them. */
8657 int quotec = c;
8658 while (ibp < limit) {
8659 *obp++ = c = *ibp++;
8660 if (c == quotec)
8661 break;
8662 if (c == '\n' && quotec == '\'')
8663 break;
8664 if (c == '\\' && ibp < limit) {
8665 while (*ibp == '\\' && ibp[1] == '\n')
8666 ibp += 2;
8667 *obp++ = *ibp++;
8671 break;
8675 return obp - start;
8678 /* Turn newlines to spaces in the string of length LENGTH at START,
8679 except inside of string constants.
8680 The string is copied into itself with its beginning staying fixed. */
8682 static int
8683 change_newlines (start, length)
8684 U_CHAR *start;
8685 int length;
8687 register U_CHAR *ibp;
8688 register U_CHAR *obp;
8689 register U_CHAR *limit;
8690 register int c;
8692 ibp = start;
8693 limit = start + length;
8694 obp = start;
8696 while (ibp < limit) {
8697 *obp++ = c = *ibp++;
8698 switch (c) {
8699 case '\n':
8700 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8701 string. Skip past the newline and its duplicate.
8702 Put a space in the output. */
8703 if (*ibp == '\n')
8705 ibp++;
8706 obp--;
8707 *obp++ = ' ';
8709 break;
8711 case '\'':
8712 case '\"':
8713 /* Notice and skip strings, so that we don't delete newlines in them. */
8715 int quotec = c;
8716 while (ibp < limit) {
8717 *obp++ = c = *ibp++;
8718 if (c == quotec)
8719 break;
8720 if (c == '\n' && quotec == '\'')
8721 break;
8724 break;
8728 return obp - start;
8731 /* my_strerror - return the descriptive text associated with an
8732 `errno' code. */
8734 char *
8735 my_strerror (errnum)
8736 int errnum;
8738 char *result;
8740 #ifndef VMS
8741 #ifndef HAVE_STRERROR
8742 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8743 #else
8744 result = strerror (errnum);
8745 #endif
8746 #else /* VMS */
8747 /* VAXCRTL's strerror() takes an optional second argument, which only
8748 matters when the first argument is EVMSERR. However, it's simplest
8749 just to pass it unconditionally. `vaxc$errno' is declared in
8750 <errno.h>, and maintained by the library in parallel with `errno'.
8751 We assume that caller's `errnum' either matches the last setting of
8752 `errno' by the library or else does not have the value `EVMSERR'. */
8754 result = strerror (errnum, vaxc$errno);
8755 #endif
8757 if (!result)
8758 result = "undocumented I/O error";
8760 return result;
8763 /* error - print error message and increment count of errors. */
8765 void
8766 error (PRINTF_ALIST (msg))
8767 PRINTF_DCL (msg)
8769 va_list args;
8771 VA_START (args, msg);
8772 verror (msg, args);
8773 va_end (args);
8776 static void
8777 verror (msg, args)
8778 char *msg;
8779 va_list args;
8781 int i;
8782 FILE_BUF *ip = NULL;
8784 print_containing_files ();
8786 for (i = indepth; i >= 0; i--)
8787 if (instack[i].fname != NULL) {
8788 ip = &instack[i];
8789 break;
8792 if (ip != NULL)
8793 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8794 vfprintf (stderr, msg, args);
8795 fprintf (stderr, "\n");
8796 errors++;
8799 /* Error including a message from `errno'. */
8801 static void
8802 error_from_errno (name)
8803 char *name;
8805 int i;
8806 FILE_BUF *ip = NULL;
8808 print_containing_files ();
8810 for (i = indepth; i >= 0; i--)
8811 if (instack[i].fname != NULL) {
8812 ip = &instack[i];
8813 break;
8816 if (ip != NULL)
8817 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8819 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8821 errors++;
8824 /* Print error message but don't count it. */
8826 void
8827 warning (PRINTF_ALIST (msg))
8828 PRINTF_DCL (msg)
8830 va_list args;
8832 VA_START (args, msg);
8833 vwarning (msg, args);
8834 va_end (args);
8837 static void
8838 vwarning (msg, args)
8839 char *msg;
8840 va_list args;
8842 int i;
8843 FILE_BUF *ip = NULL;
8845 if (inhibit_warnings)
8846 return;
8848 if (warnings_are_errors)
8849 errors++;
8851 print_containing_files ();
8853 for (i = indepth; i >= 0; i--)
8854 if (instack[i].fname != NULL) {
8855 ip = &instack[i];
8856 break;
8859 if (ip != NULL)
8860 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8861 fprintf (stderr, "warning: ");
8862 vfprintf (stderr, msg, args);
8863 fprintf (stderr, "\n");
8866 static void
8867 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8868 error_with_line (int line, PRINTF_ALIST (msg))
8869 #else
8870 error_with_line (line, PRINTF_ALIST (msg))
8871 int line;
8872 PRINTF_DCL (msg)
8873 #endif
8875 va_list args;
8877 VA_START (args, msg);
8878 verror_with_line (line, msg, args);
8879 va_end (args);
8882 static void
8883 verror_with_line (line, msg, args)
8884 int line;
8885 char *msg;
8886 va_list args;
8888 int i;
8889 FILE_BUF *ip = NULL;
8891 print_containing_files ();
8893 for (i = indepth; i >= 0; i--)
8894 if (instack[i].fname != NULL) {
8895 ip = &instack[i];
8896 break;
8899 if (ip != NULL)
8900 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8901 vfprintf (stderr, msg, args);
8902 fprintf (stderr, "\n");
8903 errors++;
8906 static void
8907 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8908 warning_with_line (int line, PRINTF_ALIST (msg))
8909 #else
8910 warning_with_line (line, PRINTF_ALIST (msg))
8911 int line;
8912 PRINTF_DCL (msg)
8913 #endif
8915 va_list args;
8917 VA_START (args, msg);
8918 vwarning_with_line (line, msg, args);
8919 va_end (args);
8922 static void
8923 vwarning_with_line (line, msg, args)
8924 int line;
8925 char *msg;
8926 va_list args;
8928 int i;
8929 FILE_BUF *ip = NULL;
8931 if (inhibit_warnings)
8932 return;
8934 if (warnings_are_errors)
8935 errors++;
8937 print_containing_files ();
8939 for (i = indepth; i >= 0; i--)
8940 if (instack[i].fname != NULL) {
8941 ip = &instack[i];
8942 break;
8945 if (ip != NULL)
8946 fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
8947 fprintf (stderr, "warning: ");
8948 vfprintf (stderr, msg, args);
8949 fprintf (stderr, "\n");
8952 /* Print an error message and maybe count it. */
8954 void
8955 pedwarn (PRINTF_ALIST (msg))
8956 PRINTF_DCL (msg)
8958 va_list args;
8960 VA_START (args, msg);
8961 if (pedantic_errors)
8962 verror (msg, args);
8963 else
8964 vwarning (msg, args);
8965 va_end (args);
8968 void
8969 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8970 pedwarn_with_line (int line, PRINTF_ALIST (msg))
8971 #else
8972 pedwarn_with_line (line, PRINTF_ALIST (msg))
8973 int line;
8974 PRINTF_DCL (msg)
8975 #endif
8977 va_list args;
8979 VA_START (args, msg);
8980 if (pedantic_errors)
8981 verror_with_line (line, msg, args);
8982 else
8983 vwarning_with_line (line, msg, args);
8984 va_end (args);
8987 /* Report a warning (or an error if pedantic_errors)
8988 giving specified file name and line number, not current. */
8990 static void
8991 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8992 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
8993 #else
8994 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
8995 char *file;
8996 int line;
8997 PRINTF_DCL (msg)
8998 #endif
9000 va_list args;
9002 if (!pedantic_errors && inhibit_warnings)
9003 return;
9004 if (file != NULL)
9005 fprintf (stderr, "%s:%d: ", file, line);
9006 if (pedantic_errors)
9007 errors++;
9008 if (!pedantic_errors)
9009 fprintf (stderr, "warning: ");
9010 VA_START (args, msg);
9011 vfprintf (stderr, msg, args);
9012 va_end (args);
9013 fprintf (stderr, "\n");
9016 /* Print the file names and line numbers of the #include
9017 directives which led to the current file. */
9019 static void
9020 print_containing_files ()
9022 FILE_BUF *ip = NULL;
9023 int i;
9024 int first = 1;
9026 /* If stack of files hasn't changed since we last printed
9027 this info, don't repeat it. */
9028 if (last_error_tick == input_file_stack_tick)
9029 return;
9031 for (i = indepth; i >= 0; i--)
9032 if (instack[i].fname != NULL) {
9033 ip = &instack[i];
9034 break;
9037 /* Give up if we don't find a source file. */
9038 if (ip == NULL)
9039 return;
9041 /* Find the other, outer source files. */
9042 for (i--; i >= 0; i--)
9043 if (instack[i].fname != NULL) {
9044 ip = &instack[i];
9045 if (first) {
9046 first = 0;
9047 fprintf (stderr, "In file included");
9048 } else {
9049 fprintf (stderr, ",\n ");
9052 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9054 if (! first)
9055 fprintf (stderr, ":\n");
9057 /* Record we have printed the status as of this time. */
9058 last_error_tick = input_file_stack_tick;
9061 /* Return the line at which an error occurred.
9062 The error is not necessarily associated with the current spot
9063 in the input stack, so LINE says where. LINE will have been
9064 copied from ip->lineno for the current input level.
9065 If the current level is for a file, we return LINE.
9066 But if the current level is not for a file, LINE is meaningless.
9067 In that case, we return the lineno of the innermost file. */
9069 static int
9070 line_for_error (line)
9071 int line;
9073 int i;
9074 int line1 = line;
9076 for (i = indepth; i >= 0; ) {
9077 if (instack[i].fname != 0)
9078 return line1;
9079 i--;
9080 if (i < 0)
9081 return 0;
9082 line1 = instack[i].lineno;
9084 abort ();
9085 /*NOTREACHED*/
9086 return 0;
9090 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9092 * As things stand, nothing is ever placed in the output buffer to be
9093 * removed again except when it's KNOWN to be part of an identifier,
9094 * so flushing and moving down everything left, instead of expanding,
9095 * should work ok.
9098 /* You might think void was cleaner for the return type,
9099 but that would get type mismatch in check_expand in strict ANSI. */
9101 static int
9102 grow_outbuf (obuf, needed)
9103 register FILE_BUF *obuf;
9104 register int needed;
9106 register U_CHAR *p;
9107 int minsize;
9109 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9110 return 0;
9112 /* Make it at least twice as big as it is now. */
9113 obuf->length *= 2;
9114 /* Make it have at least 150% of the free space we will need. */
9115 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9116 if (minsize > obuf->length)
9117 obuf->length = minsize;
9119 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9120 memory_full ();
9122 obuf->bufp = p + (obuf->bufp - obuf->buf);
9123 obuf->buf = p;
9125 return 0;
9128 /* Symbol table for macro names and special symbols */
9131 * install a name in the main hash table, even if it is already there.
9132 * name stops with first non alphanumeric, except leading '#'.
9133 * caller must check against redefinition if that is desired.
9134 * delete_macro () removes things installed by install () in fifo order.
9135 * this is important because of the `defined' special symbol used
9136 * in #if, and also if pushdef/popdef directives are ever implemented.
9138 * If LEN is >= 0, it is the length of the name.
9139 * Otherwise, compute the length by scanning the entire name.
9141 * If HASH is >= 0, it is the precomputed hash code.
9142 * Otherwise, compute the hash code.
9145 static HASHNODE *
9146 install (name, len, type, value, hash)
9147 U_CHAR *name;
9148 int len;
9149 enum node_type type;
9150 char *value;
9151 int hash;
9153 register HASHNODE *hp;
9154 register int i, bucket;
9155 register U_CHAR *p, *q;
9157 if (len < 0) {
9158 p = name;
9159 while (is_idchar[*p])
9160 p++;
9161 len = p - name;
9164 if (hash < 0)
9165 hash = hashf (name, len, HASHSIZE);
9167 i = sizeof (HASHNODE) + len + 1;
9168 hp = (HASHNODE *) xmalloc (i);
9169 bucket = hash;
9170 hp->bucket_hdr = &hashtab[bucket];
9171 hp->next = hashtab[bucket];
9172 hashtab[bucket] = hp;
9173 hp->prev = NULL;
9174 if (hp->next != NULL)
9175 hp->next->prev = hp;
9176 hp->type = type;
9177 hp->length = len;
9178 hp->value.cpval = value;
9179 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9180 p = hp->name;
9181 q = name;
9182 for (i = 0; i < len; i++)
9183 *p++ = *q++;
9184 hp->name[len] = 0;
9185 return hp;
9189 * find the most recent hash node for name name (ending with first
9190 * non-identifier char) installed by install
9192 * If LEN is >= 0, it is the length of the name.
9193 * Otherwise, compute the length by scanning the entire name.
9195 * If HASH is >= 0, it is the precomputed hash code.
9196 * Otherwise, compute the hash code.
9199 HASHNODE *
9200 lookup (name, len, hash)
9201 U_CHAR *name;
9202 int len;
9203 int hash;
9205 register U_CHAR *bp;
9206 register HASHNODE *bucket;
9208 if (len < 0) {
9209 for (bp = name; is_idchar[*bp]; bp++) ;
9210 len = bp - name;
9213 if (hash < 0)
9214 hash = hashf (name, len, HASHSIZE);
9216 bucket = hashtab[hash];
9217 while (bucket) {
9218 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9219 return bucket;
9220 bucket = bucket->next;
9222 return NULL;
9226 * Delete a hash node. Some weirdness to free junk from macros.
9227 * More such weirdness will have to be added if you define more hash
9228 * types that need it.
9231 /* Note that the DEFINITION of a macro is removed from the hash table
9232 but its storage is not freed. This would be a storage leak
9233 except that it is not reasonable to keep undefining and redefining
9234 large numbers of macros many times.
9235 In any case, this is necessary, because a macro can be #undef'd
9236 in the middle of reading the arguments to a call to it.
9237 If #undef freed the DEFINITION, that would crash. */
9239 static void
9240 delete_macro (hp)
9241 HASHNODE *hp;
9244 if (hp->prev != NULL)
9245 hp->prev->next = hp->next;
9246 if (hp->next != NULL)
9247 hp->next->prev = hp->prev;
9249 /* Make sure that the bucket chain header that the deleted guy was
9250 on points to the right thing afterwards. */
9251 if (hp == *hp->bucket_hdr)
9252 *hp->bucket_hdr = hp->next;
9254 #if 0
9255 if (hp->type == T_MACRO) {
9256 DEFINITION *d = hp->value.defn;
9257 struct reflist *ap, *nextap;
9259 for (ap = d->pattern; ap != NULL; ap = nextap) {
9260 nextap = ap->next;
9261 free (ap);
9263 free (d);
9265 #endif
9266 free (hp);
9270 * return hash function on name. must be compatible with the one
9271 * computed a step at a time, elsewhere
9274 static int
9275 hashf (name, len, hashsize)
9276 register U_CHAR *name;
9277 register int len;
9278 int hashsize;
9280 register int r = 0;
9282 while (len--)
9283 r = HASHSTEP (r, *name++);
9285 return MAKE_POS (r) % hashsize;
9289 /* Dump the definition of a single macro HP to OF. */
9291 static void
9292 dump_single_macro (hp, of)
9293 register HASHNODE *hp;
9294 FILE *of;
9296 register DEFINITION *defn = hp->value.defn;
9297 struct reflist *ap;
9298 int offset;
9299 int concat;
9302 /* Print the definition of the macro HP. */
9304 fprintf (of, "#define %s", hp->name);
9306 if (defn->nargs >= 0) {
9307 int i;
9309 fprintf (of, "(");
9310 for (i = 0; i < defn->nargs; i++) {
9311 dump_arg_n (defn, i, of);
9312 if (i + 1 < defn->nargs)
9313 fprintf (of, ", ");
9315 fprintf (of, ")");
9318 fprintf (of, " ");
9320 offset = 0;
9321 concat = 0;
9322 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9323 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9324 offset += ap->nchars;
9325 if (!traditional) {
9326 if (ap->nchars != 0)
9327 concat = 0;
9328 if (ap->stringify) {
9329 switch (ap->stringify) {
9330 case SHARP_TOKEN: fprintf (of, "#"); break;
9331 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9332 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9333 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9334 default: abort ();
9337 if (ap->raw_before != 0) {
9338 if (concat) {
9339 switch (ap->raw_before) {
9340 case WHITE_SHARP_TOKEN:
9341 case WHITE_PERCENT_COLON_TOKEN:
9342 fprintf (of, " ");
9343 break;
9344 default:
9345 break;
9347 } else {
9348 switch (ap->raw_before) {
9349 case SHARP_TOKEN: fprintf (of, "##"); break;
9350 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9351 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9352 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9353 default: abort ();
9357 concat = 0;
9359 dump_arg_n (defn, ap->argno, of);
9360 if (!traditional && ap->raw_after != 0) {
9361 switch (ap->raw_after) {
9362 case SHARP_TOKEN: fprintf (of, "##"); break;
9363 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9364 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9365 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9366 default: abort ();
9368 concat = 1;
9371 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9372 fprintf (of, "\n");
9375 /* Dump all macro definitions as #defines to stdout. */
9377 static void
9378 dump_all_macros ()
9380 int bucket;
9382 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9383 register HASHNODE *hp;
9385 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9386 if (hp->type == T_MACRO)
9387 dump_single_macro (hp, stdout);
9392 /* Output to OF a substring of a macro definition.
9393 BASE is the beginning of the definition.
9394 Output characters START thru LENGTH.
9395 Unless traditional, discard newlines outside of strings, thus
9396 converting funny-space markers to ordinary spaces. */
9398 static void
9399 dump_defn_1 (base, start, length, of)
9400 U_CHAR *base;
9401 int start;
9402 int length;
9403 FILE *of;
9405 U_CHAR *p = base + start;
9406 U_CHAR *limit = base + start + length;
9408 if (traditional)
9409 fwrite (p, sizeof (*p), length, of);
9410 else {
9411 while (p < limit) {
9412 if (*p == '\"' || *p =='\'') {
9413 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9414 NULL_PTR, NULL_PTR);
9415 fwrite (p, sizeof (*p), p1 - p, of);
9416 p = p1;
9417 } else {
9418 if (*p != '\n')
9419 putc (*p, of);
9420 p++;
9426 /* Print the name of argument number ARGNUM of macro definition DEFN
9427 to OF.
9428 Recall that DEFN->args.argnames contains all the arg names
9429 concatenated in reverse order with comma-space in between. */
9431 static void
9432 dump_arg_n (defn, argnum, of)
9433 DEFINITION *defn;
9434 int argnum;
9435 FILE *of;
9437 register U_CHAR *p = defn->args.argnames;
9438 while (argnum + 1 < defn->nargs) {
9439 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9440 argnum++;
9443 while (*p && *p != ',') {
9444 putc (*p, of);
9445 p++;
9449 /* Initialize syntactic classifications of characters. */
9451 static void
9452 initialize_char_syntax ()
9454 register int i;
9457 * Set up is_idchar and is_idstart tables. These should be
9458 * faster than saying (is_alpha (c) || c == '_'), etc.
9459 * Set up these things before calling any routines tthat
9460 * refer to them.
9462 for (i = 'a'; i <= 'z'; i++) {
9463 is_idchar[i - 'a' + 'A'] = 1;
9464 is_idchar[i] = 1;
9465 is_idstart[i - 'a' + 'A'] = 1;
9466 is_idstart[i] = 1;
9468 for (i = '0'; i <= '9'; i++)
9469 is_idchar[i] = 1;
9470 is_idchar['_'] = 1;
9471 is_idstart['_'] = 1;
9472 is_idchar['$'] = 1;
9473 is_idstart['$'] = 1;
9475 /* horizontal space table */
9476 is_hor_space[' '] = 1;
9477 is_hor_space['\t'] = 1;
9478 is_hor_space['\v'] = 1;
9479 is_hor_space['\f'] = 1;
9480 is_hor_space['\r'] = 1;
9482 is_space[' '] = 1;
9483 is_space['\t'] = 1;
9484 is_space['\v'] = 1;
9485 is_space['\f'] = 1;
9486 is_space['\n'] = 1;
9487 is_space['\r'] = 1;
9489 char_name['\v'] = "vertical tab";
9490 char_name['\f'] = "formfeed";
9491 char_name['\r'] = "carriage return";
9494 /* Initialize the built-in macros. */
9496 static void
9497 initialize_builtins (inp, outp)
9498 FILE_BUF *inp;
9499 FILE_BUF *outp;
9501 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9502 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9503 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9504 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9505 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9506 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9507 #ifndef NO_BUILTIN_SIZE_TYPE
9508 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9509 #endif
9510 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9511 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9512 #endif
9513 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9514 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9515 NULL_PTR, -1);
9516 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9517 NULL_PTR, -1);
9518 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9519 NULL_PTR, -1);
9520 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9521 if (!traditional) {
9522 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9523 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9525 if (objc)
9526 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9527 /* This is supplied using a -D by the compiler driver
9528 so that it is present only when truly compiling with GNU C. */
9529 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9530 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9532 if (debug_output)
9534 char directive[2048];
9535 U_CHAR *udirective = (U_CHAR *) directive;
9536 register struct directive *dp = &directive_table[0];
9537 struct tm *timebuf = timestamp ();
9539 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9540 instack[0].nominal_fname);
9541 output_line_directive (inp, outp, 0, same_file);
9542 pass_thru_directive (udirective, &udirective[strlen (directive)],
9543 outp, dp);
9545 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9546 output_line_directive (inp, outp, 0, same_file);
9547 pass_thru_directive (udirective, &udirective[strlen (directive)],
9548 outp, dp);
9550 #ifndef NO_BUILTIN_SIZE_TYPE
9551 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9552 output_line_directive (inp, outp, 0, same_file);
9553 pass_thru_directive (udirective, &udirective[strlen (directive)],
9554 outp, dp);
9555 #endif
9557 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9558 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9559 output_line_directive (inp, outp, 0, same_file);
9560 pass_thru_directive (udirective, &udirective[strlen (directive)],
9561 outp, dp);
9562 #endif
9564 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9565 output_line_directive (inp, outp, 0, same_file);
9566 pass_thru_directive (udirective, &udirective[strlen (directive)],
9567 outp, dp);
9569 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9570 monthnames[timebuf->tm_mon],
9571 timebuf->tm_mday, timebuf->tm_year + 1900);
9572 output_line_directive (inp, outp, 0, same_file);
9573 pass_thru_directive (udirective, &udirective[strlen (directive)],
9574 outp, dp);
9576 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9577 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9578 output_line_directive (inp, outp, 0, same_file);
9579 pass_thru_directive (udirective, &udirective[strlen (directive)],
9580 outp, dp);
9582 if (!traditional)
9584 sprintf (directive, " __STDC__ 1");
9585 output_line_directive (inp, outp, 0, same_file);
9586 pass_thru_directive (udirective, &udirective[strlen (directive)],
9587 outp, dp);
9589 if (objc)
9591 sprintf (directive, " __OBJC__ 1");
9592 output_line_directive (inp, outp, 0, same_file);
9593 pass_thru_directive (udirective, &udirective[strlen (directive)],
9594 outp, dp);
9600 * process a given definition string, for initialization
9601 * If STR is just an identifier, define it with value 1.
9602 * If STR has anything after the identifier, then it should
9603 * be identifier=definition.
9606 static void
9607 make_definition (str, op)
9608 char *str;
9609 FILE_BUF *op;
9611 FILE_BUF *ip;
9612 struct directive *kt;
9613 U_CHAR *buf, *p;
9615 p = buf = (U_CHAR *) str;
9616 if (!is_idstart[*p]) {
9617 error ("malformed option `-D %s'", str);
9618 return;
9620 while (is_idchar[*++p])
9622 if (*p == '(') {
9623 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9625 if (*p++ != ')')
9626 p = (U_CHAR *) str; /* Error */
9628 if (*p == 0) {
9629 buf = (U_CHAR *) alloca (p - buf + 4);
9630 strcpy ((char *)buf, str);
9631 strcat ((char *)buf, " 1");
9632 } else if (*p != '=') {
9633 error ("malformed option `-D %s'", str);
9634 return;
9635 } else {
9636 U_CHAR *q;
9637 /* Copy the entire option so we can modify it. */
9638 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9639 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9640 /* Change the = to a space. */
9641 buf[p - (U_CHAR *) str] = ' ';
9642 /* Scan for any backslash-newline and remove it. */
9643 p++;
9644 q = &buf[p - (U_CHAR *) str];
9645 while (*p) {
9646 if (*p == '\"' || *p == '\'') {
9647 int unterminated = 0;
9648 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9649 NULL_PTR, NULL_PTR, &unterminated);
9650 if (unterminated)
9651 return;
9652 while (p != p1)
9653 if (*p == '\\' && p[1] == '\n')
9654 p += 2;
9655 else
9656 *q++ = *p++;
9657 } else if (*p == '\\' && p[1] == '\n')
9658 p += 2;
9659 /* Change newline chars into newline-markers. */
9660 else if (*p == '\n')
9662 *q++ = '\n';
9663 *q++ = '\n';
9664 p++;
9666 else
9667 *q++ = *p++;
9669 *q = 0;
9672 ip = &instack[++indepth];
9673 ip->nominal_fname = ip->fname = "*Initialization*";
9675 ip->buf = ip->bufp = buf;
9676 ip->length = strlen ((char *) buf);
9677 ip->lineno = 1;
9678 ip->macro = 0;
9679 ip->free_ptr = 0;
9680 ip->if_stack = if_stack;
9681 ip->system_header_p = 0;
9683 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9686 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9687 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9688 --indepth;
9691 /* JF, this does the work for the -U option */
9693 static void
9694 make_undef (str, op)
9695 char *str;
9696 FILE_BUF *op;
9698 FILE_BUF *ip;
9699 struct directive *kt;
9701 ip = &instack[++indepth];
9702 ip->nominal_fname = ip->fname = "*undef*";
9704 ip->buf = ip->bufp = (U_CHAR *) str;
9705 ip->length = strlen (str);
9706 ip->lineno = 1;
9707 ip->macro = 0;
9708 ip->free_ptr = 0;
9709 ip->if_stack = if_stack;
9710 ip->system_header_p = 0;
9712 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9715 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9716 --indepth;
9719 /* Process the string STR as if it appeared as the body of a #assert.
9720 OPTION is the option name for which STR was the argument. */
9722 static void
9723 make_assertion (option, str)
9724 char *option;
9725 char *str;
9727 FILE_BUF *ip;
9728 struct directive *kt;
9729 U_CHAR *buf, *p, *q;
9731 /* Copy the entire option so we can modify it. */
9732 buf = (U_CHAR *) alloca (strlen (str) + 1);
9733 strcpy ((char *) buf, str);
9734 /* Scan for any backslash-newline and remove it. */
9735 p = q = buf;
9736 while (*p) {
9737 if (*p == '\\' && p[1] == '\n')
9738 p += 2;
9739 else
9740 *q++ = *p++;
9742 *q = 0;
9744 p = buf;
9745 if (!is_idstart[*p]) {
9746 error ("malformed option `%s %s'", option, str);
9747 return;
9749 while (is_idchar[*++p])
9751 SKIP_WHITE_SPACE (p);
9752 if (! (*p == 0 || *p == '(')) {
9753 error ("malformed option `%s %s'", option, str);
9754 return;
9757 ip = &instack[++indepth];
9758 ip->nominal_fname = ip->fname = "*Initialization*";
9760 ip->buf = ip->bufp = buf;
9761 ip->length = strlen ((char *) buf);
9762 ip->lineno = 1;
9763 ip->macro = 0;
9764 ip->free_ptr = 0;
9765 ip->if_stack = if_stack;
9766 ip->system_header_p = 0;
9768 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9771 /* Pass NULL as output ptr to do_define since we KNOW it never does
9772 any output.... */
9773 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9774 --indepth;
9777 #ifndef DIR_SEPARATOR
9778 #define DIR_SEPARATOR '/'
9779 #endif
9781 /* The previous include prefix, if any, is PREV_FILE_NAME.
9782 Translate any pathnames with COMPONENT.
9783 Allocate a new include prefix whose name is the
9784 simplified concatenation of PREFIX and NAME,
9785 with a trailing / added if needed.
9786 But return 0 if the include prefix should be ignored,
9787 e.g. because it is a duplicate of PREV_FILE_NAME. */
9789 static struct file_name_list *
9790 new_include_prefix (prev_file_name, component, prefix, name)
9791 struct file_name_list *prev_file_name;
9792 char *component;
9793 char *prefix;
9794 char *name;
9796 if (name == 0)
9797 fatal ("Directory name missing after command line option");
9799 if (*name == 0)
9800 /* Ignore the empty string. */
9801 return 0;
9803 prefix = update_path (prefix, component);
9804 name = update_path (name, component);
9807 struct file_name_list *dir
9808 = ((struct file_name_list *)
9809 xmalloc (sizeof (struct file_name_list)
9810 + strlen (prefix) + strlen (name) + 2));
9811 size_t len;
9812 strcpy (dir->fname, prefix);
9813 strcat (dir->fname, name);
9814 len = simplify_filename (dir->fname);
9816 /* Convert directory name to a prefix. */
9817 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
9818 if (len == 1 && dir->fname[len - 1] == '.')
9819 len = 0;
9820 else
9821 dir->fname[len++] = DIR_SEPARATOR;
9822 dir->fname[len] = 0;
9825 /* Ignore a directory whose name matches the previous one. */
9826 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9827 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9828 if (!first_bracket_include)
9829 first_bracket_include = prev_file_name;
9830 free (dir);
9831 return 0;
9834 #ifndef VMS
9835 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
9837 /* Add a trailing "." if there is a filename. This increases the number
9838 of systems that can stat directories. We remove it below. */
9839 if (len != 0)
9841 dir->fname[len] = '.';
9842 dir->fname[len + 1] = 0;
9845 /* Ignore a nonexistent directory. */
9846 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9847 if (errno != ENOENT && errno != ENOTDIR)
9848 error_from_errno (dir->fname);
9849 free (dir);
9850 return 0;
9853 if (len != 0)
9854 dir->fname[len] = 0;
9856 /* Ignore a directory whose identity matches the previous one. */
9857 if (prev_file_name
9858 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9859 && prev_file_name->st.st_dev == dir->st.st_dev) {
9860 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9861 if (!first_bracket_include)
9862 first_bracket_include = prev_file_name;
9863 free (dir);
9864 return 0;
9866 #endif /* ! VMS */
9868 dir->next = 0;
9869 dir->c_system_include_path = 0;
9870 dir->got_name_map = 0;
9872 return dir;
9876 /* Append a chain of `struct file_name_list's
9877 to the end of the main include chain.
9878 FIRST is the beginning of the chain to append, and LAST is the end. */
9880 static void
9881 append_include_chain (first, last)
9882 struct file_name_list *first, *last;
9884 struct file_name_list *dir;
9886 if (!first || !last)
9887 return;
9889 if (include == 0)
9890 include = first;
9891 else
9892 last_include->next = first;
9894 if (first_bracket_include == 0)
9895 first_bracket_include = first;
9897 for (dir = first; ; dir = dir->next) {
9898 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9899 if (len > max_include_len)
9900 max_include_len = len;
9901 if (dir == last)
9902 break;
9905 last->next = NULL;
9906 last_include = last;
9909 /* Place into DST a representation of the file named SRC that is suitable
9910 for `make'. Do not null-terminate DST. Return its length. */
9911 static int
9912 quote_string_for_make (dst, src)
9913 char *dst;
9914 char *src;
9916 char *p = src;
9917 int i = 0;
9918 for (;;)
9920 char c = *p++;
9921 switch (c)
9923 case '\0':
9924 case ' ':
9925 case '\t':
9927 /* GNU make uses a weird quoting scheme for white space.
9928 A space or tab preceded by 2N+1 backslashes represents
9929 N backslashes followed by space; a space or tab
9930 preceded by 2N backslashes represents N backslashes at
9931 the end of a file name; and backslashes in other
9932 contexts should not be doubled. */
9933 char *q;
9934 for (q = p - 1; src < q && q[-1] == '\\'; q--)
9936 if (dst)
9937 dst[i] = '\\';
9938 i++;
9941 if (!c)
9942 return i;
9943 if (dst)
9944 dst[i] = '\\';
9945 i++;
9946 goto ordinary_char;
9948 case '$':
9949 if (dst)
9950 dst[i] = c;
9951 i++;
9952 /* Fall through. This can mishandle things like "$(" but
9953 there's no easy fix. */
9954 default:
9955 ordinary_char:
9956 /* This can mishandle characters in the string "\0\n%*?[\\~";
9957 exactly which chars are mishandled depends on the `make' version.
9958 We know of no portable solution for this;
9959 even GNU make 3.76.1 doesn't solve the problem entirely.
9960 (Also, '\0' is mishandled due to our calling conventions.) */
9961 if (dst)
9962 dst[i] = c;
9963 i++;
9964 break;
9970 /* Add output to `deps_buffer' for the -M switch.
9971 STRING points to the text to be output.
9972 SPACER is ':' for targets, ' ' for dependencies. */
9974 static void
9975 deps_output (string, spacer)
9976 char *string;
9977 int spacer;
9979 int size = quote_string_for_make ((char *) 0, string);
9981 if (size == 0)
9982 return;
9984 #ifndef MAX_OUTPUT_COLUMNS
9985 #define MAX_OUTPUT_COLUMNS 72
9986 #endif
9987 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9988 && 1 < deps_column) {
9989 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9990 deps_size += 4;
9991 deps_column = 1;
9992 if (spacer == ' ')
9993 spacer = 0;
9996 if (deps_size + 2 * size + 8 > deps_allocated_size) {
9997 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
9998 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10000 if (spacer == ' ') {
10001 deps_buffer[deps_size++] = ' ';
10002 deps_column++;
10004 quote_string_for_make (&deps_buffer[deps_size], string);
10005 deps_size += size;
10006 deps_column += size;
10007 if (spacer == ':') {
10008 deps_buffer[deps_size++] = ':';
10009 deps_column++;
10011 deps_buffer[deps_size] = 0;
10014 static void
10015 fatal (PRINTF_ALIST (msg))
10016 PRINTF_DCL (msg)
10018 va_list args;
10020 fprintf (stderr, "%s: ", progname);
10021 VA_START (args, msg);
10022 vfprintf (stderr, msg, args);
10023 va_end (args);
10024 fprintf (stderr, "\n");
10025 exit (FATAL_EXIT_CODE);
10028 /* More 'friendly' abort that prints the line and file.
10029 config.h can #define abort fancy_abort if you like that sort of thing. */
10031 void
10032 fancy_abort ()
10034 fatal ("Internal gcc abort.");
10037 static void
10038 perror_with_name (name)
10039 char *name;
10041 fprintf (stderr, "%s: ", progname);
10042 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
10043 errors++;
10046 static void
10047 pfatal_with_name (name)
10048 char *name;
10050 perror_with_name (name);
10051 #ifdef VMS
10052 exit (vaxc$errno);
10053 #else
10054 exit (FATAL_EXIT_CODE);
10055 #endif
10058 /* Handler for SIGPIPE. */
10060 static void
10061 pipe_closed (signo)
10062 /* If this is missing, some compilers complain. */
10063 int signo;
10065 fatal ("output pipe has been closed");
10068 static void
10069 memory_full ()
10071 fatal ("Memory exhausted.");
10075 GENERIC_PTR
10076 xmalloc (size)
10077 size_t size;
10079 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10080 if (!ptr)
10081 memory_full ();
10082 return ptr;
10085 static GENERIC_PTR
10086 xrealloc (old, size)
10087 GENERIC_PTR old;
10088 size_t size;
10090 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10091 if (!ptr)
10092 memory_full ();
10093 return ptr;
10096 static GENERIC_PTR
10097 xcalloc (number, size)
10098 size_t number, size;
10100 register size_t total = number * size;
10101 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10102 if (!ptr)
10103 memory_full ();
10104 bzero (ptr, total);
10105 return ptr;
10108 static char *
10109 savestring (input)
10110 char *input;
10112 size_t size = strlen (input);
10113 char *output = xmalloc (size + 1);
10114 strcpy (output, input);
10115 return output;
10118 #ifdef VMS
10120 /* Under VMS we need to fix up the "include" specification filename so
10121 that everything following the 1st slash is changed into its correct
10122 VMS file specification. */
10124 static void
10125 hack_vms_include_specification (fname, vaxc_include)
10126 char *fname;
10127 int vaxc_include;
10129 register char *cp, *cp1, *cp2;
10130 int f, check_filename_before_returning;
10131 char Local[512];
10133 check_filename_before_returning = 0;
10135 cp = base_name (fname);
10138 * Check if we have a vax-c style '#include filename'
10139 * and add the missing .h
10141 if (vaxc_include && !index (cp,'.'))
10142 strcat (cp, ".h");
10144 cp2 = Local; /* initialize */
10146 /* We are trying to do a number of things here. First of all, we are
10147 trying to hammer the filenames into a standard format, such that later
10148 processing can handle them.
10150 If the file name contains something like [dir.], then it recognizes this
10151 as a root, and strips the ".]". Later processing will add whatever is
10152 needed to get things working properly.
10154 If no device is specified, then the first directory name is taken to be
10155 a device name (or a rooted logical). */
10157 /* See if we found that 1st slash */
10158 if (cp == 0) return; /* Nothing to do!!! */
10159 if (*cp != '/') return; /* Nothing to do!!! */
10160 /* Point to the UNIX filename part (which needs to be fixed!) */
10161 cp1 = cp+1;
10162 /* If the directory spec is not rooted, we can just copy
10163 the UNIX filename part and we are done */
10164 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10165 if (cp[-2] != '.') {
10167 * The VMS part ends in a `]', and the preceding character is not a `.'.
10168 * We strip the `]', and then splice the two parts of the name in the
10169 * usual way. Given the default locations for include files in cccp.c,
10170 * we will only use this code if the user specifies alternate locations
10171 * with the /include (-I) switch on the command line. */
10172 cp -= 1; /* Strip "]" */
10173 cp1--; /* backspace */
10174 } else {
10176 * The VMS part has a ".]" at the end, and this will not do. Later
10177 * processing will add a second directory spec, and this would be a syntax
10178 * error. Thus we strip the ".]", and thus merge the directory specs.
10179 * We also backspace cp1, so that it points to a '/'. This inhibits the
10180 * generation of the 000000 root directory spec (which does not belong here
10181 * in this case).
10183 cp -= 2; /* Strip ".]" */
10184 cp1--; }; /* backspace */
10185 } else {
10187 /* We drop in here if there is no VMS style directory specification yet.
10188 * If there is no device specification either, we make the first dir a
10189 * device and try that. If we do not do this, then we will be essentially
10190 * searching the users default directory (as if they did a #include "asdf.h").
10192 * Then all we need to do is to push a '[' into the output string. Later
10193 * processing will fill this in, and close the bracket.
10195 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10196 *cp2++ = '['; /* Open the directory specification */
10199 /* at this point we assume that we have the device spec, and (at least
10200 the opening "[" for a directory specification. We may have directories
10201 specified already */
10203 /* If there are no other slashes then the filename will be
10204 in the "root" directory. Otherwise, we need to add
10205 directory specifications. */
10206 if (index (cp1, '/') == 0) {
10207 /* Just add "000000]" as the directory string */
10208 strcpy (cp2, "000000]");
10209 cp2 += strlen (cp2);
10210 check_filename_before_returning = 1; /* we might need to fool with this later */
10211 } else {
10212 /* As long as there are still subdirectories to add, do them. */
10213 while (index (cp1, '/') != 0) {
10214 /* If this token is "." we can ignore it */
10215 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10216 cp1 += 2;
10217 continue;
10219 /* Add a subdirectory spec. Do not duplicate "." */
10220 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10221 *cp2++ = '.';
10222 /* If this is ".." then the spec becomes "-" */
10223 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10224 /* Add "-" and skip the ".." */
10225 *cp2++ = '-';
10226 cp1 += 3;
10227 continue;
10229 /* Copy the subdirectory */
10230 while (*cp1 != '/') *cp2++= *cp1++;
10231 cp1++; /* Skip the "/" */
10233 /* Close the directory specification */
10234 if (cp2[-1] == '.') /* no trailing periods */
10235 cp2--;
10236 *cp2++ = ']';
10238 /* Now add the filename */
10239 while (*cp1) *cp2++ = *cp1++;
10240 *cp2 = 0;
10241 /* Now append it to the original VMS spec. */
10242 strcpy (cp, Local);
10244 /* If we put a [000000] in the filename, try to open it first. If this fails,
10245 remove the [000000], and return that name. This provides flexibility
10246 to the user in that they can use both rooted and non-rooted logical names
10247 to point to the location of the file. */
10249 if (check_filename_before_returning) {
10250 f = open (fname, O_RDONLY, 0666);
10251 if (f >= 0) {
10252 /* The file name is OK as it is, so return it as is. */
10253 close (f);
10254 return;
10256 /* The filename did not work. Try to remove the [000000] from the name,
10257 and return it. */
10258 cp = index (fname, '[');
10259 cp2 = index (fname, ']') + 1;
10260 strcpy (cp, cp2); /* this gets rid of it */
10262 return;
10264 #endif /* VMS */
10266 #ifdef VMS
10268 /* The following wrapper functions supply additional arguments to the VMS
10269 I/O routines to optimize performance with file handling. The arguments
10270 are:
10271 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10272 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10273 "fop=tef"- Truncate unused portions of file when closing file.
10274 "shr=nil"- Disallow file sharing while file is open. */
10276 static FILE *
10277 VMS_freopen (fname, type, oldfile)
10278 char *fname;
10279 char *type;
10280 FILE *oldfile;
10282 #undef freopen /* Get back the real freopen routine. */
10283 if (strcmp (type, "w") == 0)
10284 return freopen (fname, type, oldfile,
10285 "mbc=16", "deq=64", "fop=tef", "shr=nil");
10286 return freopen (fname, type, oldfile, "mbc=16");
10289 static FILE *
10290 VMS_fopen (fname, type)
10291 char *fname;
10292 char *type;
10294 #undef fopen /* Get back the real fopen routine. */
10295 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10296 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10297 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10298 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10300 if (*type == 'w')
10301 return (*vmslib_fopen) (fname, type, "mbc=32",
10302 "deq=64", "fop=tef", "shr=nil");
10303 else
10304 return (*vmslib_fopen) (fname, type, "mbc=32");
10307 static int
10308 VMS_open (fname, flags, prot)
10309 char *fname;
10310 int flags;
10311 int prot;
10313 #undef open /* Get back the real open routine. */
10314 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10317 /* more VMS hackery */
10318 #include <fab.h>
10319 #include <nam.h>
10321 extern unsigned long SYS$PARSE(), SYS$SEARCH();
10323 /* Work around another library bug. If a file is located via a searchlist,
10324 and if the device it's on is not the same device as the one specified
10325 in the first element of that searchlist, then both stat() and fstat()
10326 will fail to return info about it. `errno' will be set to EVMSERR, and
10327 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10328 We can get around this by fully parsing the filename and then passing
10329 that absolute name to stat().
10331 Without this fix, we can end up failing to find header files, which is
10332 bad enough, but then compounding the problem by reporting the reason for
10333 failure as "normal successful completion." */
10335 #undef fstat /* Get back to the library version. */
10337 static int
10338 VMS_fstat (fd, statbuf)
10339 int fd;
10340 struct stat *statbuf;
10342 int result = fstat (fd, statbuf);
10344 if (result < 0)
10346 FILE *fp;
10347 char nambuf[NAM$C_MAXRSS+1];
10349 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10350 result = VMS_stat (nambuf, statbuf);
10351 /* No fclose(fp) here; that would close(fd) as well. */
10354 return result;
10357 static int
10358 VMS_stat (name, statbuf)
10359 const char *name;
10360 struct stat *statbuf;
10362 int result = stat (name, statbuf);
10364 if (result < 0)
10366 struct FAB fab;
10367 struct NAM nam;
10368 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
10369 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
10371 fab = cc$rms_fab;
10372 fab.fab$l_fna = (char *) name;
10373 fab.fab$b_fns = (unsigned char) strlen (name);
10374 fab.fab$l_nam = (void *) &nam;
10375 nam = cc$rms_nam;
10376 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10377 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10378 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10379 if (SYS$PARSE (&fab) & 1)
10381 if (SYS$SEARCH (&fab) & 1)
10383 res_nam[nam.nam$b_rsl] = '\0';
10384 result = stat (res_nam, statbuf);
10386 /* Clean up searchlist context cached by the system. */
10387 nam.nam$b_nop = NAM$M_SYNCHK;
10388 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10389 (void) SYS$PARSE (&fab);
10393 return result;
10395 #endif /* VMS */