Import gcc-2.8.1.tar.bz2
[official-gcc.git] / gcc / cccp.c
blob28ff4ca601b301aa2767aa50770a52bd0f905b6a
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-97, 1998 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 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
134 #define fopen(fname,mode) VMS_fopen (fname,mode)
135 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
136 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
137 static int VMS_fstat (), VMS_stat ();
138 static int VMS_open ();
139 static FILE *VMS_fopen ();
140 static FILE *VMS_freopen ();
141 static void hack_vms_include_specification ();
142 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
143 #define INO_T_HASH(a) 0
144 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
145 #endif /* VMS */
147 /* Windows does not natively support inodes, and neither does MSDOS. */
148 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
149 #define INO_T_EQ(a, b) 0
150 #endif
152 #ifndef O_RDONLY
153 #define O_RDONLY 0
154 #endif
156 #undef MIN
157 #undef MAX
158 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
159 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
161 /* Find the largest host integer type and set its size and type.
162 Watch out: on some crazy hosts `long' is shorter than `int'. */
164 #ifndef HOST_WIDE_INT
165 # if HAVE_INTTYPES_H
166 # include <inttypes.h>
167 # define HOST_WIDE_INT intmax_t
168 # else
169 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
170 # define HOST_WIDE_INT int
171 # else
172 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
173 # define HOST_WIDE_INT long
174 # else
175 # define HOST_WIDE_INT long long
176 # endif
177 # endif
178 # endif
179 #endif
181 #ifndef S_ISREG
182 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
183 #endif
185 #ifndef S_ISDIR
186 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
187 #endif
189 #ifndef INO_T_EQ
190 #define INO_T_EQ(a, b) ((a) == (b))
191 #endif
193 #ifndef INO_T_HASH
194 #define INO_T_HASH(a) (a)
195 #endif
197 #ifndef INCLUDE_LEN_FUDGE
198 #define INCLUDE_LEN_FUDGE 0
199 #endif
201 /* External declarations. */
203 extern char *version_string;
204 extern char *update_path PROTO((char *, char *));
205 #ifndef VMS
206 #ifndef HAVE_STRERROR
207 extern int sys_nerr;
208 extern char *sys_errlist[];
209 #else /* HAVE_STRERROR */
210 char *strerror ();
211 #endif
212 #else /* VMS */
213 char *strerror (int,...);
214 #endif
215 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
216 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
218 #ifndef errno
219 extern int errno;
220 #endif
222 /* Name under which this program was invoked. */
224 static char *progname;
226 /* Nonzero means use extra default include directories for C++. */
228 static int cplusplus;
230 /* Nonzero means handle cplusplus style comments */
232 static int cplusplus_comments;
234 /* Nonzero means handle #import, for objective C. */
236 static int objc;
238 /* Nonzero means this is an assembly file, and allow
239 unknown directives, which could be comments. */
241 static int lang_asm;
243 /* Current maximum length of directory names in the search path
244 for include files. (Altered as we get more of them.) */
246 static int max_include_len;
248 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
250 static int for_lint = 0;
252 /* Nonzero means copy comments into the output file. */
254 static int put_out_comments = 0;
256 /* Nonzero means don't process the ANSI trigraph sequences. */
258 static int no_trigraphs = 0;
260 /* Nonzero means print the names of included files rather than
261 the preprocessed output. 1 means just the #include "...",
262 2 means #include <...> as well. */
264 static int print_deps = 0;
266 /* Nonzero if missing .h files in -M output are assumed to be generated
267 files and not errors. */
269 static int print_deps_missing_files = 0;
271 /* Nonzero means print names of header files (-H). */
273 static int print_include_names = 0;
275 /* Nonzero means don't output line number information. */
277 static int no_line_directives;
279 /* Nonzero means output the text in failing conditionals,
280 inside #failed ... #endfailed. */
282 static int output_conditionals;
284 /* dump_only means inhibit output of the preprocessed text
285 and instead output the definitions of all user-defined
286 macros in a form suitable for use as input to cccp.
287 dump_names means pass #define and the macro name through to output.
288 dump_definitions means pass the whole definition (plus #define) through
291 static enum {dump_none, dump_only, dump_names, dump_definitions}
292 dump_macros = dump_none;
294 /* Nonzero means pass all #define and #undef directives which we actually
295 process through to the output stream. This feature is used primarily
296 to allow cc1 to record the #defines and #undefs for the sake of
297 debuggers which understand about preprocessor macros, but it may
298 also be useful with -E to figure out how symbols are defined, and
299 where they are defined. */
300 static int debug_output = 0;
302 /* Nonzero means pass #include lines through to the output,
303 even if they are ifdefed out. */
304 static int dump_includes;
306 /* Nonzero indicates special processing used by the pcp program. The
307 special effects of this mode are:
309 Inhibit all macro expansion, except those inside #if directives.
311 Process #define directives normally, and output their contents
312 to the output file.
314 Output preconditions to pcp_outfile indicating all the relevant
315 preconditions for use of this file in a later cpp run.
317 static FILE *pcp_outfile;
319 /* Nonzero means we are inside an IF during a -pcp run. In this mode
320 macro expansion is done, and preconditions are output for all macro
321 uses requiring them. */
322 static int pcp_inside_if;
324 /* Nonzero means never to include precompiled files.
325 This is 1 since there's no way now to make precompiled files,
326 so it's not worth testing for them. */
327 static int no_precomp = 1;
329 /* Nonzero means give all the error messages the ANSI standard requires. */
331 int pedantic;
333 /* Nonzero means try to make failure to fit ANSI C an error. */
335 static int pedantic_errors;
337 /* Nonzero means don't print warning messages. -w. */
339 static int inhibit_warnings = 0;
341 /* Nonzero means warn if slash-star appears in a slash-star comment,
342 or if newline-backslash appears in a slash-slash comment. */
344 static int warn_comments;
346 /* Nonzero means warn if a macro argument is (or would be)
347 stringified with -traditional. */
349 static int warn_stringify;
351 /* Nonzero means warn if there are any trigraphs. */
353 static int warn_trigraphs;
355 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
357 static int warn_undef;
359 /* Nonzero means warn if #import is used. */
361 static int warn_import = 1;
363 /* Nonzero means turn warnings into errors. */
365 static int warnings_are_errors;
367 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
369 int traditional;
371 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
373 int c89;
375 /* Nonzero causes output not to be done,
376 but directives such as #define that have side effects
377 are still obeyed. */
379 static int no_output;
381 /* Nonzero means we should look for header.gcc files that remap file names. */
382 static int remap;
384 /* Nonzero means this file was included with a -imacros or -include
385 command line and should not be recorded as an include file. */
387 static int no_record_file;
389 /* Nonzero means that we have finished processing the command line options.
390 This flag is used to decide whether or not to issue certain errors
391 and/or warnings. */
393 static int done_initializing = 0;
395 /* Line where a newline was first seen in a string constant. */
397 static int multiline_string_line = 0;
399 /* I/O buffer structure.
400 The `fname' field is nonzero for source files and #include files
401 and for the dummy text used for -D and -U.
402 It is zero for rescanning results of macro expansion
403 and for expanding macro arguments. */
404 #define INPUT_STACK_MAX 400
405 static struct file_buf {
406 char *fname;
407 /* Filename specified with #line directive. */
408 char *nominal_fname;
409 /* Include file description. */
410 struct include_file *inc;
411 /* Record where in the search path this file was found.
412 For #include_next. */
413 struct file_name_list *dir;
414 int lineno;
415 int length;
416 U_CHAR *buf;
417 U_CHAR *bufp;
418 /* Macro that this level is the expansion of.
419 Included so that we can reenable the macro
420 at the end of this level. */
421 struct hashnode *macro;
422 /* Value of if_stack at start of this file.
423 Used to prohibit unmatched #endif (etc) in an include file. */
424 struct if_stack *if_stack;
425 /* Object to be freed at end of input at this level. */
426 U_CHAR *free_ptr;
427 /* True if this is a system header file; see is_system_include. */
428 char system_header_p;
429 } instack[INPUT_STACK_MAX];
431 static int last_error_tick; /* Incremented each time we print it. */
432 static int input_file_stack_tick; /* Incremented when the status changes. */
434 /* Current nesting level of input sources.
435 `instack[indepth]' is the level currently being read. */
436 static int indepth = -1;
437 #define CHECK_DEPTH(code) \
438 if (indepth >= (INPUT_STACK_MAX - 1)) \
440 error_with_line (line_for_error (instack[indepth].lineno), \
441 "macro or `#include' recursion too deep"); \
442 code; \
445 /* Current depth in #include directives that use <...>. */
446 static int system_include_depth = 0;
448 typedef struct file_buf FILE_BUF;
450 /* The output buffer. Its LENGTH field is the amount of room allocated
451 for the buffer, not the number of chars actually present. To get
452 that, subtract outbuf.buf from outbuf.bufp. */
454 #define OUTBUF_SIZE 10 /* initial size of output buffer */
455 static FILE_BUF outbuf;
457 /* Grow output buffer OBUF points at
458 so it can hold at least NEEDED more chars. */
460 #define check_expand(OBUF, NEEDED) \
461 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
462 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
464 struct file_name_list
466 struct file_name_list *next;
467 /* If the following is 1, it is a C-language system include
468 directory. */
469 int c_system_include_path;
470 /* Mapping of file names for this directory. */
471 struct file_name_map *name_map;
472 /* Non-zero if name_map is valid. */
473 int got_name_map;
474 /* The include directory status. */
475 struct stat st;
476 /* The include prefix: "" denotes the working directory,
477 otherwise fname must end in '/'.
478 The actual size is dynamically allocated. */
479 char fname[1];
482 /* #include "file" looks in source file dir, then stack. */
483 /* #include <file> just looks in the stack. */
484 /* -I directories are added to the end, then the defaults are added. */
485 /* The */
486 static struct default_include {
487 char *fname; /* The name of the directory. */
488 char *component; /* The component containing the directory */
489 int cplusplus; /* Only look here if we're compiling C++. */
490 int cxx_aware; /* Includes in this directory don't need to
491 be wrapped in extern "C" when compiling
492 C++. */
493 } include_defaults_array[]
494 #ifdef INCLUDE_DEFAULTS
495 = INCLUDE_DEFAULTS;
496 #else
498 /* Pick up GNU C++ specific include files. */
499 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
500 { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
501 #ifdef CROSS_COMPILE
502 /* This is the dir for fixincludes. Put it just before
503 the files that we fix. */
504 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
505 /* For cross-compilation, this dir name is generated
506 automatically in Makefile.in. */
507 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
508 #ifdef TOOL_INCLUDE_DIR
509 /* This is another place that the target system's headers might be. */
510 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
511 #endif
512 #else /* not CROSS_COMPILE */
513 #ifdef LOCAL_INCLUDE_DIR
514 /* This should be /usr/local/include and should come before
515 the fixincludes-fixed header files. */
516 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
517 #endif
518 #ifdef TOOL_INCLUDE_DIR
519 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
520 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
521 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
522 #endif
523 /* This is the dir for fixincludes. Put it just before
524 the files that we fix. */
525 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
526 /* Some systems have an extra dir of include files. */
527 #ifdef SYSTEM_INCLUDE_DIR
528 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
529 #endif
530 #ifndef STANDARD_INCLUDE_COMPONENT
531 #define STANDARD_INCLUDE_COMPONENT 0
532 #endif
533 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
534 #endif /* not CROSS_COMPILE */
535 { 0, 0, 0, 0 }
537 #endif /* no INCLUDE_DEFAULTS */
539 /* The code looks at the defaults through this pointer, rather than through
540 the constant structure above. This pointer gets changed if an environment
541 variable specifies other defaults. */
542 static struct default_include *include_defaults = include_defaults_array;
544 static struct file_name_list *include = 0; /* First dir to search */
545 /* First dir to search for <file> */
546 /* This is the first element to use for #include <...>.
547 If it is 0, use the entire chain for such includes. */
548 static struct file_name_list *first_bracket_include = 0;
549 /* This is the first element in the chain that corresponds to
550 a directory of system header files. */
551 static struct file_name_list *first_system_include = 0;
552 static struct file_name_list *last_include = 0; /* Last in chain */
554 /* Chain of include directories to put at the end of the other chain. */
555 static struct file_name_list *after_include = 0;
556 static struct file_name_list *last_after_include = 0; /* Last in chain */
558 /* Chain to put at the start of the system include files. */
559 static struct file_name_list *before_system = 0;
560 static struct file_name_list *last_before_system = 0; /* Last in chain */
562 /* Directory prefix that should replace `/usr' in the standard
563 include file directories. */
564 static char *include_prefix;
566 /* Maintain and search list of included files. */
568 struct include_file {
569 struct include_file *next; /* for include_hashtab */
570 struct include_file *next_ino; /* for include_ino_hashtab */
571 char *fname;
572 /* If the following is the empty string, it means #pragma once
573 was seen in this include file, or #import was applied to the file.
574 Otherwise, if it is nonzero, it is a macro name.
575 Don't include the file again if that macro is defined. */
576 U_CHAR *control_macro;
577 /* Nonzero if the dependency on this include file has been output. */
578 int deps_output;
579 struct stat st;
582 /* Hash tables of files already included with #include or #import.
583 include_hashtab is by full name; include_ino_hashtab is by inode number. */
585 #define INCLUDE_HASHSIZE 61
586 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
587 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
589 /* Global list of strings read in from precompiled files. This list
590 is kept in the order the strings are read in, with new strings being
591 added at the end through stringlist_tailp. We use this list to output
592 the strings at the end of the run.
594 static STRINGDEF *stringlist;
595 static STRINGDEF **stringlist_tailp = &stringlist;
598 /* Structure returned by create_definition */
599 typedef struct macrodef MACRODEF;
600 struct macrodef
602 struct definition *defn;
603 U_CHAR *symnam;
604 int symlen;
607 enum sharp_token_type {
608 NO_SHARP_TOKEN = 0, /* token not present */
610 SHARP_TOKEN = '#', /* token spelled with # only */
611 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
613 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
614 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
617 /* Structure allocated for every #define. For a simple replacement
618 such as
619 #define foo bar ,
620 nargs = -1, the `pattern' list is null, and the expansion is just
621 the replacement text. Nargs = 0 means a functionlike macro with no args,
622 e.g.,
623 #define getchar() getc (stdin) .
624 When there are args, the expansion is the replacement text with the
625 args squashed out, and the reflist is a list describing how to
626 build the output from the input: e.g., "3 chars, then the 1st arg,
627 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
628 The chars here come from the expansion. Whatever is left of the
629 expansion after the last arg-occurrence is copied after that arg.
630 Note that the reflist can be arbitrarily long---
631 its length depends on the number of times the arguments appear in
632 the replacement text, not how many args there are. Example:
633 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
634 pattern list
635 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
636 where (x, y) means (nchars, argno). */
638 typedef struct definition DEFINITION;
639 struct definition {
640 int nargs;
641 int length; /* length of expansion string */
642 int predefined; /* True if the macro was builtin or */
643 /* came from the command line */
644 U_CHAR *expansion;
645 int line; /* Line number of definition */
646 char *file; /* File of definition */
647 char rest_args; /* Nonzero if last arg. absorbs the rest */
648 struct reflist {
649 struct reflist *next;
651 enum sharp_token_type stringify; /* set if a # operator before arg */
652 enum sharp_token_type raw_before; /* set if a ## operator before arg */
653 enum sharp_token_type raw_after; /* set if a ## operator after arg */
655 char rest_args; /* Nonzero if this arg. absorbs the rest */
656 int nchars; /* Number of literal chars to copy before
657 this arg occurrence. */
658 int argno; /* Number of arg to substitute (origin-0) */
659 } *pattern;
660 union {
661 /* Names of macro args, concatenated in reverse order
662 with comma-space between them.
663 The only use of this is that we warn on redefinition
664 if this differs between the old and new definitions. */
665 U_CHAR *argnames;
666 } args;
669 /* different kinds of things that can appear in the value field
670 of a hash node. Actually, this may be useless now. */
671 union hashval {
672 char *cpval;
673 DEFINITION *defn;
674 KEYDEF *keydef;
678 * special extension string that can be added to the last macro argument to
679 * allow it to absorb the "rest" of the arguments when expanded. Ex:
680 * #define wow(a, b...) process (b, a, b)
681 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
682 * { wow (one, two); } -> { process (two, one, two); }
683 * if this "rest_arg" is used with the concat token '##' and if it is not
684 * supplied then the token attached to with ## will not be outputted. Ex:
685 * #define wow (a, b...) process (b ## , a, ## b)
686 * { wow (1, 2); } -> { process (2, 1, 2); }
687 * { wow (one); } -> { process (one); {
689 static char rest_extension[] = "...";
690 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
692 /* The structure of a node in the hash table. The hash table
693 has entries for all tokens defined by #define directives (type T_MACRO),
694 plus some special tokens like __LINE__ (these each have their own
695 type, and the appropriate code is run when that type of node is seen.
696 It does not contain control words like "#define", which are recognized
697 by a separate piece of code. */
699 /* different flavors of hash nodes --- also used in keyword table */
700 enum node_type {
701 T_DEFINE = 1, /* the `#define' keyword */
702 T_INCLUDE, /* the `#include' keyword */
703 T_INCLUDE_NEXT, /* the `#include_next' keyword */
704 T_IMPORT, /* the `#import' keyword */
705 T_IFDEF, /* the `#ifdef' keyword */
706 T_IFNDEF, /* the `#ifndef' keyword */
707 T_IF, /* the `#if' keyword */
708 T_ELSE, /* `#else' */
709 T_PRAGMA, /* `#pragma' */
710 T_ELIF, /* `#elif' */
711 T_UNDEF, /* `#undef' */
712 T_LINE, /* `#line' */
713 T_ERROR, /* `#error' */
714 T_WARNING, /* `#warning' */
715 T_ENDIF, /* `#endif' */
716 T_SCCS, /* `#sccs', used on system V. */
717 T_IDENT, /* `#ident', used on system V. */
718 T_ASSERT, /* `#assert', taken from system V. */
719 T_UNASSERT, /* `#unassert', taken from system V. */
720 T_SPECLINE, /* special symbol `__LINE__' */
721 T_DATE, /* `__DATE__' */
722 T_FILE, /* `__FILE__' */
723 T_BASE_FILE, /* `__BASE_FILE__' */
724 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
725 T_VERSION, /* `__VERSION__' */
726 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
727 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
728 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
729 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
730 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
731 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
732 T_TIME, /* `__TIME__' */
733 T_CONST, /* Constant value, used by `__STDC__' */
734 T_MACRO, /* macro defined by `#define' */
735 T_DISABLED, /* macro temporarily turned off for rescan */
736 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
737 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
738 T_UNUSED /* Used for something not defined. */
741 struct hashnode {
742 struct hashnode *next; /* double links for easy deletion */
743 struct hashnode *prev;
744 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
745 chain is kept, in case the node is the head
746 of the chain and gets deleted. */
747 enum node_type type; /* type of special token */
748 int length; /* length of token, for quick comparison */
749 U_CHAR *name; /* the actual name */
750 union hashval value; /* pointer to expansion, or whatever */
753 typedef struct hashnode HASHNODE;
755 /* Some definitions for the hash table. The hash function MUST be
756 computed as shown in hashf () below. That is because the rescan
757 loop computes the hash value `on the fly' for most tokens,
758 in order to avoid the overhead of a lot of procedure calls to
759 the hashf () function. Hashf () only exists for the sake of
760 politeness, for use when speed isn't so important. */
762 #define HASHSIZE 1403
763 static HASHNODE *hashtab[HASHSIZE];
764 #define HASHSTEP(old, c) ((old << 2) + c)
765 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
767 /* Symbols to predefine. */
769 #ifdef CPP_PREDEFINES
770 static char *predefs = CPP_PREDEFINES;
771 #else
772 static char *predefs = "";
773 #endif
775 /* We let tm.h override the types used here, to handle trivial differences
776 such as the choice of unsigned int or long unsigned int for size_t.
777 When machines start needing nontrivial differences in the size type,
778 it would be best to do something here to figure out automatically
779 from other information what type to use. */
781 /* The string value for __SIZE_TYPE__. */
783 #ifndef SIZE_TYPE
784 #define SIZE_TYPE "long unsigned int"
785 #endif
787 /* The string value for __PTRDIFF_TYPE__. */
789 #ifndef PTRDIFF_TYPE
790 #define PTRDIFF_TYPE "long int"
791 #endif
793 /* The string value for __WCHAR_TYPE__. */
795 #ifndef WCHAR_TYPE
796 #define WCHAR_TYPE "int"
797 #endif
798 char * wchar_type = WCHAR_TYPE;
799 #undef WCHAR_TYPE
801 /* The string value for __USER_LABEL_PREFIX__ */
803 #ifndef USER_LABEL_PREFIX
804 #define USER_LABEL_PREFIX ""
805 #endif
807 /* The string value for __REGISTER_PREFIX__ */
809 #ifndef REGISTER_PREFIX
810 #define REGISTER_PREFIX ""
811 #endif
813 /* The string value for __IMMEDIATE_PREFIX__ */
815 #ifndef IMMEDIATE_PREFIX
816 #define IMMEDIATE_PREFIX ""
817 #endif
819 /* In the definition of a #assert name, this structure forms
820 a list of the individual values asserted.
821 Each value is itself a list of "tokens".
822 These are strings that are compared by name. */
824 struct tokenlist_list {
825 struct tokenlist_list *next;
826 struct arglist *tokens;
829 struct assertion_hashnode {
830 struct assertion_hashnode *next; /* double links for easy deletion */
831 struct assertion_hashnode *prev;
832 /* also, a back pointer to this node's hash
833 chain is kept, in case the node is the head
834 of the chain and gets deleted. */
835 struct assertion_hashnode **bucket_hdr;
836 int length; /* length of token, for quick comparison */
837 U_CHAR *name; /* the actual name */
838 /* List of token-sequences. */
839 struct tokenlist_list *value;
842 typedef struct assertion_hashnode ASSERTION_HASHNODE;
844 /* Some definitions for the hash table. The hash function MUST be
845 computed as shown in hashf below. That is because the rescan
846 loop computes the hash value `on the fly' for most tokens,
847 in order to avoid the overhead of a lot of procedure calls to
848 the hashf function. hashf only exists for the sake of
849 politeness, for use when speed isn't so important. */
851 #define ASSERTION_HASHSIZE 37
852 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
854 /* Nonzero means inhibit macroexpansion of what seem to be
855 assertion tests, in rescan. For #if. */
856 static int assertions_flag;
858 /* `struct directive' defines one #-directive, including how to handle it. */
860 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
862 struct directive {
863 int length; /* Length of name */
864 int (*func) DO_PROTO; /* Function to handle directive */
865 char *name; /* Name of directive */
866 enum node_type type; /* Code which describes which directive. */
869 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
870 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
872 /* These functions are declared to return int instead of void since they
873 are going to be placed in the table and some old compilers have trouble with
874 pointers to functions returning void. */
876 static int do_assert DO_PROTO;
877 static int do_define DO_PROTO;
878 static int do_elif DO_PROTO;
879 static int do_else DO_PROTO;
880 static int do_endif DO_PROTO;
881 static int do_error DO_PROTO;
882 static int do_ident DO_PROTO;
883 static int do_if DO_PROTO;
884 static int do_include DO_PROTO;
885 static int do_line DO_PROTO;
886 static int do_pragma DO_PROTO;
887 #ifdef SCCS_DIRECTIVE
888 static int do_sccs DO_PROTO;
889 #endif
890 static int do_unassert DO_PROTO;
891 static int do_undef DO_PROTO;
892 static int do_warning DO_PROTO;
893 static int do_xifdef DO_PROTO;
895 /* Here is the actual list of #-directives, most-often-used first. */
897 static struct directive directive_table[] = {
898 { 6, do_define, "define", T_DEFINE},
899 { 2, do_if, "if", T_IF},
900 { 5, do_xifdef, "ifdef", T_IFDEF},
901 { 6, do_xifdef, "ifndef", T_IFNDEF},
902 { 5, do_endif, "endif", T_ENDIF},
903 { 4, do_else, "else", T_ELSE},
904 { 4, do_elif, "elif", T_ELIF},
905 { 4, do_line, "line", T_LINE},
906 { 7, do_include, "include", T_INCLUDE},
907 { 12, do_include, "include_next", T_INCLUDE_NEXT},
908 { 6, do_include, "import", T_IMPORT},
909 { 5, do_undef, "undef", T_UNDEF},
910 { 5, do_error, "error", T_ERROR},
911 { 7, do_warning, "warning", T_WARNING},
912 #ifdef SCCS_DIRECTIVE
913 { 4, do_sccs, "sccs", T_SCCS},
914 #endif
915 { 6, do_pragma, "pragma", T_PRAGMA},
916 { 5, do_ident, "ident", T_IDENT},
917 { 6, do_assert, "assert", T_ASSERT},
918 { 8, do_unassert, "unassert", T_UNASSERT},
919 { -1, 0, "", T_UNUSED},
922 /* When a directive handler is called,
923 this points to the # (or the : of the %:) that started the directive. */
924 U_CHAR *directive_start;
926 /* table to tell if char can be part of a C identifier. */
927 U_CHAR is_idchar[256];
928 /* table to tell if char can be first char of a c identifier. */
929 U_CHAR is_idstart[256];
930 /* table to tell if c is horizontal space. */
931 static U_CHAR is_hor_space[256];
932 /* table to tell if c is horizontal or vertical space. */
933 U_CHAR is_space[256];
934 /* names of some characters */
935 static char *char_name[256];
937 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
938 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
940 static int errors = 0; /* Error counter for exit code */
942 /* Name of output file, for error messages. */
943 static char *out_fname;
946 /* Stack of conditionals currently in progress
947 (including both successful and failing conditionals). */
949 struct if_stack {
950 struct if_stack *next; /* for chaining to the next stack frame */
951 char *fname; /* copied from input when frame is made */
952 int lineno; /* similarly */
953 int if_succeeded; /* true if a leg of this if-group
954 has been passed through rescan */
955 U_CHAR *control_macro; /* For #ifndef at start of file,
956 this is the macro name tested. */
957 enum node_type type; /* type of last directive seen in this group */
959 typedef struct if_stack IF_STACK_FRAME;
960 static IF_STACK_FRAME *if_stack = NULL;
962 /* Buffer of -M output. */
963 static char *deps_buffer;
965 /* Number of bytes allocated in above. */
966 static int deps_allocated_size;
968 /* Number of bytes used. */
969 static int deps_size;
971 /* Number of bytes since the last newline. */
972 static int deps_column;
974 /* Nonzero means -I- has been seen,
975 so don't look for #include "foo" the source-file directory. */
976 static int ignore_srcdir;
978 static int safe_read PROTO((int, char *, int));
979 static void safe_write PROTO((int, char *, int));
981 int main PROTO((int, char **));
983 static void path_include PROTO((char *));
985 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
987 static void trigraph_pcp PROTO((FILE_BUF *));
989 static void newline_fix PROTO((U_CHAR *));
990 static void name_newline_fix PROTO((U_CHAR *));
992 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
994 static void rescan PROTO((FILE_BUF *, int));
996 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
998 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1000 static struct tm *timestamp PROTO((void));
1001 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1003 static int is_system_include PROTO((char *));
1004 static char *base_name PROTO((char *));
1005 static int absolute_filename PROTO((char *));
1006 static size_t simplify_filename PROTO((char *));
1008 static char *read_filename_string PROTO((int, FILE *));
1009 static struct file_name_map *read_name_map PROTO((char *));
1010 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
1011 static char *remap_include_file PROTO((char *, struct file_name_list *));
1012 static int lookup_ino_include PROTO((struct include_file *));
1014 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
1015 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
1017 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
1018 static int check_preconditions PROTO((char *));
1019 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1020 static void pcstring_used PROTO((HASHNODE *));
1021 static void write_output PROTO((void));
1022 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1024 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1026 static int check_macro_name PROTO((U_CHAR *, char *));
1027 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1028 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1030 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1032 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1033 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1035 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1036 static void free_token_list PROTO((struct arglist *));
1038 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1039 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1040 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1042 static void do_once PROTO((void));
1044 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1045 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1046 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1047 static void validate_else PROTO((U_CHAR *, U_CHAR *));
1049 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1050 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1051 static char *quote_string PROTO((char *, char *));
1052 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1054 /* Last arg to output_line_directive. */
1055 enum file_change_code {same_file, enter_file, leave_file};
1056 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1058 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1060 struct argdata;
1061 static char *macarg PROTO((struct argdata *, int));
1063 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
1065 static int discard_comments PROTO((U_CHAR *, int, int));
1067 static int change_newlines PROTO((U_CHAR *, int));
1069 char *my_strerror PROTO((int));
1070 void error PRINTF_PROTO_1((char *, ...));
1071 static void verror PROTO((char *, va_list));
1072 static void error_from_errno PROTO((char *));
1073 void warning PRINTF_PROTO_1((char *, ...));
1074 static void vwarning PROTO((char *, va_list));
1075 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1076 static void verror_with_line PROTO((int, char *, va_list));
1077 static void vwarning_with_line PROTO((int, char *, va_list));
1078 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1079 void pedwarn PRINTF_PROTO_1((char *, ...));
1080 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1081 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1083 static void print_containing_files PROTO((void));
1085 static int line_for_error PROTO((int));
1086 static int grow_outbuf PROTO((FILE_BUF *, int));
1088 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1089 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1090 static void delete_macro PROTO((HASHNODE *));
1091 static int hashf PROTO((U_CHAR *, int, int));
1093 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1094 static void dump_all_macros PROTO((void));
1095 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1096 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1098 static void initialize_char_syntax PROTO((void));
1099 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1101 static void make_definition PROTO((char *, FILE_BUF *));
1102 static void make_undef PROTO((char *, FILE_BUF *));
1104 static void make_assertion PROTO((char *, char *));
1106 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1107 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1109 static int quote_string_for_make PROTO((char *, char *));
1110 static void deps_output PROTO((char *, int));
1112 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1113 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1114 static void perror_with_name PROTO((char *));
1115 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1116 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1118 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1119 GENERIC_PTR xmalloc PROTO((size_t));
1120 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1121 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1122 static char *savestring PROTO((char *));
1124 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1125 retrying if necessary. If MAX_READ_LEN is defined, read at most
1126 that bytes at a time. Return a negative value if an error occurs,
1127 otherwise return the actual number of bytes read,
1128 which must be LEN unless end-of-file was reached. */
1130 static int
1131 safe_read (desc, ptr, len)
1132 int desc;
1133 char *ptr;
1134 int len;
1136 int left, rcount, nchars;
1138 left = len;
1139 while (left > 0) {
1140 rcount = left;
1141 #ifdef MAX_READ_LEN
1142 if (rcount > MAX_READ_LEN)
1143 rcount = MAX_READ_LEN;
1144 #endif
1145 nchars = read (desc, ptr, rcount);
1146 if (nchars < 0)
1148 #ifdef EINTR
1149 if (errno == EINTR)
1150 continue;
1151 #endif
1152 return nchars;
1154 if (nchars == 0)
1155 break;
1156 ptr += nchars;
1157 left -= nchars;
1159 return len - left;
1162 /* Write LEN bytes at PTR to descriptor DESC,
1163 retrying if necessary, and treating any real error as fatal.
1164 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1166 static void
1167 safe_write (desc, ptr, len)
1168 int desc;
1169 char *ptr;
1170 int len;
1172 int wcount, written;
1174 while (len > 0) {
1175 wcount = len;
1176 #ifdef MAX_WRITE_LEN
1177 if (wcount > MAX_WRITE_LEN)
1178 wcount = MAX_WRITE_LEN;
1179 #endif
1180 written = write (desc, ptr, wcount);
1181 if (written < 0)
1183 #ifdef EINTR
1184 if (errno == EINTR)
1185 continue;
1186 #endif
1187 pfatal_with_name (out_fname);
1189 ptr += written;
1190 len -= written;
1195 main (argc, argv)
1196 int argc;
1197 char **argv;
1199 struct stat st;
1200 char *in_fname;
1201 char *cp;
1202 int f, i;
1203 FILE_BUF *fp;
1204 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1205 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1206 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1207 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1208 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1210 /* Record the option used with each element of pend_assertions.
1211 This is preparation for supporting more than one option for making
1212 an assertion. */
1213 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1214 int inhibit_predefs = 0;
1215 int no_standard_includes = 0;
1216 int no_standard_cplusplus_includes = 0;
1217 int missing_newline = 0;
1219 /* Non-0 means don't output the preprocessed program. */
1220 int inhibit_output = 0;
1221 /* Non-0 means -v, so print the full set of include dirs. */
1222 int verbose = 0;
1224 /* File name which deps are being written to.
1225 This is 0 if deps are being written to stdout. */
1226 char *deps_file = 0;
1227 /* Fopen file mode to open deps_file with. */
1228 char *deps_mode = "a";
1229 /* Stream on which to print the dependency information. */
1230 FILE *deps_stream = 0;
1231 /* Target-name to write with the dependency information. */
1232 char *deps_target = 0;
1234 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1235 /* Get rid of any avoidable limit on stack size. */
1237 struct rlimit rlim;
1239 /* Set the stack limit huge so that alloca (particularly stringtab
1240 in dbxread.c) does not fail. */
1241 getrlimit (RLIMIT_STACK, &rlim);
1242 rlim.rlim_cur = rlim.rlim_max;
1243 setrlimit (RLIMIT_STACK, &rlim);
1245 #endif
1247 #ifdef SIGPIPE
1248 signal (SIGPIPE, pipe_closed);
1249 #endif
1251 progname = base_name (argv[0]);
1253 #ifdef VMS
1255 /* Remove extension from PROGNAME. */
1256 char *p;
1257 char *s = progname = savestring (progname);
1259 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1260 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1261 && (p[1] == 'e' || p[1] == 'E')
1262 && (p[2] == 'x' || p[2] == 'X')
1263 && (p[3] == 'e' || p[3] == 'E')
1264 && !p[4])
1265 *p = '\0';
1267 #endif
1269 in_fname = NULL;
1270 out_fname = NULL;
1272 /* Initialize is_idchar. */
1273 initialize_char_syntax ();
1275 no_line_directives = 0;
1276 no_trigraphs = 1;
1277 dump_macros = dump_none;
1278 no_output = 0;
1279 cplusplus = 0;
1280 cplusplus_comments = 1;
1282 bzero ((char *) pend_files, argc * sizeof (char *));
1283 bzero ((char *) pend_defs, argc * sizeof (char *));
1284 bzero ((char *) pend_undefs, argc * sizeof (char *));
1285 bzero ((char *) pend_assertions, argc * sizeof (char *));
1286 bzero ((char *) pend_includes, argc * sizeof (char *));
1288 /* Process switches and find input file name. */
1290 for (i = 1; i < argc; i++) {
1291 if (argv[i][0] != '-') {
1292 if (out_fname != NULL)
1293 fatal ("Usage: %s [switches] input output", argv[0]);
1294 else if (in_fname != NULL)
1295 out_fname = argv[i];
1296 else
1297 in_fname = argv[i];
1298 } else {
1299 switch (argv[i][1]) {
1301 case 'i':
1302 if (!strcmp (argv[i], "-include")) {
1303 if (i + 1 == argc)
1304 fatal ("Filename missing after `-include' option");
1305 else
1306 simplify_filename (pend_includes[i] = argv[++i]);
1308 if (!strcmp (argv[i], "-imacros")) {
1309 if (i + 1 == argc)
1310 fatal ("Filename missing after `-imacros' option");
1311 else
1312 simplify_filename (pend_files[i] = argv[++i]);
1314 if (!strcmp (argv[i], "-iprefix")) {
1315 if (i + 1 == argc)
1316 fatal ("Filename missing after `-iprefix' option");
1317 else
1318 include_prefix = argv[++i];
1320 if (!strcmp (argv[i], "-ifoutput")) {
1321 output_conditionals = 1;
1323 if (!strcmp (argv[i], "-isystem")) {
1324 struct file_name_list *dirtmp;
1326 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1327 "", argv[++i])))
1328 break;
1329 dirtmp->c_system_include_path = 1;
1331 if (before_system == 0)
1332 before_system = dirtmp;
1333 else
1334 last_before_system->next = dirtmp;
1335 last_before_system = dirtmp; /* Tail follows the last one */
1337 /* Add directory to end of path for includes,
1338 with the default prefix at the front of its name. */
1339 if (!strcmp (argv[i], "-iwithprefix")) {
1340 struct file_name_list *dirtmp;
1341 char *prefix;
1343 if (include_prefix != 0)
1344 prefix = include_prefix;
1345 else {
1346 prefix = savestring (GCC_INCLUDE_DIR);
1347 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1348 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1349 prefix[strlen (prefix) - 7] = 0;
1352 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1353 prefix, argv[++i])))
1354 break;
1356 if (after_include == 0)
1357 after_include = dirtmp;
1358 else
1359 last_after_include->next = dirtmp;
1360 last_after_include = dirtmp; /* Tail follows the last one */
1362 /* Add directory to main path for includes,
1363 with the default prefix at the front of its name. */
1364 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1365 struct file_name_list *dirtmp;
1366 char *prefix;
1368 if (include_prefix != 0)
1369 prefix = include_prefix;
1370 else {
1371 prefix = savestring (GCC_INCLUDE_DIR);
1372 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1373 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1374 prefix[strlen (prefix) - 7] = 0;
1377 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1378 append_include_chain (dirtmp, dirtmp);
1380 /* Add directory to end of path for includes. */
1381 if (!strcmp (argv[i], "-idirafter")) {
1382 struct file_name_list *dirtmp;
1384 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1385 "", argv[++i])))
1386 break;
1388 if (after_include == 0)
1389 after_include = dirtmp;
1390 else
1391 last_after_include->next = dirtmp;
1392 last_after_include = dirtmp; /* Tail follows the last one */
1394 break;
1396 case 'o':
1397 if (out_fname != NULL)
1398 fatal ("Output filename specified twice");
1399 if (i + 1 == argc)
1400 fatal ("Filename missing after -o option");
1401 out_fname = argv[++i];
1402 if (!strcmp (out_fname, "-"))
1403 out_fname = "";
1404 break;
1406 case 'p':
1407 if (!strcmp (argv[i], "-pedantic"))
1408 pedantic = 1;
1409 else if (!strcmp (argv[i], "-pedantic-errors")) {
1410 pedantic = 1;
1411 pedantic_errors = 1;
1412 } else if (!strcmp (argv[i], "-pcp")) {
1413 char *pcp_fname;
1414 if (i + 1 == argc)
1415 fatal ("Filename missing after -pcp option");
1416 pcp_fname = argv[++i];
1417 pcp_outfile
1418 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1419 ? fopen (pcp_fname, "w")
1420 : stdout);
1421 if (pcp_outfile == 0)
1422 pfatal_with_name (pcp_fname);
1423 no_precomp = 1;
1425 break;
1427 case 't':
1428 if (!strcmp (argv[i], "-traditional")) {
1429 traditional = 1;
1430 cplusplus_comments = 0;
1431 } else if (!strcmp (argv[i], "-trigraphs")) {
1432 no_trigraphs = 0;
1434 break;
1436 case 'l':
1437 if (! strcmp (argv[i], "-lang-c"))
1438 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1439 if (! strcmp (argv[i], "-lang-c89"))
1440 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1441 if (! strcmp (argv[i], "-lang-c++"))
1442 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1443 if (! strcmp (argv[i], "-lang-objc"))
1444 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1445 if (! strcmp (argv[i], "-lang-objc++"))
1446 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1447 if (! strcmp (argv[i], "-lang-asm"))
1448 lang_asm = 1;
1449 if (! strcmp (argv[i], "-lint"))
1450 for_lint = 1;
1451 break;
1453 case '+':
1454 cplusplus = 1, cplusplus_comments = 1;
1455 break;
1457 case 'w':
1458 inhibit_warnings = 1;
1459 break;
1461 case 'W':
1462 if (!strcmp (argv[i], "-Wtrigraphs"))
1463 warn_trigraphs = 1;
1464 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1465 warn_trigraphs = 0;
1466 else if (!strcmp (argv[i], "-Wcomment"))
1467 warn_comments = 1;
1468 else if (!strcmp (argv[i], "-Wno-comment"))
1469 warn_comments = 0;
1470 else if (!strcmp (argv[i], "-Wcomments"))
1471 warn_comments = 1;
1472 else if (!strcmp (argv[i], "-Wno-comments"))
1473 warn_comments = 0;
1474 else if (!strcmp (argv[i], "-Wtraditional"))
1475 warn_stringify = 1;
1476 else if (!strcmp (argv[i], "-Wno-traditional"))
1477 warn_stringify = 0;
1478 else if (!strcmp (argv[i], "-Wundef"))
1479 warn_undef = 1;
1480 else if (!strcmp (argv[i], "-Wno-undef"))
1481 warn_undef = 0;
1482 else if (!strcmp (argv[i], "-Wimport"))
1483 warn_import = 1;
1484 else if (!strcmp (argv[i], "-Wno-import"))
1485 warn_import = 0;
1486 else if (!strcmp (argv[i], "-Werror"))
1487 warnings_are_errors = 1;
1488 else if (!strcmp (argv[i], "-Wno-error"))
1489 warnings_are_errors = 0;
1490 else if (!strcmp (argv[i], "-Wall"))
1492 warn_trigraphs = 1;
1493 warn_comments = 1;
1495 break;
1497 case 'M':
1498 /* The style of the choices here is a bit mixed.
1499 The chosen scheme is a hybrid of keeping all options in one string
1500 and specifying each option in a separate argument:
1501 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1502 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1503 -M[M][G][D file]. This is awkward to handle in specs, and is not
1504 as extensible. */
1505 /* ??? -MG must be specified in addition to one of -M or -MM.
1506 This can be relaxed in the future without breaking anything.
1507 The converse isn't true. */
1509 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1510 if (!strcmp (argv[i], "-MG"))
1512 print_deps_missing_files = 1;
1513 break;
1515 if (!strcmp (argv[i], "-M"))
1516 print_deps = 2;
1517 else if (!strcmp (argv[i], "-MM"))
1518 print_deps = 1;
1519 else if (!strcmp (argv[i], "-MD"))
1520 print_deps = 2;
1521 else if (!strcmp (argv[i], "-MMD"))
1522 print_deps = 1;
1523 /* For -MD and -MMD options, write deps on file named by next arg. */
1524 if (!strcmp (argv[i], "-MD")
1525 || !strcmp (argv[i], "-MMD")) {
1526 if (i + 1 == argc)
1527 fatal ("Filename missing after %s option", argv[i]);
1528 i++;
1529 deps_file = argv[i];
1530 deps_mode = "w";
1531 } else {
1532 /* For -M and -MM, write deps on standard output
1533 and suppress the usual output. */
1534 deps_stream = stdout;
1535 inhibit_output = 1;
1537 break;
1539 case 'd':
1541 char *p = argv[i] + 2;
1542 char c;
1543 while ((c = *p++)) {
1544 /* Arg to -d specifies what parts of macros to dump */
1545 switch (c) {
1546 case 'M':
1547 dump_macros = dump_only;
1548 no_output = 1;
1549 break;
1550 case 'N':
1551 dump_macros = dump_names;
1552 break;
1553 case 'D':
1554 dump_macros = dump_definitions;
1555 break;
1556 case 'I':
1557 dump_includes = 1;
1558 break;
1562 break;
1564 case 'g':
1565 if (argv[i][2] == '3')
1566 debug_output = 1;
1567 break;
1569 case 'v':
1570 fprintf (stderr, "GNU CPP version %s", version_string);
1571 #ifdef TARGET_VERSION
1572 TARGET_VERSION;
1573 #endif
1574 fprintf (stderr, "\n");
1575 verbose = 1;
1576 break;
1578 case 'H':
1579 print_include_names = 1;
1580 break;
1582 case 'D':
1583 if (argv[i][2] != 0)
1584 pend_defs[i] = argv[i] + 2;
1585 else if (i + 1 == argc)
1586 fatal ("Macro name missing after -D option");
1587 else
1588 i++, pend_defs[i] = argv[i];
1589 break;
1591 case 'A':
1593 char *p;
1595 if (argv[i][2] != 0)
1596 p = argv[i] + 2;
1597 else if (i + 1 == argc)
1598 fatal ("Assertion missing after -A option");
1599 else
1600 p = argv[++i];
1602 if (!strcmp (p, "-")) {
1603 /* -A- eliminates all predefined macros and assertions.
1604 Let's include also any that were specified earlier
1605 on the command line. That way we can get rid of any
1606 that were passed automatically in from GCC. */
1607 int j;
1608 inhibit_predefs = 1;
1609 for (j = 0; j < i; j++)
1610 pend_defs[j] = pend_assertions[j] = 0;
1611 } else {
1612 pend_assertions[i] = p;
1613 pend_assertion_options[i] = "-A";
1616 break;
1618 case 'U': /* JF #undef something */
1619 if (argv[i][2] != 0)
1620 pend_undefs[i] = argv[i] + 2;
1621 else if (i + 1 == argc)
1622 fatal ("Macro name missing after -U option");
1623 else
1624 pend_undefs[i] = argv[i+1], i++;
1625 break;
1627 case 'C':
1628 put_out_comments = 1;
1629 break;
1631 case 'E': /* -E comes from cc -E; ignore it. */
1632 break;
1634 case 'P':
1635 no_line_directives = 1;
1636 break;
1638 case '$': /* Don't include $ in identifiers. */
1639 is_idchar['$'] = is_idstart['$'] = 0;
1640 break;
1642 case 'I': /* Add directory to path for includes. */
1644 struct file_name_list *dirtmp;
1646 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1647 ignore_srcdir = 1;
1648 /* Don't use any preceding -I directories for #include <...>. */
1649 first_bracket_include = 0;
1651 else {
1652 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1653 argv[i][2] ? argv[i] + 2 : argv[++i]);
1654 append_include_chain (dirtmp, dirtmp);
1657 break;
1659 case 'n':
1660 if (!strcmp (argv[i], "-nostdinc"))
1661 /* -nostdinc causes no default include directories.
1662 You must specify all include-file directories with -I. */
1663 no_standard_includes = 1;
1664 else if (!strcmp (argv[i], "-nostdinc++"))
1665 /* -nostdinc++ causes no default C++-specific include directories. */
1666 no_standard_cplusplus_includes = 1;
1667 else if (!strcmp (argv[i], "-noprecomp"))
1668 no_precomp = 1;
1669 break;
1671 case 'r':
1672 if (!strcmp (argv[i], "-remap"))
1673 remap = 1;
1674 break;
1676 case 'u':
1677 /* Sun compiler passes undocumented switch "-undef".
1678 Let's assume it means to inhibit the predefined symbols. */
1679 inhibit_predefs = 1;
1680 break;
1682 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1683 if (in_fname == NULL) {
1684 in_fname = "";
1685 break;
1686 } else if (out_fname == NULL) {
1687 out_fname = "";
1688 break;
1689 } /* else fall through into error */
1691 default:
1692 fatal ("Invalid option `%s'", argv[i]);
1697 /* Add dirs from CPATH after dirs from -I. */
1698 /* There seems to be confusion about what CPATH should do,
1699 so for the moment it is not documented. */
1700 /* Some people say that CPATH should replace the standard include dirs,
1701 but that seems pointless: it comes before them, so it overrides them
1702 anyway. */
1703 cp = getenv ("CPATH");
1704 if (cp && ! no_standard_includes)
1705 path_include (cp);
1707 /* Initialize output buffer */
1709 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1710 outbuf.bufp = outbuf.buf;
1711 outbuf.length = OUTBUF_SIZE;
1713 /* Do partial setup of input buffer for the sake of generating
1714 early #line directives (when -g is in effect). */
1716 fp = &instack[++indepth];
1717 if (in_fname == NULL)
1718 in_fname = "";
1719 fp->nominal_fname = fp->fname = in_fname;
1720 fp->lineno = 0;
1722 /* In C++, wchar_t is a distinct basic type, and we can expect
1723 __wchar_t to be defined by cc1plus. */
1724 if (cplusplus)
1725 wchar_type = "__wchar_t";
1727 /* Install __LINE__, etc. Must follow initialize_char_syntax
1728 and option processing. */
1729 initialize_builtins (fp, &outbuf);
1731 /* Do standard #defines and assertions
1732 that identify system and machine type. */
1734 if (!inhibit_predefs) {
1735 char *p = (char *) alloca (strlen (predefs) + 1);
1736 strcpy (p, predefs);
1737 while (*p) {
1738 char *q;
1739 while (*p == ' ' || *p == '\t')
1740 p++;
1741 /* Handle -D options. */
1742 if (p[0] == '-' && p[1] == 'D') {
1743 q = &p[2];
1744 while (*p && *p != ' ' && *p != '\t')
1745 p++;
1746 if (*p != 0)
1747 *p++= 0;
1748 if (debug_output)
1749 output_line_directive (fp, &outbuf, 0, same_file);
1750 make_definition (q, &outbuf);
1751 while (*p == ' ' || *p == '\t')
1752 p++;
1753 } else if (p[0] == '-' && p[1] == 'A') {
1754 /* Handle -A options (assertions). */
1755 char *assertion;
1756 char *past_name;
1757 char *value;
1758 char *past_value;
1759 char *termination;
1760 int save_char;
1762 assertion = &p[2];
1763 past_name = assertion;
1764 /* Locate end of name. */
1765 while (*past_name && *past_name != ' '
1766 && *past_name != '\t' && *past_name != '(')
1767 past_name++;
1768 /* Locate `(' at start of value. */
1769 value = past_name;
1770 while (*value && (*value == ' ' || *value == '\t'))
1771 value++;
1772 if (*value++ != '(')
1773 abort ();
1774 while (*value && (*value == ' ' || *value == '\t'))
1775 value++;
1776 past_value = value;
1777 /* Locate end of value. */
1778 while (*past_value && *past_value != ' '
1779 && *past_value != '\t' && *past_value != ')')
1780 past_value++;
1781 termination = past_value;
1782 while (*termination && (*termination == ' ' || *termination == '\t'))
1783 termination++;
1784 if (*termination++ != ')')
1785 abort ();
1786 if (*termination && *termination != ' ' && *termination != '\t')
1787 abort ();
1788 /* Temporarily null-terminate the value. */
1789 save_char = *termination;
1790 *termination = '\0';
1791 /* Install the assertion. */
1792 make_assertion ("-A", assertion);
1793 *termination = (char) save_char;
1794 p = termination;
1795 while (*p == ' ' || *p == '\t')
1796 p++;
1797 } else {
1798 abort ();
1803 /* Now handle the command line options. */
1805 /* Do -U's, -D's and -A's in the order they were seen. */
1806 for (i = 1; i < argc; i++) {
1807 if (pend_undefs[i]) {
1808 if (debug_output)
1809 output_line_directive (fp, &outbuf, 0, same_file);
1810 make_undef (pend_undefs[i], &outbuf);
1812 if (pend_defs[i]) {
1813 if (debug_output)
1814 output_line_directive (fp, &outbuf, 0, same_file);
1815 make_definition (pend_defs[i], &outbuf);
1817 if (pend_assertions[i])
1818 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1821 done_initializing = 1;
1823 { /* Read the appropriate environment variable and if it exists
1824 replace include_defaults with the listed path. */
1825 char *epath = 0;
1826 switch ((objc << 1) + cplusplus)
1828 case 0:
1829 epath = getenv ("C_INCLUDE_PATH");
1830 break;
1831 case 1:
1832 epath = getenv ("CPLUS_INCLUDE_PATH");
1833 break;
1834 case 2:
1835 epath = getenv ("OBJC_INCLUDE_PATH");
1836 break;
1837 case 3:
1838 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1839 break;
1841 /* If the environment var for this language is set,
1842 add to the default list of include directories. */
1843 if (epath) {
1844 int num_dirs;
1845 char *startp, *endp;
1847 for (num_dirs = 1, startp = epath; *startp; startp++)
1848 if (*startp == PATH_SEPARATOR)
1849 num_dirs++;
1850 include_defaults
1851 = (struct default_include *) xmalloc ((num_dirs
1852 * sizeof (struct default_include))
1853 + sizeof (include_defaults_array));
1854 startp = endp = epath;
1855 num_dirs = 0;
1856 while (1) {
1857 char c = *endp++;
1858 if (c == PATH_SEPARATOR || !c) {
1859 endp[-1] = 0;
1860 include_defaults[num_dirs].fname
1861 = startp == endp ? "." : savestring (startp);
1862 endp[-1] = c;
1863 include_defaults[num_dirs].component = 0;
1864 include_defaults[num_dirs].cplusplus = cplusplus;
1865 include_defaults[num_dirs].cxx_aware = 1;
1866 num_dirs++;
1867 if (!c)
1868 break;
1869 startp = endp;
1872 /* Put the usual defaults back in at the end. */
1873 bcopy ((char *) include_defaults_array,
1874 (char *) &include_defaults[num_dirs],
1875 sizeof (include_defaults_array));
1879 append_include_chain (before_system, last_before_system);
1880 first_system_include = before_system;
1882 /* Unless -fnostdinc,
1883 tack on the standard include file dirs to the specified list */
1884 if (!no_standard_includes) {
1885 struct default_include *p = include_defaults;
1886 char *specd_prefix = include_prefix;
1887 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1888 int default_len = 0;
1889 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1890 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1891 default_len = strlen (default_prefix) - 7;
1892 default_prefix[default_len] = 0;
1894 /* Search "translated" versions of GNU directories.
1895 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1896 if (specd_prefix != 0 && default_len != 0)
1897 for (p = include_defaults; p->fname; p++) {
1898 /* Some standard dirs are only for C++. */
1899 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1900 /* Does this dir start with the prefix? */
1901 if (!strncmp (p->fname, default_prefix, default_len)) {
1902 /* Yes; change prefix and add to search list. */
1903 struct file_name_list *new
1904 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1905 p->fname + default_len);
1906 if (new) {
1907 new->c_system_include_path = !p->cxx_aware;
1908 append_include_chain (new, new);
1909 if (first_system_include == 0)
1910 first_system_include = new;
1915 /* Search ordinary names for GNU include directories. */
1916 for (p = include_defaults; p->fname; p++) {
1917 /* Some standard dirs are only for C++. */
1918 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1919 struct file_name_list *new
1920 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1921 if (new) {
1922 new->c_system_include_path = !p->cxx_aware;
1923 append_include_chain (new, new);
1924 if (first_system_include == 0)
1925 first_system_include = new;
1931 /* Tack the after_include chain at the end of the include chain. */
1932 append_include_chain (after_include, last_after_include);
1933 if (first_system_include == 0)
1934 first_system_include = after_include;
1936 /* With -v, print the list of dirs to search. */
1937 if (verbose) {
1938 struct file_name_list *p;
1939 fprintf (stderr, "#include \"...\" search starts here:\n");
1940 for (p = include; p; p = p->next) {
1941 if (p == first_bracket_include)
1942 fprintf (stderr, "#include <...> search starts here:\n");
1943 if (!p->fname[0])
1944 fprintf (stderr, " .\n");
1945 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1946 fprintf (stderr, " %s\n", p->fname);
1947 else
1948 /* Omit trailing '/'. */
1949 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1951 fprintf (stderr, "End of search list.\n");
1954 /* -MG doesn't select the form of output and must be specified with one of
1955 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1956 inhibit compilation. */
1957 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1958 fatal ("-MG must be specified with one of -M or -MM");
1960 /* Either of two environment variables can specify output of deps.
1961 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1962 where OUTPUT_FILE is the file to write deps info to
1963 and DEPS_TARGET is the target to mention in the deps. */
1965 if (print_deps == 0
1966 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1967 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1968 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1969 char *s;
1970 char *output_file;
1972 if (spec == 0) {
1973 spec = getenv ("SUNPRO_DEPENDENCIES");
1974 print_deps = 2;
1976 else
1977 print_deps = 1;
1979 s = spec;
1980 /* Find the space before the DEPS_TARGET, if there is one. */
1981 /* This should use index. (mrs) */
1982 while (*s != 0 && *s != ' ') s++;
1983 if (*s != 0) {
1984 deps_target = s + 1;
1985 output_file = xmalloc (s - spec + 1);
1986 bcopy (spec, output_file, s - spec);
1987 output_file[s - spec] = 0;
1989 else {
1990 deps_target = 0;
1991 output_file = spec;
1994 deps_file = output_file;
1995 deps_mode = "a";
1998 /* For -M, print the expected object file name
1999 as the target of this Make-rule. */
2000 if (print_deps) {
2001 deps_allocated_size = 200;
2002 deps_buffer = xmalloc (deps_allocated_size);
2003 deps_buffer[0] = 0;
2004 deps_size = 0;
2005 deps_column = 0;
2007 if (deps_target) {
2008 deps_output (deps_target, ':');
2009 } else if (*in_fname == 0) {
2010 deps_output ("-", ':');
2011 } else {
2012 char *p, *q;
2013 int len;
2015 q = base_name (in_fname);
2017 /* Copy remainder to mungable area. */
2018 p = (char *) alloca (strlen(q) + 8);
2019 strcpy (p, q);
2021 /* Output P, but remove known suffixes. */
2022 len = strlen (p);
2023 q = p + len;
2024 if (len >= 2
2025 && p[len - 2] == '.'
2026 && index("cCsSm", p[len - 1]))
2027 q = p + (len - 2);
2028 else if (len >= 3
2029 && p[len - 3] == '.'
2030 && p[len - 2] == 'c'
2031 && p[len - 1] == 'c')
2032 q = p + (len - 3);
2033 else if (len >= 4
2034 && p[len - 4] == '.'
2035 && p[len - 3] == 'c'
2036 && p[len - 2] == 'x'
2037 && p[len - 1] == 'x')
2038 q = p + (len - 4);
2039 else if (len >= 4
2040 && p[len - 4] == '.'
2041 && p[len - 3] == 'c'
2042 && p[len - 2] == 'p'
2043 && p[len - 1] == 'p')
2044 q = p + (len - 4);
2046 /* Supply our own suffix. */
2047 strcpy (q, OBJECT_SUFFIX);
2049 deps_output (p, ':');
2050 deps_output (in_fname, ' ');
2054 /* Scan the -imacros files before the main input.
2055 Much like #including them, but with no_output set
2056 so that only their macro definitions matter. */
2058 no_output++; no_record_file++;
2059 for (i = 1; i < argc; i++)
2060 if (pend_files[i]) {
2061 struct include_file *inc;
2062 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2063 if (fd < 0) {
2064 perror_with_name (pend_files[i]);
2065 return FATAL_EXIT_CODE;
2067 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2069 no_output--; no_record_file--;
2071 /* Copy the entire contents of the main input file into
2072 the stacked input buffer previously allocated for it. */
2074 /* JF check for stdin */
2075 if (in_fname == NULL || *in_fname == 0) {
2076 in_fname = "";
2077 f = 0;
2078 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2079 goto perror;
2081 if (fstat (f, &st) != 0)
2082 pfatal_with_name (in_fname);
2083 fp->nominal_fname = fp->fname = in_fname;
2084 fp->lineno = 1;
2085 fp->system_header_p = 0;
2086 /* JF all this is mine about reading pipes and ttys */
2087 if (! S_ISREG (st.st_mode)) {
2088 /* Read input from a file that is not a normal disk file.
2089 We cannot preallocate a buffer with the correct size,
2090 so we must read in the file a piece at the time and make it bigger. */
2091 int size;
2092 int bsize;
2093 int cnt;
2095 if (S_ISDIR (st.st_mode))
2096 fatal ("Input file `%s' is a directory", in_fname);
2098 bsize = 2000;
2099 size = 0;
2100 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2101 for (;;) {
2102 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2103 if (cnt < 0) goto perror; /* error! */
2104 size += cnt;
2105 if (size != bsize) break; /* End of file */
2106 bsize *= 2;
2107 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2109 fp->length = size;
2110 } else {
2111 /* Read a file whose size we can determine in advance.
2112 For the sake of VMS, st.st_size is just an upper bound. */
2113 size_t s = (size_t) st.st_size;
2114 if (s != st.st_size || s + 2 < s)
2115 memory_full ();
2116 fp->buf = (U_CHAR *) xmalloc (s + 2);
2117 fp->length = safe_read (f, (char *) fp->buf, s);
2118 if (fp->length < 0) goto perror;
2120 fp->bufp = fp->buf;
2121 fp->if_stack = if_stack;
2123 /* Make sure data ends with a newline. And put a null after it. */
2125 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2126 /* Backslash-newline at end is not good enough. */
2127 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2128 fp->buf[fp->length++] = '\n';
2129 missing_newline = 1;
2131 fp->buf[fp->length] = '\0';
2133 /* Unless inhibited, convert trigraphs in the input. */
2135 if (!no_trigraphs)
2136 trigraph_pcp (fp);
2138 /* Now that we know the input file is valid, open the output. */
2140 if (!out_fname || !strcmp (out_fname, ""))
2141 out_fname = "stdout";
2142 else if (! freopen (out_fname, "w", stdout))
2143 pfatal_with_name (out_fname);
2145 output_line_directive (fp, &outbuf, 0, same_file);
2147 /* Scan the -include files before the main input. */
2149 no_record_file++;
2150 for (i = 1; i < argc; i++)
2151 if (pend_includes[i]) {
2152 struct include_file *inc;
2153 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2154 if (fd < 0) {
2155 perror_with_name (pend_includes[i]);
2156 return FATAL_EXIT_CODE;
2158 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2160 no_record_file--;
2162 /* Scan the input, processing macros and directives. */
2164 rescan (&outbuf, 0);
2166 if (missing_newline)
2167 fp->lineno--;
2169 if (pedantic && missing_newline)
2170 pedwarn ("file does not end in newline");
2172 /* Now we have processed the entire input
2173 Write whichever kind of output has been requested. */
2175 if (dump_macros == dump_only)
2176 dump_all_macros ();
2177 else if (! inhibit_output) {
2178 write_output ();
2181 if (print_deps) {
2182 /* Don't actually write the deps file if compilation has failed. */
2183 if (errors == 0) {
2184 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2185 pfatal_with_name (deps_file);
2186 fputs (deps_buffer, deps_stream);
2187 putc ('\n', deps_stream);
2188 if (deps_file) {
2189 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2190 fatal ("I/O error on output");
2195 if (pcp_outfile && pcp_outfile != stdout
2196 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2197 fatal ("I/O error on `-pcp' output");
2199 if (ferror (stdout) || fclose (stdout) != 0)
2200 fatal ("I/O error on output");
2202 if (errors)
2203 exit (FATAL_EXIT_CODE);
2204 exit (SUCCESS_EXIT_CODE);
2206 perror:
2207 pfatal_with_name (in_fname);
2208 return 0;
2211 /* Given a colon-separated list of file names PATH,
2212 add all the names to the search path for include files. */
2214 static void
2215 path_include (path)
2216 char *path;
2218 char *p;
2220 p = path;
2222 if (*p)
2223 while (1) {
2224 char *q = p;
2225 char c;
2226 struct file_name_list *dirtmp;
2228 /* Find the end of this name. */
2229 while ((c = *q++) != PATH_SEPARATOR && c)
2230 continue;
2232 q[-1] = 0;
2233 dirtmp = new_include_prefix (last_include, NULL_PTR,
2234 "", p == q ? "." : p);
2235 q[-1] = c;
2236 append_include_chain (dirtmp, dirtmp);
2238 /* Advance past this name. */
2239 p = q;
2240 if (! c)
2241 break;
2245 /* Return the address of the first character in S that equals C.
2246 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2247 Return 0 if there is no such character. Assume that C itself is not '\0'.
2248 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2249 but unfortunately memchr isn't autoconfigured yet. */
2251 static U_CHAR *
2252 index0 (s, c, n)
2253 U_CHAR *s;
2254 int c;
2255 size_t n;
2257 char *p = (char *) s;
2258 for (;;) {
2259 char *q = index (p, c);
2260 if (q)
2261 return (U_CHAR *) q;
2262 else {
2263 size_t l = strlen (p);
2264 if (l == n)
2265 return 0;
2266 l++;
2267 p += l;
2268 n -= l;
2273 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2274 before main CCCP processing. Name `pcp' is also in honor of the
2275 drugs the trigraph designers must have been on.
2277 Using an extra pass through the buffer takes a little extra time,
2278 but is infinitely less hairy than trying to handle trigraphs inside
2279 strings, etc. everywhere, and also makes sure that trigraphs are
2280 only translated in the top level of processing. */
2282 static void
2283 trigraph_pcp (buf)
2284 FILE_BUF *buf;
2286 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2287 int len;
2289 fptr = bptr = sptr = buf->buf;
2290 lptr = fptr + buf->length;
2291 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2292 if (*++sptr != '?')
2293 continue;
2294 switch (*++sptr) {
2295 case '=':
2296 c = '#';
2297 break;
2298 case '(':
2299 c = '[';
2300 break;
2301 case '/':
2302 c = '\\';
2303 break;
2304 case ')':
2305 c = ']';
2306 break;
2307 case '\'':
2308 c = '^';
2309 break;
2310 case '<':
2311 c = '{';
2312 break;
2313 case '!':
2314 c = '|';
2315 break;
2316 case '>':
2317 c = '}';
2318 break;
2319 case '-':
2320 c = '~';
2321 break;
2322 case '?':
2323 sptr--;
2324 continue;
2325 default:
2326 continue;
2328 len = sptr - fptr - 2;
2330 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2331 C, this will be memmove (). */
2332 if (bptr != fptr && len > 0)
2333 bcopy ((char *) fptr, (char *) bptr, len);
2335 bptr += len;
2336 *bptr++ = c;
2337 fptr = ++sptr;
2339 len = buf->length - (fptr - buf->buf);
2340 if (bptr != fptr && len > 0)
2341 bcopy ((char *) fptr, (char *) bptr, len);
2342 buf->length -= fptr - bptr;
2343 buf->buf[buf->length] = '\0';
2344 if (warn_trigraphs && fptr != bptr)
2345 warning_with_line (0, "%lu trigraph(s) encountered",
2346 (unsigned long) (fptr - bptr) / 2);
2349 /* Move all backslash-newline pairs out of embarrassing places.
2350 Exchange all such pairs following BP
2351 with any potentially-embarrassing characters that follow them.
2352 Potentially-embarrassing characters are / and *
2353 (because a backslash-newline inside a comment delimiter
2354 would cause it not to be recognized). */
2356 static void
2357 newline_fix (bp)
2358 U_CHAR *bp;
2360 register U_CHAR *p = bp;
2362 /* First count the backslash-newline pairs here. */
2364 while (p[0] == '\\' && p[1] == '\n')
2365 p += 2;
2367 /* What follows the backslash-newlines is not embarrassing. */
2369 if (*p != '/' && *p != '*')
2370 return;
2372 /* Copy all potentially embarrassing characters
2373 that follow the backslash-newline pairs
2374 down to where the pairs originally started. */
2376 while (*p == '*' || *p == '/')
2377 *bp++ = *p++;
2379 /* Now write the same number of pairs after the embarrassing chars. */
2380 while (bp < p) {
2381 *bp++ = '\\';
2382 *bp++ = '\n';
2386 /* Like newline_fix but for use within a directive-name.
2387 Move any backslash-newlines up past any following symbol constituents. */
2389 static void
2390 name_newline_fix (bp)
2391 U_CHAR *bp;
2393 register U_CHAR *p = bp;
2395 /* First count the backslash-newline pairs here. */
2396 while (p[0] == '\\' && p[1] == '\n')
2397 p += 2;
2399 /* What follows the backslash-newlines is not embarrassing. */
2401 if (!is_idchar[*p])
2402 return;
2404 /* Copy all potentially embarrassing characters
2405 that follow the backslash-newline pairs
2406 down to where the pairs originally started. */
2408 while (is_idchar[*p])
2409 *bp++ = *p++;
2411 /* Now write the same number of pairs after the embarrassing chars. */
2412 while (bp < p) {
2413 *bp++ = '\\';
2414 *bp++ = '\n';
2418 /* Look for lint commands in comments.
2420 When we come in here, ibp points into a comment. Limit is as one expects.
2421 scan within the comment -- it should start, after lwsp, with a lint command.
2422 If so that command is returned as a (constant) string.
2424 Upon return, any arg will be pointed to with argstart and will be
2425 arglen long. Note that we don't parse that arg since it will just
2426 be printed out again. */
2428 static char *
2429 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2430 register U_CHAR *ibp;
2431 register U_CHAR *limit;
2432 U_CHAR **argstart; /* point to command arg */
2433 int *arglen, *cmdlen; /* how long they are */
2435 HOST_WIDE_INT linsize;
2436 register U_CHAR *numptr; /* temp for arg parsing */
2438 *arglen = 0;
2440 SKIP_WHITE_SPACE (ibp);
2442 if (ibp >= limit) return NULL;
2444 linsize = limit - ibp;
2446 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2447 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2448 *cmdlen = 10;
2449 return "NOTREACHED";
2451 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2452 *cmdlen = 8;
2453 return "ARGSUSED";
2455 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2456 *cmdlen = 11;
2457 return "LINTLIBRARY";
2459 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2460 *cmdlen = 7;
2461 ibp += 7; linsize -= 7;
2462 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2464 /* OK, read a number */
2465 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2466 numptr++);
2467 *arglen = numptr - *argstart;
2468 return "VARARGS";
2470 return NULL;
2474 * The main loop of the program.
2476 * Read characters from the input stack, transferring them to the
2477 * output buffer OP.
2479 * Macros are expanded and push levels on the input stack.
2480 * At the end of such a level it is popped off and we keep reading.
2481 * At the end of any other kind of level, we return.
2482 * #-directives are handled, except within macros.
2484 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2485 * and insert them when appropriate. This is set while scanning macro
2486 * arguments before substitution. It is zero when scanning for final output.
2487 * There are three types of Newline markers:
2488 * * Newline - follows a macro name that was not expanded
2489 * because it appeared inside an expansion of the same macro.
2490 * This marker prevents future expansion of that identifier.
2491 * When the input is rescanned into the final output, these are deleted.
2492 * These are also deleted by ## concatenation.
2493 * * Newline Space (or Newline and any other whitespace character)
2494 * stands for a place that tokens must be separated or whitespace
2495 * is otherwise desirable, but where the ANSI standard specifies there
2496 * is no whitespace. This marker turns into a Space (or whichever other
2497 * whitespace char appears in the marker) in the final output,
2498 * but it turns into nothing in an argument that is stringified with #.
2499 * Such stringified arguments are the only place where the ANSI standard
2500 * specifies with precision that whitespace may not appear.
2502 * During this function, IP->bufp is kept cached in IBP for speed of access.
2503 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2504 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2505 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2506 * explicitly, and before RECACHE, since RECACHE uses OBP.
2509 static void
2510 rescan (op, output_marks)
2511 FILE_BUF *op;
2512 int output_marks;
2514 /* Character being scanned in main loop. */
2515 register U_CHAR c;
2517 /* Length of pending accumulated identifier. */
2518 register int ident_length = 0;
2520 /* Hash code of pending accumulated identifier. */
2521 register int hash = 0;
2523 /* Current input level (&instack[indepth]). */
2524 FILE_BUF *ip;
2526 /* Pointer for scanning input. */
2527 register U_CHAR *ibp;
2529 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2530 register U_CHAR *limit;
2532 /* Pointer for storing output. */
2533 register U_CHAR *obp;
2535 /* REDO_CHAR is nonzero if we are processing an identifier
2536 after backing up over the terminating character.
2537 Sometimes we process an identifier without backing up over
2538 the terminating character, if the terminating character
2539 is not special. Backing up is done so that the terminating character
2540 will be dispatched on again once the identifier is dealt with. */
2541 int redo_char = 0;
2543 /* 1 if within an identifier inside of which a concatenation
2544 marker (Newline -) has been seen. */
2545 int concatenated = 0;
2547 /* While scanning a comment or a string constant,
2548 this records the line it started on, for error messages. */
2549 int start_line;
2551 /* Record position of last `real' newline. */
2552 U_CHAR *beg_of_line;
2554 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2556 #define POPMACRO \
2557 do { ip->macro->type = T_MACRO; \
2558 if (ip->free_ptr) free (ip->free_ptr); \
2559 --indepth; } while (0)
2561 /* Reload `rescan's local variables that describe the current
2562 level of the input stack. */
2564 #define RECACHE \
2565 do { ip = &instack[indepth]; \
2566 ibp = ip->bufp; \
2567 limit = ip->buf + ip->length; \
2568 op->bufp = obp; \
2569 check_expand (op, limit - ibp); \
2570 beg_of_line = 0; \
2571 obp = op->bufp; } while (0)
2573 if (no_output && instack[indepth].fname != 0)
2574 skip_if_group (&instack[indepth], 1, NULL);
2576 obp = op->bufp;
2577 RECACHE;
2579 beg_of_line = ibp;
2581 /* Our caller must always put a null after the end of
2582 the input at each input stack level. */
2583 if (*limit != 0)
2584 abort ();
2586 while (1) {
2587 c = *ibp++;
2588 *obp++ = c;
2590 switch (c) {
2591 case '\\':
2592 if (*ibp == '\n' && !ip->macro) {
2593 /* At the top level, always merge lines ending with backslash-newline,
2594 even in middle of identifier. But do not merge lines in a macro,
2595 since backslash might be followed by a newline-space marker. */
2596 ++ibp;
2597 ++ip->lineno;
2598 --obp; /* remove backslash from obuf */
2599 break;
2601 /* If ANSI, backslash is just another character outside a string. */
2602 if (!traditional)
2603 goto randomchar;
2604 /* Otherwise, backslash suppresses specialness of following char,
2605 so copy it here to prevent the switch from seeing it.
2606 But first get any pending identifier processed. */
2607 if (ident_length > 0)
2608 goto specialchar;
2609 if (ibp < limit)
2610 *obp++ = *ibp++;
2611 break;
2613 case '%':
2614 if (ident_length || ip->macro || traditional)
2615 goto randomchar;
2616 while (*ibp == '\\' && ibp[1] == '\n') {
2617 ibp += 2;
2618 ++ip->lineno;
2620 if (*ibp != ':')
2621 break;
2622 /* Treat this %: digraph as if it were #. */
2623 /* Fall through. */
2625 case '#':
2626 if (assertions_flag) {
2627 if (ident_length)
2628 goto specialchar;
2629 /* Copy #foo (bar lose) without macro expansion. */
2630 obp[-1] = '#'; /* In case it was '%'. */
2631 SKIP_WHITE_SPACE (ibp);
2632 while (is_idchar[*ibp])
2633 *obp++ = *ibp++;
2634 SKIP_WHITE_SPACE (ibp);
2635 if (*ibp == '(') {
2636 ip->bufp = ibp;
2637 skip_paren_group (ip);
2638 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2639 obp += ip->bufp - ibp;
2640 ibp = ip->bufp;
2642 break;
2645 /* If this is expanding a macro definition, don't recognize
2646 preprocessing directives. */
2647 if (ip->macro != 0)
2648 goto randomchar;
2649 /* If this is expand_into_temp_buffer,
2650 don't recognize them either. Warn about them
2651 only after an actual newline at this level,
2652 not at the beginning of the input level. */
2653 if (! ip->fname) {
2654 if (ip->buf != beg_of_line)
2655 warning ("preprocessing directive not recognized within macro arg");
2656 goto randomchar;
2658 if (ident_length)
2659 goto specialchar;
2662 /* # keyword: a # must be first nonblank char on the line */
2663 if (beg_of_line == 0)
2664 goto randomchar;
2666 U_CHAR *bp;
2668 /* Scan from start of line, skipping whitespace, comments
2669 and backslash-newlines, and see if we reach this #.
2670 If not, this # is not special. */
2671 bp = beg_of_line;
2672 /* If -traditional, require # to be at beginning of line. */
2673 if (!traditional) {
2674 while (1) {
2675 if (is_hor_space[*bp])
2676 bp++;
2677 else if (*bp == '\\' && bp[1] == '\n')
2678 bp += 2;
2679 else if (*bp == '/' && bp[1] == '*') {
2680 bp += 2;
2681 while (!(*bp == '*' && bp[1] == '/'))
2682 bp++;
2683 bp += 2;
2685 /* There is no point in trying to deal with C++ // comments here,
2686 because if there is one, then this # must be part of the
2687 comment and we would never reach here. */
2688 else break;
2690 if (c == '%') {
2691 if (bp[0] != '%')
2692 break;
2693 while (bp[1] == '\\' && bp[2] == '\n')
2694 bp += 2;
2695 if (bp + 1 != ibp)
2696 break;
2697 /* %: appears at start of line; skip past the ':' too. */
2698 bp++;
2699 ibp++;
2702 if (bp + 1 != ibp)
2703 goto randomchar;
2706 /* This # can start a directive. */
2708 --obp; /* Don't copy the '#' */
2710 ip->bufp = ibp;
2711 op->bufp = obp;
2712 if (! handle_directive (ip, op)) {
2713 #ifdef USE_C_ALLOCA
2714 alloca (0);
2715 #endif
2716 /* Not a known directive: treat it as ordinary text.
2717 IP, OP, IBP, etc. have not been changed. */
2718 if (no_output && instack[indepth].fname) {
2719 /* If not generating expanded output,
2720 what we do with ordinary text is skip it.
2721 Discard everything until next # directive. */
2722 skip_if_group (&instack[indepth], 1, 0);
2723 RECACHE;
2724 beg_of_line = ibp;
2725 break;
2727 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2728 /* Don't expand an identifier that could be a macro directive.
2729 (Section 3.8.3 of the ANSI C standard) */
2730 SKIP_WHITE_SPACE (ibp);
2731 if (is_idstart[*ibp])
2733 *obp++ = *ibp++;
2734 while (is_idchar[*ibp])
2735 *obp++ = *ibp++;
2737 goto randomchar;
2739 #ifdef USE_C_ALLOCA
2740 alloca (0);
2741 #endif
2742 /* A # directive has been successfully processed. */
2743 /* If not generating expanded output, ignore everything until
2744 next # directive. */
2745 if (no_output && instack[indepth].fname)
2746 skip_if_group (&instack[indepth], 1, 0);
2747 obp = op->bufp;
2748 RECACHE;
2749 beg_of_line = ibp;
2750 break;
2752 case '\"': /* skip quoted string */
2753 case '\'':
2754 /* A single quoted string is treated like a double -- some
2755 programs (e.g., troff) are perverse this way */
2757 /* Handle any pending identifier;
2758 but the L in L'...' or L"..." is not an identifier. */
2759 if (ident_length) {
2760 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2761 goto specialchar;
2762 ident_length = hash = 0;
2765 start_line = ip->lineno;
2767 /* Skip ahead to a matching quote. */
2769 while (1) {
2770 if (ibp >= limit) {
2771 if (ip->macro != 0) {
2772 /* try harder: this string crosses a macro expansion boundary.
2773 This can happen naturally if -traditional.
2774 Otherwise, only -D can make a macro with an unmatched quote. */
2775 POPMACRO;
2776 RECACHE;
2777 continue;
2779 if (!traditional) {
2780 error_with_line (line_for_error (start_line),
2781 "unterminated string or character constant");
2782 if (multiline_string_line) {
2783 error_with_line (multiline_string_line,
2784 "possible real start of unterminated constant");
2785 multiline_string_line = 0;
2788 break;
2790 *obp++ = *ibp;
2791 switch (*ibp++) {
2792 case '\n':
2793 ++ip->lineno;
2794 ++op->lineno;
2795 /* Traditionally, end of line ends a string constant with no error.
2796 So exit the loop and record the new line. */
2797 if (traditional) {
2798 beg_of_line = ibp;
2799 goto while2end;
2801 if (c == '\'') {
2802 error_with_line (line_for_error (start_line),
2803 "unterminated character constant");
2804 goto while2end;
2806 if (multiline_string_line == 0) {
2807 if (pedantic)
2808 pedwarn_with_line (line_for_error (start_line),
2809 "string constant runs past end of line");
2810 multiline_string_line = ip->lineno - 1;
2812 break;
2814 case '\\':
2815 if (*ibp == '\n') {
2816 /* Backslash newline is replaced by nothing at all, but
2817 keep the line counts correct. But if we are reading
2818 from a macro, keep the backslash newline, since backslash
2819 newlines have already been processed. */
2820 if (ip->macro)
2821 *obp++ = '\n';
2822 else
2823 --obp;
2824 ++ibp;
2825 ++ip->lineno;
2826 } else {
2827 /* ANSI stupidly requires that in \\ the second \
2828 is *not* prevented from combining with a newline. */
2829 if (!ip->macro) {
2830 while (*ibp == '\\' && ibp[1] == '\n') {
2831 ibp += 2;
2832 ++ip->lineno;
2835 *obp++ = *ibp++;
2837 break;
2839 case '\"':
2840 case '\'':
2841 if (ibp[-1] == c)
2842 goto while2end;
2843 break;
2846 while2end:
2847 break;
2849 case '/':
2850 if (ip->macro != 0)
2851 goto randomchar;
2852 if (*ibp == '\\' && ibp[1] == '\n')
2853 newline_fix (ibp);
2854 if (*ibp != '*'
2855 && !(cplusplus_comments && *ibp == '/'))
2856 goto randomchar;
2857 if (ident_length)
2858 goto specialchar;
2860 if (*ibp == '/') {
2861 /* C++ style comment... */
2862 start_line = ip->lineno;
2864 /* Comments are equivalent to spaces. */
2865 if (! put_out_comments)
2866 obp[-1] = ' ';
2869 U_CHAR *before_bp = ibp;
2871 while (++ibp < limit) {
2872 if (*ibp == '\n') {
2873 if (ibp[-1] != '\\') {
2874 if (put_out_comments) {
2875 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2876 obp += ibp - before_bp;
2878 break;
2880 if (warn_comments)
2881 warning ("multiline `//' comment");
2882 ++ip->lineno;
2883 /* Copy the newline into the output buffer, in order to
2884 avoid the pain of a #line every time a multiline comment
2885 is seen. */
2886 if (!put_out_comments)
2887 *obp++ = '\n';
2888 ++op->lineno;
2891 break;
2895 /* Ordinary C comment. Skip it, optionally copying it to output. */
2897 start_line = ip->lineno;
2899 ++ibp; /* Skip the star. */
2901 /* If this cpp is for lint, we peek inside the comments: */
2902 if (for_lint) {
2903 U_CHAR *argbp;
2904 int cmdlen, arglen;
2905 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2907 if (lintcmd != NULL) {
2908 op->bufp = obp;
2909 check_expand (op, cmdlen + arglen + 14);
2910 obp = op->bufp;
2911 /* I believe it is always safe to emit this newline: */
2912 obp[-1] = '\n';
2913 bcopy ("#pragma lint ", (char *) obp, 13);
2914 obp += 13;
2915 bcopy (lintcmd, (char *) obp, cmdlen);
2916 obp += cmdlen;
2918 if (arglen != 0) {
2919 *(obp++) = ' ';
2920 bcopy (argbp, (char *) obp, arglen);
2921 obp += arglen;
2924 /* OK, now bring us back to the state we were in before we entered
2925 this branch. We need #line because the #pragma's newline always
2926 messes up the line count. */
2927 op->bufp = obp;
2928 output_line_directive (ip, op, 0, same_file);
2929 check_expand (op, limit - ibp + 2);
2930 obp = op->bufp;
2931 *(obp++) = '/';
2935 /* Comments are equivalent to spaces.
2936 Note that we already output the slash; we might not want it.
2937 For -traditional, a comment is equivalent to nothing. */
2938 if (! put_out_comments) {
2939 if (traditional)
2940 obp--;
2941 else
2942 obp[-1] = ' ';
2944 else
2945 *obp++ = '*';
2948 U_CHAR *before_bp = ibp;
2950 for (;;) {
2951 switch (*ibp++) {
2952 case '*':
2953 if (ibp[-2] == '/' && warn_comments)
2954 warning ("`/*' within comment");
2955 if (*ibp == '\\' && ibp[1] == '\n')
2956 newline_fix (ibp);
2957 if (*ibp == '/')
2958 goto comment_end;
2959 break;
2961 case '\n':
2962 ++ip->lineno;
2963 /* Copy the newline into the output buffer, in order to
2964 avoid the pain of a #line every time a multiline comment
2965 is seen. */
2966 if (!put_out_comments)
2967 *obp++ = '\n';
2968 ++op->lineno;
2969 break;
2971 case 0:
2972 if (limit < ibp) {
2973 error_with_line (line_for_error (start_line),
2974 "unterminated comment");
2975 goto limit_reached;
2977 break;
2980 comment_end:
2982 ibp++;
2983 if (put_out_comments) {
2984 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2985 obp += ibp - before_bp;
2988 break;
2990 case '$':
2991 if (! is_idchar['$'])
2992 goto randomchar;
2993 if (pedantic)
2994 pedwarn ("`$' in identifier");
2995 goto letter;
2997 case '0': case '1': case '2': case '3': case '4':
2998 case '5': case '6': case '7': case '8': case '9':
2999 /* If digit is not part of identifier, it starts a number,
3000 which means that following letters are not an identifier.
3001 "0x5" does not refer to an identifier "x5".
3002 So copy all alphanumerics that follow without accumulating
3003 as an identifier. Periods also, for sake of "3.e7". */
3005 if (ident_length == 0) {
3006 for (;;) {
3007 if (!ip->macro) {
3008 while (ibp[0] == '\\' && ibp[1] == '\n') {
3009 ++ip->lineno;
3010 ibp += 2;
3013 c = *ibp++;
3014 if (!is_idchar[c] && c != '.') {
3015 --ibp;
3016 break;
3018 *obp++ = c;
3019 /* A sign can be part of a preprocessing number
3020 if it follows an `e' or `p'. */
3021 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3022 if (!ip->macro) {
3023 while (ibp[0] == '\\' && ibp[1] == '\n') {
3024 ++ip->lineno;
3025 ibp += 2;
3028 if (*ibp == '+' || *ibp == '-') {
3029 *obp++ = *ibp++;
3030 /* But traditional C does not let the token go past the sign,
3031 and C89 does not allow `p'. */
3032 if (traditional || (c89 && (c == 'p' || c == 'P')))
3033 break;
3037 break;
3039 /* fall through */
3041 case '_':
3042 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3043 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3044 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3045 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3046 case 'y': case 'z':
3047 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3048 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3049 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3050 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3051 case 'Y': case 'Z':
3052 letter:
3053 ident_length++;
3054 /* Compute step of hash function, to avoid a proc call on every token */
3055 hash = HASHSTEP (hash, c);
3056 break;
3058 case '\n':
3059 if (ip->fname == 0 && *ibp == '-') {
3060 /* Newline - inhibits expansion of preceding token.
3061 If expanding a macro arg, we keep the newline -.
3062 In final output, it is deleted.
3063 We recognize Newline - in macro bodies and macro args. */
3064 if (! concatenated) {
3065 ident_length = 0;
3066 hash = 0;
3068 ibp++;
3069 if (!output_marks) {
3070 obp--;
3071 } else {
3072 /* If expanding a macro arg, keep the newline -. */
3073 *obp++ = '-';
3075 break;
3078 /* If reprocessing a macro expansion, newline is a special marker. */
3079 else if (ip->macro != 0) {
3080 /* Newline White is a "funny space" to separate tokens that are
3081 supposed to be separate but without space between.
3082 Here White means any whitespace character.
3083 Newline - marks a recursive macro use that is not
3084 supposed to be expandable. */
3086 if (is_space[*ibp]) {
3087 /* Newline Space does not prevent expansion of preceding token
3088 so expand the preceding token and then come back. */
3089 if (ident_length > 0)
3090 goto specialchar;
3092 /* If generating final output, newline space makes a space. */
3093 if (!output_marks) {
3094 obp[-1] = *ibp++;
3095 /* And Newline Newline makes a newline, so count it. */
3096 if (obp[-1] == '\n')
3097 op->lineno++;
3098 } else {
3099 /* If expanding a macro arg, keep the newline space.
3100 If the arg gets stringified, newline space makes nothing. */
3101 *obp++ = *ibp++;
3103 } else abort (); /* Newline followed by something random? */
3104 break;
3107 /* If there is a pending identifier, handle it and come back here. */
3108 if (ident_length > 0)
3109 goto specialchar;
3111 beg_of_line = ibp;
3113 /* Update the line counts and output a #line if necessary. */
3114 ++ip->lineno;
3115 ++op->lineno;
3116 if (ip->lineno != op->lineno) {
3117 op->bufp = obp;
3118 output_line_directive (ip, op, 1, same_file);
3119 check_expand (op, limit - ibp);
3120 obp = op->bufp;
3122 break;
3124 /* Come here either after (1) a null character that is part of the input
3125 or (2) at the end of the input, because there is a null there. */
3126 case 0:
3127 if (ibp <= limit)
3128 /* Our input really contains a null character. */
3129 goto randomchar;
3131 limit_reached:
3132 /* At end of a macro-expansion level, pop it and read next level. */
3133 if (ip->macro != 0) {
3134 obp--;
3135 ibp--;
3136 /* If traditional, and we have an identifier that ends here,
3137 process it now, so we get the right error for recursion. */
3138 if (traditional && ident_length
3139 && ! is_idchar[*instack[indepth - 1].bufp]) {
3140 redo_char = 1;
3141 goto randomchar;
3143 POPMACRO;
3144 RECACHE;
3145 break;
3148 /* If we don't have a pending identifier,
3149 return at end of input. */
3150 if (ident_length == 0) {
3151 obp--;
3152 ibp--;
3153 op->bufp = obp;
3154 ip->bufp = ibp;
3155 goto ending;
3158 /* If we do have a pending identifier, just consider this null
3159 a special character and arrange to dispatch on it again.
3160 The second time, IDENT_LENGTH will be zero so we will return. */
3162 /* Fall through */
3164 specialchar:
3166 /* Handle the case of a character such as /, ', " or null
3167 seen following an identifier. Back over it so that
3168 after the identifier is processed the special char
3169 will be dispatched on again. */
3171 ibp--;
3172 obp--;
3173 redo_char = 1;
3175 default:
3177 randomchar:
3179 if (ident_length > 0) {
3180 register HASHNODE *hp;
3182 /* We have just seen an identifier end. If it's a macro, expand it.
3184 IDENT_LENGTH is the length of the identifier
3185 and HASH is its hash code.
3187 The identifier has already been copied to the output,
3188 so if it is a macro we must remove it.
3190 If REDO_CHAR is 0, the char that terminated the identifier
3191 has been skipped in the output and the input.
3192 OBP-IDENT_LENGTH-1 points to the identifier.
3193 If the identifier is a macro, we must back over the terminator.
3195 If REDO_CHAR is 1, the terminating char has already been
3196 backed over. OBP-IDENT_LENGTH points to the identifier. */
3198 if (!pcp_outfile || pcp_inside_if) {
3199 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3200 hp = hp->next) {
3202 if (hp->length == ident_length) {
3203 int obufp_before_macroname;
3204 int op_lineno_before_macroname;
3205 register int i = ident_length;
3206 register U_CHAR *p = hp->name;
3207 register U_CHAR *q = obp - i;
3208 int disabled;
3210 if (! redo_char)
3211 q--;
3213 do { /* All this to avoid a strncmp () */
3214 if (*p++ != *q++)
3215 goto hashcollision;
3216 } while (--i);
3218 /* We found a use of a macro name.
3219 see if the context shows it is a macro call. */
3221 /* Back up over terminating character if not already done. */
3222 if (! redo_char) {
3223 ibp--;
3224 obp--;
3227 /* Save this as a displacement from the beginning of the output
3228 buffer. We can not save this as a position in the output
3229 buffer, because it may get realloc'ed by RECACHE. */
3230 obufp_before_macroname = (obp - op->buf) - ident_length;
3231 op_lineno_before_macroname = op->lineno;
3233 if (hp->type == T_PCSTRING) {
3234 pcstring_used (hp); /* Mark the definition of this key
3235 as needed, ensuring that it
3236 will be output. */
3237 break; /* Exit loop, since the key cannot have a
3238 definition any longer. */
3241 /* Record whether the macro is disabled. */
3242 disabled = hp->type == T_DISABLED;
3244 /* This looks like a macro ref, but if the macro was disabled,
3245 just copy its name and put in a marker if requested. */
3247 if (disabled) {
3248 #if 0
3249 /* This error check caught useful cases such as
3250 #define foo(x,y) bar (x (y,0), y)
3251 foo (foo, baz) */
3252 if (traditional)
3253 error ("recursive use of macro `%s'", hp->name);
3254 #endif
3256 if (output_marks) {
3257 check_expand (op, limit - ibp + 2);
3258 *obp++ = '\n';
3259 *obp++ = '-';
3261 break;
3264 /* If macro wants an arglist, verify that a '(' follows.
3265 first skip all whitespace, copying it to the output
3266 after the macro name. Then, if there is no '(',
3267 decide this is not a macro call and leave things that way. */
3268 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3269 && hp->value.defn->nargs >= 0)
3271 U_CHAR *old_ibp = ibp;
3272 U_CHAR *old_obp = obp;
3273 int old_iln = ip->lineno;
3274 int old_oln = op->lineno;
3276 while (1) {
3277 /* Scan forward over whitespace, copying it to the output. */
3278 if (ibp == limit && ip->macro != 0) {
3279 POPMACRO;
3280 RECACHE;
3281 old_ibp = ibp;
3282 old_obp = obp;
3283 old_iln = ip->lineno;
3284 old_oln = op->lineno;
3286 else if (is_space[*ibp]) {
3287 *obp++ = *ibp++;
3288 if (ibp[-1] == '\n') {
3289 if (ip->macro == 0) {
3290 /* Newline in a file. Count it. */
3291 ++ip->lineno;
3292 ++op->lineno;
3293 } else if (!output_marks) {
3294 /* A newline mark, and we don't want marks
3295 in the output. If it is newline-hyphen,
3296 discard it entirely. Otherwise, it is
3297 newline-whitechar, so keep the whitechar. */
3298 obp--;
3299 if (*ibp == '-')
3300 ibp++;
3301 else {
3302 if (*ibp == '\n')
3303 ++op->lineno;
3304 *obp++ = *ibp++;
3306 } else {
3307 /* A newline mark; copy both chars to the output. */
3308 *obp++ = *ibp++;
3312 else if (ip->macro)
3313 break;
3314 else if (*ibp == '/') {
3315 /* If a comment, copy it unchanged or discard it. */
3316 if (ibp[1] == '\\' && ibp[2] == '\n')
3317 newline_fix (ibp + 1);
3318 if (ibp[1] == '*') {
3319 if (put_out_comments) {
3320 *obp++ = '/';
3321 *obp++ = '*';
3322 } else if (! traditional) {
3323 *obp++ = ' ';
3325 for (ibp += 2; ibp < limit; ibp++) {
3326 /* We need not worry about newline-marks,
3327 since they are never found in comments. */
3328 if (ibp[0] == '*') {
3329 if (ibp[1] == '\\' && ibp[2] == '\n')
3330 newline_fix (ibp + 1);
3331 if (ibp[1] == '/') {
3332 ibp += 2;
3333 if (put_out_comments) {
3334 *obp++ = '*';
3335 *obp++ = '/';
3337 break;
3340 if (*ibp == '\n') {
3341 /* Newline in a file. Count it. */
3342 ++ip->lineno;
3343 ++op->lineno;
3345 if (put_out_comments)
3346 *obp++ = *ibp;
3348 } else if (ibp[1] == '/' && cplusplus_comments) {
3349 if (put_out_comments) {
3350 *obp++ = '/';
3351 *obp++ = '/';
3352 } else if (! traditional) {
3353 *obp++ = ' ';
3355 for (ibp += 2; *ibp != '\n' || ibp[-1] == '\\'; ibp++)
3356 if (put_out_comments)
3357 *obp++ = *ibp;
3358 } else
3359 break;
3361 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3362 ibp += 2;
3363 ++ip->lineno;
3365 else break;
3367 if (*ibp != '(') {
3368 /* It isn't a macro call.
3369 Put back the space that we just skipped. */
3370 ibp = old_ibp;
3371 obp = old_obp;
3372 ip->lineno = old_iln;
3373 op->lineno = old_oln;
3374 /* Exit the for loop. */
3375 break;
3379 /* This is now known to be a macro call.
3380 Discard the macro name from the output,
3381 along with any following whitespace just copied,
3382 but preserve newlines if not outputting marks since this
3383 is more likely to do the right thing with line numbers. */
3384 obp = op->buf + obufp_before_macroname;
3385 if (output_marks)
3386 op->lineno = op_lineno_before_macroname;
3387 else {
3388 int newlines = op->lineno - op_lineno_before_macroname;
3389 while (0 < newlines--)
3390 *obp++ = '\n';
3393 /* Prevent accidental token-pasting with a character
3394 before the macro call. */
3395 if (!traditional && obp != op->buf) {
3396 switch (obp[-1]) {
3397 case '!': case '%': case '&': case '*':
3398 case '+': case '-': case '.': case '/':
3399 case ':': case '<': case '=': case '>':
3400 case '^': case '|':
3401 /* If we are expanding a macro arg, make a newline marker
3402 to separate the tokens. If we are making real output,
3403 a plain space will do. */
3404 if (output_marks)
3405 *obp++ = '\n';
3406 *obp++ = ' ';
3410 /* Expand the macro, reading arguments as needed,
3411 and push the expansion on the input stack. */
3412 ip->bufp = ibp;
3413 op->bufp = obp;
3414 macroexpand (hp, op);
3416 /* Reexamine input stack, since macroexpand has pushed
3417 a new level on it. */
3418 obp = op->bufp;
3419 RECACHE;
3420 break;
3422 hashcollision:
3424 } /* End hash-table-search loop */
3426 ident_length = hash = 0; /* Stop collecting identifier */
3427 redo_char = 0;
3428 concatenated = 0;
3429 } /* End if (ident_length > 0) */
3430 } /* End switch */
3431 } /* End per-char loop */
3433 /* Come here to return -- but first give an error message
3434 if there was an unterminated successful conditional. */
3435 ending:
3436 if (if_stack != ip->if_stack)
3438 char *str;
3440 switch (if_stack->type)
3442 case T_IF:
3443 str = "if";
3444 break;
3445 case T_IFDEF:
3446 str = "ifdef";
3447 break;
3448 case T_IFNDEF:
3449 str = "ifndef";
3450 break;
3451 case T_ELSE:
3452 str = "else";
3453 break;
3454 case T_ELIF:
3455 str = "elif";
3456 break;
3457 default:
3458 abort ();
3461 error_with_line (line_for_error (if_stack->lineno),
3462 "unterminated `#%s' conditional", str);
3464 if_stack = ip->if_stack;
3468 * Rescan a string into a temporary buffer and return the result
3469 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3471 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3472 * and insert such markers when appropriate. See `rescan' for details.
3473 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3474 * before substitution; it is 0 for other uses.
3476 static FILE_BUF
3477 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3478 U_CHAR *buf, *limit;
3479 int output_marks, assertions;
3481 register FILE_BUF *ip;
3482 FILE_BUF obuf;
3483 int length = limit - buf;
3484 U_CHAR *buf1;
3485 int odepth = indepth;
3486 int save_assertions_flag = assertions_flag;
3488 assertions_flag = assertions;
3490 if (length < 0)
3491 abort ();
3493 /* Set up the input on the input stack. */
3495 buf1 = (U_CHAR *) alloca (length + 1);
3497 register U_CHAR *p1 = buf;
3498 register U_CHAR *p2 = buf1;
3500 while (p1 != limit)
3501 *p2++ = *p1++;
3503 buf1[length] = 0;
3505 /* Set up to receive the output. */
3507 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3508 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3509 obuf.fname = 0;
3510 obuf.macro = 0;
3511 obuf.free_ptr = 0;
3513 CHECK_DEPTH ({return obuf;});
3515 ++indepth;
3517 ip = &instack[indepth];
3518 ip->fname = 0;
3519 ip->nominal_fname = 0;
3520 ip->inc = 0;
3521 ip->system_header_p = 0;
3522 ip->macro = 0;
3523 ip->free_ptr = 0;
3524 ip->length = length;
3525 ip->buf = ip->bufp = buf1;
3526 ip->if_stack = if_stack;
3528 ip->lineno = obuf.lineno = 1;
3530 /* Scan the input, create the output. */
3531 rescan (&obuf, output_marks);
3533 /* Pop input stack to original state. */
3534 --indepth;
3536 if (indepth != odepth)
3537 abort ();
3539 /* Record the output. */
3540 obuf.length = obuf.bufp - obuf.buf;
3542 assertions_flag = save_assertions_flag;
3543 return obuf;
3547 * Process a # directive. Expects IP->bufp to point after the '#', as in
3548 * `#define foo bar'. Passes to the directive handler
3549 * (do_define, do_include, etc.): the addresses of the 1st and
3550 * last chars of the directive (starting immediately after the #
3551 * keyword), plus op and the keyword table pointer. If the directive
3552 * contains comments it is copied into a temporary buffer sans comments
3553 * and the temporary buffer is passed to the directive handler instead.
3554 * Likewise for backslash-newlines.
3556 * Returns nonzero if this was a known # directive.
3557 * Otherwise, returns zero, without advancing the input pointer.
3560 static int
3561 handle_directive (ip, op)
3562 FILE_BUF *ip, *op;
3564 register U_CHAR *bp, *cp;
3565 register struct directive *kt;
3566 register int ident_length;
3567 U_CHAR *resume_p;
3569 /* Nonzero means we must copy the entire directive
3570 to get rid of comments or backslash-newlines. */
3571 int copy_directive = 0;
3573 U_CHAR *ident, *after_ident;
3575 bp = ip->bufp;
3577 /* Record where the directive started. do_xifdef needs this. */
3578 directive_start = bp - 1;
3580 /* Skip whitespace and \-newline. */
3581 while (1) {
3582 if (is_hor_space[*bp]) {
3583 if (*bp != ' ' && *bp != '\t' && pedantic)
3584 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3585 bp++;
3586 } else if (*bp == '/') {
3587 if (bp[1] == '\\' && bp[2] == '\n')
3588 newline_fix (bp + 1);
3589 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3590 break;
3591 ip->bufp = bp + 2;
3592 skip_to_end_of_comment (ip, &ip->lineno, 0);
3593 bp = ip->bufp;
3594 } else if (*bp == '\\' && bp[1] == '\n') {
3595 bp += 2; ip->lineno++;
3596 } else break;
3599 /* Now find end of directive name.
3600 If we encounter a backslash-newline, exchange it with any following
3601 symbol-constituents so that we end up with a contiguous name. */
3603 cp = bp;
3604 while (1) {
3605 if (is_idchar[*cp])
3606 cp++;
3607 else {
3608 if (*cp == '\\' && cp[1] == '\n')
3609 name_newline_fix (cp);
3610 if (is_idchar[*cp])
3611 cp++;
3612 else break;
3615 ident_length = cp - bp;
3616 ident = bp;
3617 after_ident = cp;
3619 /* A line of just `#' becomes blank. */
3621 if (ident_length == 0 && *after_ident == '\n') {
3622 ip->bufp = after_ident;
3623 return 1;
3626 if (ident_length == 0 || !is_idstart[*ident]) {
3627 U_CHAR *p = ident;
3628 while (is_idchar[*p]) {
3629 if (*p < '0' || *p > '9')
3630 break;
3631 p++;
3633 /* Handle # followed by a line number. */
3634 if (p != ident && !is_idchar[*p]) {
3635 static struct directive line_directive_table[] = {
3636 { 4, do_line, "line", T_LINE},
3638 if (pedantic)
3639 pedwarn ("`#' followed by integer");
3640 after_ident = ident;
3641 kt = line_directive_table;
3642 goto old_linenum;
3645 /* Avoid error for `###' and similar cases unless -pedantic. */
3646 if (p == ident) {
3647 while (*p == '#' || is_hor_space[*p]) p++;
3648 if (*p == '\n') {
3649 if (pedantic && !lang_asm)
3650 warning ("invalid preprocessing directive");
3651 return 0;
3655 if (!lang_asm)
3656 error ("invalid preprocessing directive name");
3658 return 0;
3662 * Decode the keyword and call the appropriate expansion
3663 * routine, after moving the input pointer up to the next line.
3665 for (kt = directive_table; kt->length > 0; kt++) {
3666 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3667 register U_CHAR *buf;
3668 register U_CHAR *limit;
3669 int unterminated;
3670 int junk;
3671 int *already_output;
3673 /* Nonzero means do not delete comments within the directive.
3674 #define needs this when -traditional. */
3675 int keep_comments;
3677 old_linenum:
3679 limit = ip->buf + ip->length;
3680 unterminated = 0;
3681 already_output = 0;
3682 keep_comments = traditional && kt->type == T_DEFINE;
3683 /* #import is defined only in Objective C, or when on the NeXT. */
3684 if (kt->type == T_IMPORT
3685 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3686 break;
3688 /* Find the end of this directive (first newline not backslashed
3689 and not in a string or comment).
3690 Set COPY_DIRECTIVE if the directive must be copied
3691 (it contains a backslash-newline or a comment). */
3693 buf = bp = after_ident;
3694 while (bp < limit) {
3695 register U_CHAR c = *bp++;
3696 switch (c) {
3697 case '\\':
3698 if (bp < limit) {
3699 if (*bp == '\n') {
3700 ip->lineno++;
3701 copy_directive = 1;
3702 bp++;
3703 } else if (traditional)
3704 bp++;
3706 break;
3708 case '"':
3709 /* "..." is special for #include. */
3710 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3711 while (bp < limit && *bp != '\n') {
3712 if (*bp == '"') {
3713 bp++;
3714 break;
3716 if (*bp == '\\' && bp[1] == '\n') {
3717 ip->lineno++;
3718 copy_directive = 1;
3719 bp++;
3721 bp++;
3723 break;
3725 /* Fall through. */
3726 case '\'':
3727 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3728 /* Don't bother calling the directive if we already got an error
3729 message due to unterminated string. Skip everything and pretend
3730 we called the directive. */
3731 if (unterminated) {
3732 if (traditional) {
3733 /* Traditional preprocessing permits unterminated strings. */
3734 ip->bufp = bp;
3735 goto endloop1;
3737 ip->bufp = bp;
3738 return 1;
3740 break;
3742 /* <...> is special for #include. */
3743 case '<':
3744 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3745 break;
3746 while (bp < limit && *bp != '>' && *bp != '\n') {
3747 if (*bp == '\\' && bp[1] == '\n') {
3748 ip->lineno++;
3749 copy_directive = 1;
3750 bp++;
3752 bp++;
3754 break;
3756 case '/':
3757 if (*bp == '\\' && bp[1] == '\n')
3758 newline_fix (bp);
3759 if (*bp == '*'
3760 || (cplusplus_comments && *bp == '/')) {
3761 U_CHAR *obp = bp - 1;
3762 ip->bufp = bp + 1;
3763 skip_to_end_of_comment (ip, &ip->lineno, 0);
3764 bp = ip->bufp;
3765 /* No need to copy the directive because of a comment at the end;
3766 just don't include the comment in the directive. */
3767 if (!put_out_comments) {
3768 U_CHAR *p;
3769 for (p = bp; *p == ' ' || *p == '\t'; p++)
3770 continue;
3771 if (*p == '\n') {
3772 bp = obp;
3773 goto endloop1;
3776 /* Don't remove the comments if -traditional. */
3777 if (! keep_comments)
3778 copy_directive++;
3780 break;
3782 case '\f':
3783 case '\r':
3784 case '\v':
3785 if (pedantic)
3786 pedwarn ("%s in preprocessing directive", char_name[c]);
3787 break;
3789 case '\n':
3790 --bp; /* Point to the newline */
3791 ip->bufp = bp;
3792 goto endloop1;
3795 ip->bufp = bp;
3797 endloop1:
3798 resume_p = ip->bufp;
3799 /* BP is the end of the directive.
3800 RESUME_P is the next interesting data after the directive.
3801 A comment may come between. */
3803 /* If a directive should be copied through, and -C was given,
3804 pass it through before removing comments. */
3805 if (!no_output && put_out_comments
3806 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
3807 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3808 : kt->type == T_PRAGMA)) {
3809 int len;
3811 /* Output directive name. */
3812 check_expand (op, kt->length + 2);
3813 /* Make sure # is at the start of a line */
3814 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3815 op->lineno++;
3816 *op->bufp++ = '\n';
3818 *op->bufp++ = '#';
3819 bcopy (kt->name, op->bufp, kt->length);
3820 op->bufp += kt->length;
3822 /* Output arguments. */
3823 len = (bp - buf);
3824 check_expand (op, len);
3825 bcopy (buf, (char *) op->bufp, len);
3826 op->bufp += len;
3827 /* Take account of any (escaped) newlines just output. */
3828 while (--len >= 0)
3829 if (buf[len] == '\n')
3830 op->lineno++;
3832 already_output = &junk;
3833 } /* Don't we need a newline or #line? */
3835 if (copy_directive) {
3836 register U_CHAR *xp = buf;
3837 /* Need to copy entire directive into temp buffer before dispatching */
3839 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3840 some slop */
3841 buf = cp;
3843 /* Copy to the new buffer, deleting comments
3844 and backslash-newlines (and whitespace surrounding the latter). */
3846 while (xp < bp) {
3847 register U_CHAR c = *xp++;
3848 *cp++ = c;
3850 switch (c) {
3851 case '\n':
3852 abort (); /* A bare newline should never part of the line. */
3853 break;
3855 /* <...> is special for #include. */
3856 case '<':
3857 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3858 break;
3859 while (xp < bp && c != '>') {
3860 c = *xp++;
3861 if (c == '\\' && xp < bp && *xp == '\n')
3862 xp++;
3863 else
3864 *cp++ = c;
3866 break;
3868 case '\\':
3869 if (*xp == '\n') {
3870 xp++;
3871 cp--;
3872 if (cp != buf && is_hor_space[cp[-1]]) {
3873 while (cp - 1 != buf && is_hor_space[cp[-2]])
3874 cp--;
3875 SKIP_WHITE_SPACE (xp);
3876 } else if (is_hor_space[*xp]) {
3877 *cp++ = *xp++;
3878 SKIP_WHITE_SPACE (xp);
3880 } else if (traditional && xp < bp) {
3881 *cp++ = *xp++;
3883 break;
3885 case '\'':
3886 case '\"':
3888 register U_CHAR *bp1
3889 = skip_quoted_string (xp - 1, bp, ip->lineno,
3890 NULL_PTR, NULL_PTR, NULL_PTR);
3891 while (xp != bp1)
3892 *cp++ = *xp++;
3894 break;
3896 case '/':
3897 if (*xp == '*'
3898 || (cplusplus_comments && *xp == '/')) {
3899 ip->bufp = xp + 1;
3900 /* If we already copied the directive through,
3901 already_output != 0 prevents outputting comment now. */
3902 skip_to_end_of_comment (ip, already_output, 0);
3903 if (keep_comments)
3904 while (xp != ip->bufp)
3905 *cp++ = *xp++;
3906 /* Delete or replace the slash. */
3907 else if (traditional)
3908 cp--;
3909 else
3910 cp[-1] = ' ';
3911 xp = ip->bufp;
3916 /* Null-terminate the copy. */
3918 *cp = 0;
3919 } else
3920 cp = bp;
3922 ip->bufp = resume_p;
3924 /* Some directives should be written out for cc1 to process,
3925 just as if they were not defined. And sometimes we're copying
3926 directives through. */
3928 if (!no_output && already_output == 0
3929 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
3930 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3931 : kt->type == T_PRAGMA)) {
3932 int len;
3934 /* Output directive name. */
3935 check_expand (op, kt->length + 1);
3936 *op->bufp++ = '#';
3937 bcopy (kt->name, (char *) op->bufp, kt->length);
3938 op->bufp += kt->length;
3940 if (kt->type == T_DEFINE && dump_macros == dump_names) {
3941 /* Output `#define name' only. */
3942 U_CHAR *xp = buf;
3943 U_CHAR *yp;
3944 SKIP_WHITE_SPACE (xp);
3945 yp = xp;
3946 while (is_idchar[*xp]) xp++;
3947 len = (xp - yp);
3948 check_expand (op, len + 1);
3949 *op->bufp++ = ' ';
3950 bcopy (yp, (char *) op->bufp, len);
3951 } else {
3952 /* Output entire directive. */
3953 len = (cp - buf);
3954 check_expand (op, len);
3955 bcopy (buf, (char *) op->bufp, len);
3957 op->bufp += len;
3958 } /* Don't we need a newline or #line? */
3960 /* Call the appropriate directive handler. buf now points to
3961 either the appropriate place in the input buffer, or to
3962 the temp buffer if it was necessary to make one. cp
3963 points to the first char after the contents of the (possibly
3964 copied) directive, in either case. */
3965 (*kt->func) (buf, cp, op, kt);
3966 check_expand (op, ip->length - (ip->bufp - ip->buf));
3968 return 1;
3972 /* It is deliberate that we don't warn about undefined directives.
3973 That is the responsibility of cc1. */
3974 return 0;
3977 static struct tm *
3978 timestamp ()
3980 static struct tm *timebuf;
3981 if (!timebuf) {
3982 time_t t = time ((time_t *) 0);
3983 timebuf = localtime (&t);
3985 return timebuf;
3988 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3989 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3993 * expand things like __FILE__. Place the expansion into the output
3994 * buffer *without* rescanning.
3997 static void
3998 special_symbol (hp, op)
3999 HASHNODE *hp;
4000 FILE_BUF *op;
4002 char *buf;
4003 int i, len;
4004 int true_indepth;
4005 FILE_BUF *ip = NULL;
4006 struct tm *timebuf;
4008 int paren = 0; /* For special `defined' keyword */
4010 if (pcp_outfile && pcp_inside_if
4011 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4012 error ("Predefined macro `%s' used inside `#if' during precompilation",
4013 hp->name);
4015 for (i = indepth; i >= 0; i--)
4016 if (instack[i].fname != NULL) {
4017 ip = &instack[i];
4018 break;
4020 if (ip == NULL) {
4021 error ("cccp error: not in any file?!");
4022 return; /* the show must go on */
4025 switch (hp->type) {
4026 case T_FILE:
4027 case T_BASE_FILE:
4029 char *string;
4030 if (hp->type == T_FILE)
4031 string = ip->nominal_fname;
4032 else
4033 string = instack[0].nominal_fname;
4035 if (string)
4037 buf = (char *) alloca (3 + 4 * strlen (string));
4038 quote_string (buf, string);
4040 else
4041 buf = "\"\"";
4043 break;
4046 case T_INCLUDE_LEVEL:
4047 true_indepth = 0;
4048 for (i = indepth; i >= 0; i--)
4049 if (instack[i].fname != NULL)
4050 true_indepth++;
4052 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4053 sprintf (buf, "%d", true_indepth - 1);
4054 break;
4056 case T_VERSION:
4057 buf = (char *) alloca (3 + strlen (version_string));
4058 sprintf (buf, "\"%s\"", version_string);
4059 break;
4061 #ifndef NO_BUILTIN_SIZE_TYPE
4062 case T_SIZE_TYPE:
4063 buf = SIZE_TYPE;
4064 break;
4065 #endif
4067 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4068 case T_PTRDIFF_TYPE:
4069 buf = PTRDIFF_TYPE;
4070 break;
4071 #endif
4073 case T_WCHAR_TYPE:
4074 buf = wchar_type;
4075 break;
4077 case T_USER_LABEL_PREFIX_TYPE:
4078 buf = USER_LABEL_PREFIX;
4079 break;
4081 case T_REGISTER_PREFIX_TYPE:
4082 buf = REGISTER_PREFIX;
4083 break;
4085 case T_IMMEDIATE_PREFIX_TYPE:
4086 buf = IMMEDIATE_PREFIX;
4087 break;
4089 case T_CONST:
4090 buf = hp->value.cpval;
4091 #ifdef STDC_0_IN_SYSTEM_HEADERS
4092 if (ip->system_header_p
4093 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4094 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4095 buf = "0";
4096 #endif
4097 if (pcp_inside_if && pcp_outfile)
4098 /* Output a precondition for this macro use */
4099 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4100 break;
4102 case T_SPECLINE:
4103 buf = (char *) alloca (10);
4104 sprintf (buf, "%d", ip->lineno);
4105 break;
4107 case T_DATE:
4108 case T_TIME:
4109 buf = (char *) alloca (20);
4110 timebuf = timestamp ();
4111 if (hp->type == T_DATE)
4112 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4113 timebuf->tm_mday, timebuf->tm_year + 1900);
4114 else
4115 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4116 timebuf->tm_sec);
4117 break;
4119 case T_SPEC_DEFINED:
4120 buf = " 0 "; /* Assume symbol is not defined */
4121 ip = &instack[indepth];
4122 SKIP_WHITE_SPACE (ip->bufp);
4123 if (*ip->bufp == '(') {
4124 paren++;
4125 ip->bufp++; /* Skip over the paren */
4126 SKIP_WHITE_SPACE (ip->bufp);
4129 if (!is_idstart[*ip->bufp])
4130 goto oops;
4131 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4132 goto oops;
4133 if ((hp = lookup (ip->bufp, -1, -1))) {
4134 if (pcp_outfile && pcp_inside_if
4135 && (hp->type == T_CONST
4136 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4137 /* Output a precondition for this macro use. */
4138 fprintf (pcp_outfile, "#define %s\n", hp->name);
4139 buf = " 1 ";
4141 else
4142 if (pcp_outfile && pcp_inside_if) {
4143 /* Output a precondition for this macro use */
4144 U_CHAR *cp = ip->bufp;
4145 fprintf (pcp_outfile, "#undef ");
4146 while (is_idchar[*cp]) /* Ick! */
4147 fputc (*cp++, pcp_outfile);
4148 putc ('\n', pcp_outfile);
4150 while (is_idchar[*ip->bufp])
4151 ++ip->bufp;
4152 SKIP_WHITE_SPACE (ip->bufp);
4153 if (paren) {
4154 if (*ip->bufp != ')')
4155 goto oops;
4156 ++ip->bufp;
4158 break;
4160 oops:
4162 error ("`defined' without an identifier");
4163 break;
4165 default:
4166 error ("cccp error: invalid special hash type"); /* time for gdb */
4167 abort ();
4169 len = strlen (buf);
4170 check_expand (op, len);
4171 bcopy (buf, (char *) op->bufp, len);
4172 op->bufp += len;
4174 return;
4178 /* Routines to handle #directives */
4180 /* Handle #include and #import.
4181 This function expects to see "fname" or <fname> on the input. */
4183 static int
4184 do_include (buf, limit, op, keyword)
4185 U_CHAR *buf, *limit;
4186 FILE_BUF *op;
4187 struct directive *keyword;
4189 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4190 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4191 static int import_warning = 0;
4192 char *fname; /* Dynamically allocated fname buffer */
4193 char *pcftry;
4194 char *pcfname;
4195 char *fbeg, *fend; /* Beginning and end of fname */
4196 U_CHAR *fin;
4198 struct file_name_list *search_start = include; /* Chain of dirs to search */
4199 struct file_name_list *dsp; /* First in chain, if #include "..." */
4200 struct file_name_list *searchptr = 0;
4201 size_t flen;
4203 int f = -3; /* file number */
4204 struct include_file *inc = 0;
4206 int retried = 0; /* Have already tried macro
4207 expanding the include line*/
4208 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4209 #ifdef VMS
4210 int vaxc_include = 0; /* 1 for token without punctuation */
4211 #endif
4212 int pcf = -1;
4213 char *pcfbuf;
4214 char *pcfbuflimit;
4215 int pcfnum;
4217 if (pedantic && !instack[indepth].system_header_p)
4219 if (importing)
4220 pedwarn ("ANSI C does not allow `#import'");
4221 if (skip_dirs)
4222 pedwarn ("ANSI C does not allow `#include_next'");
4225 if (importing && warn_import && !inhibit_warnings
4226 && !instack[indepth].system_header_p && !import_warning) {
4227 import_warning = 1;
4228 warning ("using `#import' is not recommended");
4229 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4230 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4231 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4232 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4233 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4234 fprintf (stderr, " ... <real contents of file> ...\n");
4235 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4236 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4237 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4238 fprintf (stderr, "when it is equipped with such a conditional.\n");
4241 get_filename:
4243 fin = buf;
4244 SKIP_WHITE_SPACE (fin);
4245 /* Discard trailing whitespace so we can easily see
4246 if we have parsed all the significant chars we were given. */
4247 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4248 fbeg = fend = (char *) alloca (limit - fin);
4250 switch (*fin++) {
4251 case '\"':
4253 FILE_BUF *fp;
4254 /* Copy the operand text, concatenating the strings. */
4256 for (;;) {
4257 for (;;) {
4258 if (fin == limit)
4259 goto invalid_include_file_name;
4260 *fend = *fin++;
4261 if (*fend == '"')
4262 break;
4263 fend++;
4265 if (fin == limit)
4266 break;
4267 /* If not at the end, there had better be another string. */
4268 /* Skip just horiz space, and don't go past limit. */
4269 while (fin != limit && is_hor_space[*fin]) fin++;
4270 if (fin != limit && *fin == '\"')
4271 fin++;
4272 else
4273 goto fail;
4277 /* We have "filename". Figure out directory this source
4278 file is coming from and put it on the front of the list. */
4280 /* If -I- was specified, don't search current dir, only spec'd ones. */
4281 if (ignore_srcdir) break;
4283 for (fp = &instack[indepth]; fp >= instack; fp--)
4285 int n;
4286 char *nam;
4288 if ((nam = fp->nominal_fname) != NULL) {
4289 /* Found a named file. Figure out dir of the file,
4290 and put it in front of the search list. */
4291 dsp = ((struct file_name_list *)
4292 alloca (sizeof (struct file_name_list) + strlen (nam)));
4293 strcpy (dsp->fname, nam);
4294 simplify_filename (dsp->fname);
4295 nam = base_name (dsp->fname);
4296 *nam = 0;
4297 /* But for efficiency's sake, do not insert the dir
4298 if it matches the search list's first dir. */
4299 dsp->next = search_start;
4300 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4301 search_start = dsp;
4302 n = nam - dsp->fname;
4303 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4304 max_include_len = n + INCLUDE_LEN_FUDGE;
4306 dsp[0].got_name_map = 0;
4307 break;
4310 break;
4313 case '<':
4314 while (fin != limit && *fin != '>')
4315 *fend++ = *fin++;
4316 if (*fin == '>' && fin + 1 == limit) {
4317 angle_brackets = 1;
4318 /* If -I-, start with the first -I dir after the -I-. */
4319 search_start = first_bracket_include;
4320 break;
4322 goto fail;
4324 default:
4325 #ifdef VMS
4327 * Support '#include xyz' like VAX-C to allow for easy use of all the
4328 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4329 * code from case '<' is repeated here) and generates a warning.
4330 * (Note: macro expansion of `xyz' takes precedence.)
4332 if (retried && isalpha(*(U_CHAR *) (--fbeg))) {
4333 while (fin != limit && (!isspace(*fin)))
4334 *fend++ = *fin++;
4335 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4336 vaxc_include = 1;
4337 if (fin == limit) {
4338 angle_brackets = 1;
4339 /* If -I-, start with the first -I dir after the -I-. */
4340 search_start = first_bracket_include;
4341 break;
4344 #endif
4346 fail:
4347 if (! retried) {
4348 /* Expand buffer and then remove any newline markers.
4349 We can't just tell expand_to_temp_buffer to omit the markers,
4350 since it would put extra spaces in include file names. */
4351 FILE_BUF trybuf;
4352 U_CHAR *src;
4353 int errors_before_expansion = errors;
4354 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4355 if (errors != errors_before_expansion) {
4356 free (trybuf.buf);
4357 goto invalid_include_file_name;
4359 src = trybuf.buf;
4360 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4361 limit = buf;
4362 while (src != trybuf.bufp) {
4363 switch ((*limit++ = *src++)) {
4364 case '\n':
4365 limit--;
4366 src++;
4367 break;
4369 case '\'':
4370 case '\"':
4372 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4373 NULL_PTR, NULL_PTR, NULL_PTR);
4374 while (src != src1)
4375 *limit++ = *src++;
4377 break;
4380 *limit = 0;
4381 free (trybuf.buf);
4382 retried = 1;
4383 goto get_filename;
4386 invalid_include_file_name:
4387 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4388 return 0;
4391 /* For #include_next, skip in the search path
4392 past the dir in which the containing file was found. */
4393 if (skip_dirs) {
4394 FILE_BUF *fp;
4395 for (fp = &instack[indepth]; fp >= instack; fp--)
4396 if (fp->fname != NULL) {
4397 /* fp->dir is null if the containing file was specified
4398 with an absolute file name. In that case, don't skip anything. */
4399 if (fp->dir)
4400 search_start = fp->dir->next;
4401 break;
4405 *fend = 0;
4406 flen = simplify_filename (fbeg);
4408 if (flen == 0)
4410 error ("empty file name in `#%s'", keyword->name);
4411 return 0;
4414 /* Allocate this permanently, because it gets stored in the definitions
4415 of macros. */
4416 fname = xmalloc (max_include_len + flen + 1);
4417 /* + 1 above for terminating null. */
4419 system_include_depth += angle_brackets;
4421 /* If specified file name is absolute, just open it. */
4423 if (absolute_filename (fbeg)) {
4424 strcpy (fname, fbeg);
4425 f = open_include_file (fname, NULL_PTR, importing, &inc);
4426 } else {
4428 struct bypass_dir {
4429 struct bypass_dir *next;
4430 char *fname;
4431 struct file_name_list *searchptr;
4432 } **bypass_slot = 0;
4434 /* Search directory path, trying to open the file.
4435 Copy each filename tried into FNAME. */
4437 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4439 if (searchptr == first_bracket_include) {
4440 /* Go to bypass directory if we know we've seen this file before. */
4441 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4442 struct bypass_dir *p;
4443 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4444 INCLUDE_HASHSIZE)];
4445 for (p = *bypass_slot; p; p = p->next)
4446 if (!strcmp (fbeg, p->fname)) {
4447 searchptr = p->searchptr;
4448 bypass_slot = 0;
4449 break;
4453 strcpy (fname, searchptr->fname);
4454 strcat (fname, fbeg);
4455 #ifdef VMS
4456 /* Change this 1/2 Unix 1/2 VMS file specification into a
4457 full VMS file specification */
4458 if (searchptr->fname[0]) {
4459 /* Fix up the filename */
4460 hack_vms_include_specification (fname, vaxc_include);
4461 } else {
4462 /* This is a normal VMS filespec, so use it unchanged. */
4463 strcpy (fname, fbeg);
4464 /* if it's '#include filename', add the missing .h */
4465 if (vaxc_include && index(fname,'.')==NULL) {
4466 strcat (fname, ".h");
4469 #endif /* VMS */
4470 f = open_include_file (fname, searchptr, importing, &inc);
4471 if (f != -1) {
4472 if (bypass_slot && searchptr != first_bracket_include) {
4473 /* This is the first time we found this include file,
4474 and we found it after first_bracket_include.
4475 Record its location so that we can bypass to here next time. */
4476 struct bypass_dir *p
4477 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4478 p->next = *bypass_slot;
4479 p->fname = fname + strlen (searchptr->fname);
4480 p->searchptr = searchptr;
4481 *bypass_slot = p;
4483 break;
4485 #ifdef VMS
4486 /* Our VMS hacks can produce invalid filespecs, so don't worry
4487 about errors other than EACCES. */
4488 if (errno == EACCES)
4489 break;
4490 #else
4491 if (errno != ENOENT && errno != ENOTDIR)
4492 break;
4493 #endif
4498 if (f < 0) {
4500 if (f == -2) {
4501 /* The file was already included. */
4503 /* If generating dependencies and -MG was specified, we assume missing
4504 files are leaf files, living in the same directory as the source file
4505 or other similar place; these missing files may be generated from
4506 other files and may not exist yet (eg: y.tab.h). */
4507 } else if (print_deps_missing_files
4508 && (system_include_depth != 0) < print_deps)
4510 /* If it was requested as a system header file,
4511 then assume it belongs in the first place to look for such. */
4512 if (angle_brackets)
4514 if (search_start) {
4515 char *p = (char *) alloca (strlen (search_start->fname)
4516 + strlen (fbeg) + 1);
4517 strcpy (p, search_start->fname);
4518 strcat (p, fbeg);
4519 deps_output (p, ' ');
4522 else
4524 /* Otherwise, omit the directory, as if the file existed
4525 in the directory with the source. */
4526 deps_output (fbeg, ' ');
4529 /* If -M was specified, and this header file won't be added to the
4530 dependency list, then don't count this as an error, because we can
4531 still produce correct output. Otherwise, we can't produce correct
4532 output, because there may be dependencies we need inside the missing
4533 file, and we don't know what directory this missing file exists in. */
4534 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4535 warning ("No include path in which to find %s", fbeg);
4536 else if (f != -3)
4537 error_from_errno (fbeg);
4538 else
4539 error ("No include path in which to find %s", fbeg);
4541 } else {
4543 /* Actually process the file. */
4545 pcftry = (char *) alloca (strlen (fname) + 30);
4546 pcfbuf = 0;
4547 pcfnum = 0;
4549 if (!no_precomp)
4551 do {
4552 sprintf (pcftry, "%s%d", fname, pcfnum++);
4554 pcf = open (pcftry, O_RDONLY, 0666);
4555 if (pcf != -1)
4557 struct stat s;
4559 if (fstat (pcf, &s) != 0)
4560 pfatal_with_name (pcftry);
4561 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4562 || inc->st.st_dev != s.st_dev)
4564 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4565 /* Don't need it any more. */
4566 close (pcf);
4568 else
4570 /* Don't need it at all. */
4571 close (pcf);
4572 break;
4575 } while (pcf != -1 && !pcfbuf);
4578 /* Actually process the file */
4579 if (pcfbuf) {
4580 pcfname = xmalloc (strlen (pcftry) + 1);
4581 strcpy (pcfname, pcftry);
4582 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4583 (U_CHAR *) fname, op);
4585 else
4586 finclude (f, inc, op, is_system_include (fname), searchptr);
4589 system_include_depth -= angle_brackets;
4591 return 0;
4594 /* Return nonzero if the given FILENAME is an absolute pathname which
4595 designates a file within one of the known "system" include file
4596 directories. We assume here that if the given FILENAME looks like
4597 it is the name of a file which resides either directly in a "system"
4598 include file directory, or within any subdirectory thereof, then the
4599 given file must be a "system" include file. This function tells us
4600 if we should suppress pedantic errors/warnings for the given FILENAME.
4602 The value is 2 if the file is a C-language system header file
4603 for which C++ should (on most systems) assume `extern "C"'. */
4605 static int
4606 is_system_include (filename)
4607 register char *filename;
4609 struct file_name_list *searchptr;
4611 for (searchptr = first_system_include; searchptr;
4612 searchptr = searchptr->next)
4613 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4614 return searchptr->c_system_include_path + 1;
4615 return 0;
4618 /* Yield the non-directory suffix of a file name. */
4620 static char *
4621 base_name (fname)
4622 char *fname;
4624 char *s = fname;
4625 char *p;
4626 #if defined (__MSDOS__) || defined (_WIN32)
4627 if (isalpha (s[0]) && s[1] == ':') s += 2;
4628 #endif
4629 #ifdef VMS
4630 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4631 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4632 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4633 if (s != fname)
4634 return s;
4635 #endif
4636 if ((p = rindex (s, '/'))) s = p + 1;
4637 #ifdef DIR_SEPARATOR
4638 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4639 #endif
4640 return s;
4643 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4645 static int
4646 absolute_filename (filename)
4647 char *filename;
4649 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4650 if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4651 #endif
4652 #if defined (__CYGWIN32__)
4653 /* At present, any path that begins with a drive spec is absolute. */
4654 if (isalpha (filename[0]) && filename[1] == ':') return 1;
4655 #endif
4656 if (filename[0] == '/') return 1;
4657 #ifdef DIR_SEPARATOR
4658 if (filename[0] == DIR_SEPARATOR) return 1;
4659 #endif
4660 return 0;
4663 /* Remove unnecessary characters from FILENAME in place,
4664 to avoid unnecessary filename aliasing.
4665 Return the length of the resulting string.
4667 Do only the simplifications allowed by Posix.
4668 It is OK to miss simplifications on non-Posix hosts,
4669 since this merely leads to suboptimal results. */
4671 static size_t
4672 simplify_filename (filename)
4673 char *filename;
4675 register char *from = filename;
4676 register char *to = filename;
4677 char *to0;
4679 /* Remove redundant initial /s. */
4680 if (*from == '/') {
4681 *to++ = '/';
4682 if (*++from == '/') {
4683 if (*++from == '/') {
4684 /* 3 or more initial /s are equivalent to 1 /. */
4685 while (*++from == '/')
4686 continue;
4687 } else {
4688 /* On some hosts // differs from /; Posix allows this. */
4689 static int slashslash_vs_slash;
4690 if (slashslash_vs_slash == 0) {
4691 struct stat s1, s2;
4692 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4693 && INO_T_EQ (s1.st_ino, s2.st_ino)
4694 && s1.st_dev == s2.st_dev)
4695 ? 1 : -1);
4697 if (slashslash_vs_slash < 0)
4698 *to++ = '/';
4702 to0 = to;
4704 for (;;) {
4705 if (from[0] == '.' && from[1] == '/')
4706 from += 2;
4707 else {
4708 /* Copy this component and trailing /, if any. */
4709 while ((*to++ = *from++) != '/') {
4710 if (!to[-1]) {
4711 /* Trim . component at end of nonempty name. */
4712 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4714 /* Trim unnecessary trailing /s. */
4715 while (to0 < --to && to[-1] == '/')
4716 continue;
4718 *to = 0;
4719 return to - filename;
4724 /* Skip /s after a /. */
4725 while (*from == '/')
4726 from++;
4730 /* The file_name_map structure holds a mapping of file names for a
4731 particular directory. This mapping is read from the file named
4732 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4733 map filenames on a file system with severe filename restrictions,
4734 such as DOS. The format of the file name map file is just a series
4735 of lines with two tokens on each line. The first token is the name
4736 to map, and the second token is the actual name to use. */
4738 struct file_name_map
4740 struct file_name_map *map_next;
4741 char *map_from;
4742 char *map_to;
4745 #define FILE_NAME_MAP_FILE "header.gcc"
4747 /* Read a space delimited string of unlimited length from a stdio
4748 file. */
4750 static char *
4751 read_filename_string (ch, f)
4752 int ch;
4753 FILE *f;
4755 char *alloc, *set;
4756 int len;
4758 len = 20;
4759 set = alloc = xmalloc (len + 1);
4760 if (! is_space[ch])
4762 *set++ = ch;
4763 while ((ch = getc (f)) != EOF && ! is_space[ch])
4765 if (set - alloc == len)
4767 len *= 2;
4768 alloc = xrealloc (alloc, len + 1);
4769 set = alloc + len / 2;
4771 *set++ = ch;
4774 *set = '\0';
4775 ungetc (ch, f);
4776 return alloc;
4779 /* Read the file name map file for DIRNAME.
4780 If DIRNAME is empty, read the map file for the working directory;
4781 otherwise DIRNAME must end in '/'. */
4783 static struct file_name_map *
4784 read_name_map (dirname)
4785 char *dirname;
4787 /* This structure holds a linked list of file name maps, one per
4788 directory. */
4789 struct file_name_map_list
4791 struct file_name_map_list *map_list_next;
4792 char *map_list_name;
4793 struct file_name_map *map_list_map;
4795 static struct file_name_map_list *map_list;
4796 register struct file_name_map_list *map_list_ptr;
4797 char *name;
4798 FILE *f;
4799 size_t dirlen;
4801 for (map_list_ptr = map_list; map_list_ptr;
4802 map_list_ptr = map_list_ptr->map_list_next)
4803 if (! strcmp (map_list_ptr->map_list_name, dirname))
4804 return map_list_ptr->map_list_map;
4806 map_list_ptr = ((struct file_name_map_list *)
4807 xmalloc (sizeof (struct file_name_map_list)));
4808 map_list_ptr->map_list_name = savestring (dirname);
4809 map_list_ptr->map_list_map = NULL;
4811 dirlen = strlen (dirname);
4812 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4813 strcpy (name, dirname);
4814 strcat (name, FILE_NAME_MAP_FILE);
4815 f = fopen (name, "r");
4816 if (!f)
4817 map_list_ptr->map_list_map = NULL;
4818 else
4820 int ch;
4822 while ((ch = getc (f)) != EOF)
4824 char *from, *to;
4825 struct file_name_map *ptr;
4826 size_t tolen;
4828 if (is_space[ch])
4829 continue;
4830 from = read_filename_string (ch, f);
4831 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4833 to = read_filename_string (ch, f);
4835 simplify_filename (from);
4836 tolen = simplify_filename (to);
4838 ptr = ((struct file_name_map *)
4839 xmalloc (sizeof (struct file_name_map)));
4840 ptr->map_from = from;
4842 /* Make the real filename absolute. */
4843 if (absolute_filename (to))
4844 ptr->map_to = to;
4845 else
4847 ptr->map_to = xmalloc (dirlen + tolen + 1);
4848 strcpy (ptr->map_to, dirname);
4849 strcat (ptr->map_to, to);
4850 free (to);
4853 ptr->map_next = map_list_ptr->map_list_map;
4854 map_list_ptr->map_list_map = ptr;
4856 while ((ch = getc (f)) != '\n')
4857 if (ch == EOF)
4858 break;
4860 fclose (f);
4863 map_list_ptr->map_list_next = map_list;
4864 map_list = map_list_ptr;
4866 return map_list_ptr->map_list_map;
4869 /* Try to open include file FILENAME. SEARCHPTR is the directory
4870 being tried from the include file search path.
4871 IMPORTING is "" if we are importing, null otherwise.
4872 Return -2 if found, either a matching name or a matching inode.
4873 Otherwise, open the file and return a file descriptor if successful
4874 or -1 if unsuccessful.
4875 Unless unsuccessful, put a descriptor of the included file into *PINC.
4876 This function maps filenames on file systems based on information read by
4877 read_name_map. */
4879 static int
4880 open_include_file (filename, searchptr, importing, pinc)
4881 char *filename;
4882 struct file_name_list *searchptr;
4883 U_CHAR *importing;
4884 struct include_file **pinc;
4886 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
4887 int fd = -2;
4889 /* Look up FNAME in include_hashtab. */
4890 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4891 strlen (fname),
4892 INCLUDE_HASHSIZE)];
4893 struct include_file *inc, *head = *phead;
4894 for (inc = head; inc; inc = inc->next)
4895 if (!strcmp (fname, inc->fname))
4896 break;
4898 if (!inc
4899 || ! inc->control_macro
4900 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4902 fd = open (fname, O_RDONLY, 0);
4904 if (fd < 0)
4905 return fd;
4907 if (!inc) {
4908 /* FNAME was not in include_hashtab; insert a new entry. */
4909 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4910 inc->next = head;
4911 inc->fname = fname;
4912 inc->control_macro = 0;
4913 inc->deps_output = 0;
4914 if (fstat (fd, &inc->st) != 0)
4915 pfatal_with_name (fname);
4916 *phead = inc;
4918 /* Look for another file with the same inode and device. */
4919 if (lookup_ino_include (inc)
4920 && inc->control_macro
4921 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4922 close (fd);
4923 fd = -2;
4927 /* For -M, add this file to the dependencies. */
4928 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4929 inc->deps_output = 1;
4930 deps_output (fname, ' ');
4933 /* Handle -H option. */
4934 if (print_include_names)
4935 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4938 if (importing)
4939 inc->control_macro = importing;
4941 *pinc = inc;
4942 return fd;
4945 /* Return the remapped name of the the include file FILENAME.
4946 SEARCHPTR is the directory being tried from the include file path. */
4948 static char *
4949 remap_include_file (filename, searchptr)
4950 char *filename;
4951 struct file_name_list *searchptr;
4953 register struct file_name_map *map;
4954 register char *from;
4956 if (searchptr)
4958 if (! searchptr->got_name_map)
4960 searchptr->name_map = read_name_map (searchptr->fname);
4961 searchptr->got_name_map = 1;
4964 /* Check the mapping for the directory we are using. */
4965 from = filename + strlen (searchptr->fname);
4966 for (map = searchptr->name_map; map; map = map->map_next)
4967 if (! strcmp (map->map_from, from))
4968 return map->map_to;
4971 from = base_name (filename);
4973 if (from != filename || !searchptr)
4975 /* Try to find a mapping file for the particular directory we are
4976 looking in. Thus #include <sys/types.h> will look up sys/types.h
4977 in /usr/include/header.gcc and look up types.h in
4978 /usr/include/sys/header.gcc. */
4980 char *dir = (char *) alloca (from - filename + 1);
4981 bcopy (filename, dir, from - filename);
4982 dir[from - filename] = '\0';
4984 for (map = read_name_map (dir); map; map = map->map_next)
4985 if (! strcmp (map->map_from, from))
4986 return map->map_to;
4989 return filename;
4992 /* Insert INC into the include file table, hashed by device and inode number.
4993 If a file with different name but same dev+ino was already in the table,
4994 return 1 and set INC's control macro to the already-known macro. */
4996 static int
4997 lookup_ino_include (inc)
4998 struct include_file *inc;
5000 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5001 % INCLUDE_HASHSIZE);
5002 struct include_file *i = include_ino_hashtab[hash];
5003 inc->next_ino = i;
5004 include_ino_hashtab[hash] = inc;
5006 for (; i; i = i->next_ino)
5007 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5008 && inc->st.st_dev == i->st.st_dev) {
5009 inc->control_macro = i->control_macro;
5010 return 1;
5013 return 0;
5016 /* Process file descriptor F, which corresponds to include file INC,
5017 with output to OP.
5018 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5019 "system" include directories (as decided by the `is_system_include'
5020 function above).
5021 DIRPTR is the link in the dir path through which this file was found,
5022 or 0 if the file name was absolute. */
5024 static void
5025 finclude (f, inc, op, system_header_p, dirptr)
5026 int f;
5027 struct include_file *inc;
5028 FILE_BUF *op;
5029 int system_header_p;
5030 struct file_name_list *dirptr;
5032 char *fname = inc->fname;
5033 int i;
5034 FILE_BUF *fp; /* For input stack frame */
5035 int missing_newline = 0;
5037 CHECK_DEPTH (return;);
5039 fp = &instack[indepth + 1];
5040 bzero ((char *) fp, sizeof (FILE_BUF));
5041 fp->nominal_fname = fp->fname = fname;
5042 fp->inc = inc;
5043 fp->length = 0;
5044 fp->lineno = 1;
5045 fp->if_stack = if_stack;
5046 fp->system_header_p = system_header_p;
5047 fp->dir = dirptr;
5049 if (S_ISREG (inc->st.st_mode)) {
5050 size_t s = (size_t) inc->st.st_size;
5051 if (s != inc->st.st_size || s + 2 < s)
5052 memory_full ();
5053 fp->buf = (U_CHAR *) xmalloc (s + 2);
5054 fp->bufp = fp->buf;
5056 /* Read the file contents, knowing that s is an upper bound
5057 on the number of bytes we can read. */
5058 fp->length = safe_read (f, (char *) fp->buf, s);
5059 if (fp->length < 0) goto nope;
5061 else if (S_ISDIR (inc->st.st_mode)) {
5062 error ("directory `%s' specified in #include", fname);
5063 close (f);
5064 return;
5065 } else {
5066 /* Cannot count its file size before reading.
5067 First read the entire file into heap and
5068 copy them into buffer on stack. */
5070 int bsize = 2000;
5071 int st_size = 0;
5073 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5075 for (;;) {
5076 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5077 if (i < 0)
5078 goto nope; /* error! */
5079 st_size += i;
5080 if (st_size != bsize)
5081 break; /* End of file */
5082 bsize *= 2;
5083 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5085 fp->bufp = fp->buf;
5086 fp->length = st_size;
5089 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5090 /* Backslash-newline at end is not good enough. */
5091 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5092 fp->buf[fp->length++] = '\n';
5093 missing_newline = 1;
5095 fp->buf[fp->length] = '\0';
5097 /* Close descriptor now, so nesting does not use lots of descriptors. */
5098 close (f);
5100 /* Must do this before calling trigraph_pcp, so that the correct file name
5101 will be printed in warning messages. */
5103 indepth++;
5104 input_file_stack_tick++;
5106 if (!no_trigraphs)
5107 trigraph_pcp (fp);
5109 output_line_directive (fp, op, 0, enter_file);
5110 rescan (op, 0);
5112 if (missing_newline)
5113 fp->lineno--;
5115 if (pedantic && missing_newline)
5116 pedwarn ("file does not end in newline");
5118 indepth--;
5119 input_file_stack_tick++;
5120 output_line_directive (&instack[indepth], op, 0, leave_file);
5121 free (fp->buf);
5122 return;
5124 nope:
5126 perror_with_name (fname);
5127 close (f);
5128 free (fp->buf);
5131 /* Record that inclusion of the include file INC
5132 should be controlled by the macro named MACRO_NAME.
5133 This means that trying to include the file again
5134 will do something if that macro is defined. */
5136 static void
5137 record_control_macro (inc, macro_name)
5138 struct include_file *inc;
5139 U_CHAR *macro_name;
5141 if (!inc->control_macro || inc->control_macro[0])
5142 inc->control_macro = macro_name;
5145 /* Load the specified precompiled header into core, and verify its
5146 preconditions. PCF indicates the file descriptor to read, which must
5147 be a regular file. *ST is its file status.
5148 FNAME indicates the file name of the original header.
5149 *LIMIT will be set to an address one past the end of the file.
5150 If the preconditions of the file are not satisfied, the buffer is
5151 freed and we return 0. If the preconditions are satisfied, return
5152 the address of the buffer following the preconditions. The buffer, in
5153 this case, should never be freed because various pieces of it will
5154 be referred to until all precompiled strings are output at the end of
5155 the run. */
5157 static char *
5158 check_precompiled (pcf, st, fname, limit)
5159 int pcf;
5160 struct stat *st;
5161 char *fname;
5162 char **limit;
5164 int length = 0;
5165 char *buf;
5166 char *cp;
5168 if (pcp_outfile)
5169 return 0;
5171 if (S_ISREG (st->st_mode))
5173 size_t s = (size_t) st->st_size;
5174 if (s != st->st_size || s + 2 < s)
5175 memory_full ();
5176 buf = xmalloc (s + 2);
5177 length = safe_read (pcf, buf, s);
5178 if (length < 0)
5179 goto nope;
5181 else
5182 abort ();
5184 if (length > 0 && buf[length-1] != '\n')
5185 buf[length++] = '\n';
5186 buf[length] = '\0';
5188 *limit = buf + length;
5190 /* File is in core. Check the preconditions. */
5191 if (!check_preconditions (buf))
5192 goto nope;
5193 for (cp = buf; *cp; cp++)
5195 #ifdef DEBUG_PCP
5196 fprintf (stderr, "Using preinclude %s\n", fname);
5197 #endif
5198 return cp + 1;
5200 nope:
5201 #ifdef DEBUG_PCP
5202 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5203 #endif
5204 free (buf);
5205 return 0;
5208 /* PREC (null terminated) points to the preconditions of a
5209 precompiled header. These are a series of #define and #undef
5210 lines which must match the current contents of the hash
5211 table. */
5213 static int
5214 check_preconditions (prec)
5215 char *prec;
5217 MACRODEF mdef;
5218 char *lineend;
5220 while (*prec) {
5221 lineend = index (prec, '\n');
5223 if (*prec++ != '#') {
5224 error ("Bad format encountered while reading precompiled file");
5225 return 0;
5227 if (!strncmp (prec, "define", 6)) {
5228 HASHNODE *hp;
5230 prec += 6;
5231 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5233 if (mdef.defn == 0)
5234 abort ();
5236 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5237 || (hp->type != T_MACRO && hp->type != T_CONST)
5238 || (hp->type == T_MACRO
5239 && !compare_defs (mdef.defn, hp->value.defn)
5240 && (mdef.defn->length != 2
5241 || mdef.defn->expansion[0] != '\n'
5242 || mdef.defn->expansion[1] != ' ')))
5243 return 0;
5244 } else if (!strncmp (prec, "undef", 5)) {
5245 char *name;
5246 int len;
5248 prec += 5;
5249 while (is_hor_space[(U_CHAR) *prec])
5250 prec++;
5251 name = prec;
5252 while (is_idchar[(U_CHAR) *prec])
5253 prec++;
5254 len = prec - name;
5256 if (lookup ((U_CHAR *) name, len, -1))
5257 return 0;
5258 } else {
5259 error ("Bad format encountered while reading precompiled file");
5260 return 0;
5262 prec = lineend + 1;
5264 /* They all passed successfully */
5265 return 1;
5268 /* Process the main body of a precompiled file. BUF points to the
5269 string section of the file, following the preconditions. LIMIT is one
5270 character past the end. NAME is the name of the file being read
5271 in. OP is the main output buffer. */
5273 static void
5274 pcfinclude (buf, limit, name, op)
5275 U_CHAR *buf, *limit, *name;
5276 FILE_BUF *op;
5278 FILE_BUF tmpbuf;
5279 int nstrings;
5280 U_CHAR *cp = buf;
5282 /* First in the file comes 4 bytes indicating the number of strings, */
5283 /* in network byte order. (MSB first). */
5284 nstrings = *cp++;
5285 nstrings = (nstrings << 8) | *cp++;
5286 nstrings = (nstrings << 8) | *cp++;
5287 nstrings = (nstrings << 8) | *cp++;
5289 /* Looping over each string... */
5290 while (nstrings--) {
5291 U_CHAR *string_start;
5292 U_CHAR *endofthiskey;
5293 STRINGDEF *str;
5294 int nkeys;
5296 /* Each string starts with a STRINGDEF structure (str), followed */
5297 /* by the text of the string (string_start) */
5299 /* First skip to a longword boundary */
5300 /* ??? Why a 4-byte boundary? On all machines? */
5301 /* NOTE: This works correctly even if size_t
5302 is narrower than a pointer.
5303 Do not try risky measures here to get another type to use!
5304 Do not include stddef.h--it will fail! */
5305 if ((size_t) cp & 3)
5306 cp += 4 - ((size_t) cp & 3);
5308 /* Now get the string. */
5309 str = (STRINGDEF *) (GENERIC_PTR) cp;
5310 string_start = cp += sizeof (STRINGDEF);
5312 for (; *cp; cp++) /* skip the string */
5315 /* We need to macro expand the string here to ensure that the
5316 proper definition environment is in place. If it were only
5317 expanded when we find out it is needed, macros necessary for
5318 its proper expansion might have had their definitions changed. */
5319 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5320 /* Lineno is already set in the precompiled file */
5321 str->contents = tmpbuf.buf;
5322 str->len = tmpbuf.length;
5323 str->writeflag = 0;
5324 str->filename = name;
5325 str->output_mark = outbuf.bufp - outbuf.buf;
5327 str->chain = 0;
5328 *stringlist_tailp = str;
5329 stringlist_tailp = &str->chain;
5331 /* Next comes a fourbyte number indicating the number of keys
5332 for this string. */
5333 nkeys = *cp++;
5334 nkeys = (nkeys << 8) | *cp++;
5335 nkeys = (nkeys << 8) | *cp++;
5336 nkeys = (nkeys << 8) | *cp++;
5338 /* If this number is -1, then the string is mandatory. */
5339 if (nkeys == -1)
5340 str->writeflag = 1;
5341 else
5342 /* Otherwise, for each key, */
5343 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5344 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5345 HASHNODE *hp;
5347 /* It starts with a KEYDEF structure */
5348 cp += sizeof (KEYDEF);
5350 /* Find the end of the key. At the end of this for loop we
5351 advance CP to the start of the next key using this variable. */
5352 endofthiskey = cp + strlen ((char *) cp);
5353 kp->str = str;
5355 /* Expand the key, and enter it into the hash table. */
5356 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5357 tmpbuf.bufp = tmpbuf.buf;
5359 while (is_hor_space[*tmpbuf.bufp])
5360 tmpbuf.bufp++;
5361 if (!is_idstart[*tmpbuf.bufp]
5362 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5363 str->writeflag = 1;
5364 continue;
5367 hp = lookup (tmpbuf.bufp, -1, -1);
5368 if (hp == NULL) {
5369 kp->chain = 0;
5370 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5372 else if (hp->type == T_PCSTRING) {
5373 kp->chain = hp->value.keydef;
5374 hp->value.keydef = kp;
5376 else
5377 str->writeflag = 1;
5380 /* This output_line_directive serves to switch us back to the current
5381 input file in case some of these strings get output (which will
5382 result in line directives for the header file being output). */
5383 output_line_directive (&instack[indepth], op, 0, enter_file);
5386 /* Called from rescan when it hits a key for strings. Mark them all
5387 used and clean up. */
5389 static void
5390 pcstring_used (hp)
5391 HASHNODE *hp;
5393 KEYDEF *kp;
5395 for (kp = hp->value.keydef; kp; kp = kp->chain)
5396 kp->str->writeflag = 1;
5397 delete_macro (hp);
5400 /* Write the output, interspersing precompiled strings in their
5401 appropriate places. */
5403 static void
5404 write_output ()
5406 STRINGDEF *next_string;
5407 U_CHAR *cur_buf_loc;
5408 int line_directive_len = 80;
5409 char *line_directive = xmalloc (line_directive_len);
5410 int len;
5412 /* In each run through the loop, either cur_buf_loc ==
5413 next_string_loc, in which case we print a series of strings, or
5414 it is less than next_string_loc, in which case we write some of
5415 the buffer. */
5416 cur_buf_loc = outbuf.buf;
5417 next_string = stringlist;
5419 while (cur_buf_loc < outbuf.bufp || next_string) {
5420 if (next_string
5421 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5422 if (next_string->writeflag) {
5423 len = 4 * strlen ((char *) next_string->filename) + 32;
5424 while (len > line_directive_len)
5425 line_directive = xrealloc (line_directive,
5426 line_directive_len *= 2);
5427 sprintf (line_directive, "\n# %d ", next_string->lineno);
5428 strcpy (quote_string (line_directive + strlen (line_directive),
5429 (char *) next_string->filename),
5430 "\n");
5431 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5432 safe_write (fileno (stdout),
5433 (char *) next_string->contents, next_string->len);
5435 next_string = next_string->chain;
5437 else {
5438 len = (next_string
5439 ? (next_string->output_mark
5440 - (cur_buf_loc - outbuf.buf))
5441 : outbuf.bufp - cur_buf_loc);
5443 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5444 cur_buf_loc += len;
5447 free (line_directive);
5450 /* Pass a directive through to the output file.
5451 BUF points to the contents of the directive, as a contiguous string.
5452 LIMIT points to the first character past the end of the directive.
5453 KEYWORD is the keyword-table entry for the directive. */
5455 static void
5456 pass_thru_directive (buf, limit, op, keyword)
5457 U_CHAR *buf, *limit;
5458 FILE_BUF *op;
5459 struct directive *keyword;
5461 register unsigned keyword_length = keyword->length;
5463 check_expand (op, 1 + keyword_length + (limit - buf));
5464 *op->bufp++ = '#';
5465 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5466 op->bufp += keyword_length;
5467 if (limit != buf && buf[0] != ' ')
5468 *op->bufp++ = ' ';
5469 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5470 op->bufp += (limit - buf);
5471 #if 0
5472 *op->bufp++ = '\n';
5473 /* Count the line we have just made in the output,
5474 to get in sync properly. */
5475 op->lineno++;
5476 #endif
5479 /* The arglist structure is built by do_define to tell
5480 collect_definition where the argument names begin. That
5481 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5482 would contain pointers to the strings x, y, and z.
5483 Collect_definition would then build a DEFINITION node,
5484 with reflist nodes pointing to the places x, y, and z had
5485 appeared. So the arglist is just convenience data passed
5486 between these two routines. It is not kept around after
5487 the current #define has been processed and entered into the
5488 hash table. */
5490 struct arglist {
5491 struct arglist *next;
5492 U_CHAR *name;
5493 int length;
5494 int argno;
5495 char rest_args;
5498 /* Create a DEFINITION node from a #define directive. Arguments are
5499 as for do_define. */
5501 static MACRODEF
5502 create_definition (buf, limit, op)
5503 U_CHAR *buf, *limit;
5504 FILE_BUF *op;
5506 U_CHAR *bp; /* temp ptr into input buffer */
5507 U_CHAR *symname; /* remember where symbol name starts */
5508 int sym_length; /* and how long it is */
5509 int line = instack[indepth].lineno;
5510 char *file = instack[indepth].nominal_fname;
5511 int rest_args = 0;
5513 DEFINITION *defn;
5514 int arglengths = 0; /* Accumulate lengths of arg names
5515 plus number of args. */
5516 MACRODEF mdef;
5518 bp = buf;
5520 while (is_hor_space[*bp])
5521 bp++;
5523 symname = bp; /* remember where it starts */
5524 sym_length = check_macro_name (bp, "macro");
5525 bp += sym_length;
5527 /* Lossage will occur if identifiers or control keywords are broken
5528 across lines using backslash. This is not the right place to take
5529 care of that. */
5531 if (*bp == '(') {
5532 struct arglist *arg_ptrs = NULL;
5533 int argno = 0;
5535 bp++; /* skip '(' */
5536 SKIP_WHITE_SPACE (bp);
5538 /* Loop over macro argument names. */
5539 while (*bp != ')') {
5540 struct arglist *temp;
5542 temp = (struct arglist *) alloca (sizeof (struct arglist));
5543 temp->name = bp;
5544 temp->next = arg_ptrs;
5545 temp->argno = argno++;
5546 temp->rest_args = 0;
5547 arg_ptrs = temp;
5549 if (rest_args)
5550 pedwarn ("another parameter follows `%s'",
5551 rest_extension);
5553 if (!is_idstart[*bp])
5554 pedwarn ("invalid character in macro parameter name");
5556 /* Find the end of the arg name. */
5557 while (is_idchar[*bp]) {
5558 bp++;
5559 /* do we have a "special" rest-args extension here? */
5560 if (limit - bp > REST_EXTENSION_LENGTH
5561 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5562 rest_args = 1;
5563 temp->rest_args = 1;
5564 break;
5567 temp->length = bp - temp->name;
5568 if (rest_args == 1)
5569 bp += REST_EXTENSION_LENGTH;
5570 arglengths += temp->length + 2;
5571 SKIP_WHITE_SPACE (bp);
5572 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5573 error ("badly punctuated parameter list in `#define'");
5574 goto nope;
5576 if (*bp == ',') {
5577 bp++;
5578 SKIP_WHITE_SPACE (bp);
5579 /* A comma at this point can only be followed by an identifier. */
5580 if (!is_idstart[*bp]) {
5581 error ("badly punctuated parameter list in `#define'");
5582 goto nope;
5585 if (bp >= limit) {
5586 error ("unterminated parameter list in `#define'");
5587 goto nope;
5590 struct arglist *otemp;
5592 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5593 if (temp->length == otemp->length
5594 && bcmp (temp->name, otemp->name, temp->length) == 0) {
5595 error ("duplicate argument name `%.*s' in `#define'",
5596 temp->length, temp->name);
5597 goto nope;
5602 ++bp; /* skip paren */
5603 SKIP_WHITE_SPACE (bp);
5604 /* now everything from bp before limit is the definition. */
5605 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5606 defn->rest_args = rest_args;
5608 /* Now set defn->args.argnames to the result of concatenating
5609 the argument names in reverse order
5610 with comma-space between them. */
5611 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5613 struct arglist *temp;
5614 int i = 0;
5615 for (temp = arg_ptrs; temp; temp = temp->next) {
5616 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5617 i += temp->length;
5618 if (temp->next != 0) {
5619 defn->args.argnames[i++] = ',';
5620 defn->args.argnames[i++] = ' ';
5623 defn->args.argnames[i] = 0;
5625 } else {
5626 /* Simple expansion or empty definition. */
5628 if (bp < limit)
5630 if (is_hor_space[*bp]) {
5631 bp++;
5632 SKIP_WHITE_SPACE (bp);
5633 } else if (sym_length) {
5634 switch (*bp) {
5635 case '!': case '"': case '#': case '%': case '&': case '\'':
5636 case ')': case '*': case '+': case ',': case '-': case '.':
5637 case '/': case ':': case ';': case '<': case '=': case '>':
5638 case '?': case '[': case '\\': case ']': case '^': case '{':
5639 case '|': case '}': case '~':
5640 warning ("missing white space after `#define %.*s'",
5641 sym_length, symname);
5642 break;
5644 default:
5645 pedwarn ("missing white space after `#define %.*s'",
5646 sym_length, symname);
5647 break;
5651 /* Now everything from bp before limit is the definition. */
5652 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5653 defn->args.argnames = (U_CHAR *) "";
5656 defn->line = line;
5657 defn->file = file;
5659 /* OP is null if this is a predefinition */
5660 defn->predefined = !op;
5661 mdef.defn = defn;
5662 mdef.symnam = symname;
5663 mdef.symlen = sym_length;
5665 return mdef;
5667 nope:
5668 mdef.defn = 0;
5669 return mdef;
5672 /* Process a #define directive.
5673 BUF points to the contents of the #define directive, as a contiguous string.
5674 LIMIT points to the first character past the end of the definition.
5675 KEYWORD is the keyword-table entry for #define. */
5677 static int
5678 do_define (buf, limit, op, keyword)
5679 U_CHAR *buf, *limit;
5680 FILE_BUF *op;
5681 struct directive *keyword;
5683 int hashcode;
5684 MACRODEF mdef;
5686 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5687 if (pcp_outfile && op)
5688 pass_thru_directive (buf, limit, op, keyword);
5690 mdef = create_definition (buf, limit, op);
5691 if (mdef.defn == 0)
5692 goto nope;
5694 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5697 HASHNODE *hp;
5698 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5699 int ok = 0;
5700 /* Redefining a precompiled key is ok. */
5701 if (hp->type == T_PCSTRING)
5702 ok = 1;
5703 /* Redefining a macro is ok if the definitions are the same. */
5704 else if (hp->type == T_MACRO)
5705 ok = ! compare_defs (mdef.defn, hp->value.defn);
5706 /* Redefining a constant is ok with -D. */
5707 else if (hp->type == T_CONST)
5708 ok = ! done_initializing;
5709 /* Print the warning if it's not ok. */
5710 if (!ok) {
5711 /* If we are passing through #define and #undef directives, do
5712 that for this re-definition now. */
5713 if (debug_output && op)
5714 pass_thru_directive (buf, limit, op, keyword);
5716 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5717 if (hp->type == T_MACRO)
5718 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5719 "this is the location of the previous definition");
5721 /* Replace the old definition. */
5722 hp->type = T_MACRO;
5723 hp->value.defn = mdef.defn;
5724 } else {
5725 /* If we are passing through #define and #undef directives, do
5726 that for this new definition now. */
5727 if (debug_output && op)
5728 pass_thru_directive (buf, limit, op, keyword);
5729 install (mdef.symnam, mdef.symlen, T_MACRO,
5730 (char *) mdef.defn, hashcode);
5734 return 0;
5736 nope:
5738 return 1;
5741 /* Check a purported macro name SYMNAME, and yield its length.
5742 USAGE is the kind of name this is intended for. */
5744 static int
5745 check_macro_name (symname, usage)
5746 U_CHAR *symname;
5747 char *usage;
5749 U_CHAR *p;
5750 int sym_length;
5752 for (p = symname; is_idchar[*p]; p++)
5754 sym_length = p - symname;
5755 if (sym_length == 0
5756 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5757 error ("invalid %s name", usage);
5758 else if (!is_idstart[*symname]
5759 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5760 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5761 return sym_length;
5764 /* Return zero if two DEFINITIONs are isomorphic. */
5766 static int
5767 compare_defs (d1, d2)
5768 DEFINITION *d1, *d2;
5770 register struct reflist *a1, *a2;
5771 register U_CHAR *p1 = d1->expansion;
5772 register U_CHAR *p2 = d2->expansion;
5773 int first = 1;
5775 if (d1->nargs != d2->nargs)
5776 return 1;
5777 if (pedantic
5778 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5779 return 1;
5780 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5781 a1 = a1->next, a2 = a2->next) {
5782 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5783 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5784 || a1->argno != a2->argno
5785 || a1->stringify != a2->stringify
5786 || a1->raw_before != a2->raw_before
5787 || a1->raw_after != a2->raw_after)
5788 return 1;
5789 first = 0;
5790 p1 += a1->nchars;
5791 p2 += a2->nchars;
5793 if (a1 != a2)
5794 return 1;
5795 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5796 p2, d2->length - (p2 - d2->expansion), 1))
5797 return 1;
5798 return 0;
5801 /* Return 1 if two parts of two macro definitions are effectively different.
5802 One of the parts starts at BEG1 and has LEN1 chars;
5803 the other has LEN2 chars at BEG2.
5804 Any sequence of whitespace matches any other sequence of whitespace.
5805 FIRST means these parts are the first of a macro definition;
5806 so ignore leading whitespace entirely.
5807 LAST means these parts are the last of a macro definition;
5808 so ignore trailing whitespace entirely. */
5810 static int
5811 comp_def_part (first, beg1, len1, beg2, len2, last)
5812 int first;
5813 U_CHAR *beg1, *beg2;
5814 int len1, len2;
5815 int last;
5817 register U_CHAR *end1 = beg1 + len1;
5818 register U_CHAR *end2 = beg2 + len2;
5819 if (first) {
5820 while (beg1 != end1 && is_space[*beg1]) beg1++;
5821 while (beg2 != end2 && is_space[*beg2]) beg2++;
5823 if (last) {
5824 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5825 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5827 while (beg1 != end1 && beg2 != end2) {
5828 if (is_space[*beg1] && is_space[*beg2]) {
5829 while (beg1 != end1 && is_space[*beg1]) beg1++;
5830 while (beg2 != end2 && is_space[*beg2]) beg2++;
5831 } else if (*beg1 == *beg2) {
5832 beg1++; beg2++;
5833 } else break;
5835 return (beg1 != end1) || (beg2 != end2);
5838 /* Read a replacement list for a macro with parameters.
5839 Build the DEFINITION structure.
5840 Reads characters of text starting at BUF until END.
5841 ARGLIST specifies the formal parameters to look for
5842 in the text of the definition; NARGS is the number of args
5843 in that list, or -1 for a macro name that wants no argument list.
5844 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5845 and NAMELEN is its length in characters.
5847 Note that comments, backslash-newlines, and leading white space
5848 have already been deleted from the argument. */
5850 /* If there is no trailing whitespace, a Newline Space is added at the end
5851 to prevent concatenation that would be contrary to the standard. */
5853 static DEFINITION *
5854 collect_expansion (buf, end, nargs, arglist)
5855 U_CHAR *buf, *end;
5856 int nargs;
5857 struct arglist *arglist;
5859 DEFINITION *defn;
5860 register U_CHAR *p, *limit, *lastp, *exp_p;
5861 struct reflist *endpat = NULL;
5862 /* Pointer to first nonspace after last ## seen. */
5863 U_CHAR *concat = 0;
5864 /* Pointer to first nonspace after last single-# seen. */
5865 U_CHAR *stringify = 0;
5866 /* How those tokens were spelled. */
5867 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5868 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5869 int maxsize;
5870 int expected_delimiter = '\0';
5872 /* Scan thru the replacement list, ignoring comments and quoted
5873 strings, picking up on the macro calls. It does a linear search
5874 thru the arg list on every potential symbol. Profiling might say
5875 that something smarter should happen. */
5877 if (end < buf)
5878 abort ();
5880 /* Find the beginning of the trailing whitespace. */
5881 limit = end;
5882 p = buf;
5883 while (p < limit && is_space[limit[-1]]) limit--;
5885 /* Allocate space for the text in the macro definition.
5886 Each input char may or may not need 1 byte,
5887 so this is an upper bound.
5888 The extra 3 are for invented trailing newline-marker and final null. */
5889 maxsize = (sizeof (DEFINITION)
5890 + (limit - p) + 3);
5891 defn = (DEFINITION *) xcalloc (1, maxsize);
5893 defn->nargs = nargs;
5894 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5895 lastp = exp_p;
5897 if (p[0] == '#'
5898 ? p[1] == '#'
5899 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5900 error ("`##' at start of macro definition");
5901 p += p[0] == '#' ? 2 : 4;
5904 /* Process the main body of the definition. */
5905 while (p < limit) {
5906 int skipped_arg = 0;
5907 register U_CHAR c = *p++;
5909 *exp_p++ = c;
5911 if (!traditional) {
5912 switch (c) {
5913 case '\'':
5914 case '\"':
5915 if (expected_delimiter != '\0') {
5916 if (c == expected_delimiter)
5917 expected_delimiter = '\0';
5918 } else
5919 expected_delimiter = c;
5920 break;
5922 case '\\':
5923 if (p < limit && expected_delimiter) {
5924 /* In a string, backslash goes through
5925 and makes next char ordinary. */
5926 *exp_p++ = *p++;
5928 break;
5930 case '%':
5931 if (!expected_delimiter && *p == ':') {
5932 /* %: is not a digraph if preceded by an odd number of '<'s. */
5933 U_CHAR *p0 = p - 1;
5934 while (buf < p0 && p0[-1] == '<')
5935 p0--;
5936 if ((p - p0) & 1) {
5937 /* Treat %:%: as ## and %: as #. */
5938 if (p[1] == '%' && p[2] == ':') {
5939 p += 2;
5940 goto sharp_sharp_token;
5942 if (nargs >= 0) {
5943 p++;
5944 goto sharp_token;
5948 break;
5950 case '#':
5951 /* # is ordinary inside a string. */
5952 if (expected_delimiter)
5953 break;
5954 if (*p == '#') {
5955 sharp_sharp_token:
5956 /* ##: concatenate preceding and following tokens. */
5957 /* Take out the first #, discard preceding whitespace. */
5958 exp_p--;
5959 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5960 --exp_p;
5961 /* Skip the second #. */
5962 p++;
5963 concat_sharp_token_type = c;
5964 if (is_hor_space[*p]) {
5965 concat_sharp_token_type = c + 1;
5966 p++;
5967 SKIP_WHITE_SPACE (p);
5969 concat = p;
5970 if (p == limit)
5971 error ("`##' at end of macro definition");
5972 } else if (nargs >= 0) {
5973 /* Single #: stringify following argument ref.
5974 Don't leave the # in the expansion. */
5975 sharp_token:
5976 exp_p--;
5977 stringify_sharp_token_type = c;
5978 if (is_hor_space[*p]) {
5979 stringify_sharp_token_type = c + 1;
5980 p++;
5981 SKIP_WHITE_SPACE (p);
5983 if (! is_idstart[*p] || nargs == 0
5984 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
5985 error ("`#' operator is not followed by a macro argument name");
5986 else
5987 stringify = p;
5989 break;
5991 } else {
5992 /* In -traditional mode, recognize arguments inside strings and
5993 and character constants, and ignore special properties of #.
5994 Arguments inside strings are considered "stringified", but no
5995 extra quote marks are supplied. */
5996 switch (c) {
5997 case '\'':
5998 case '\"':
5999 if (expected_delimiter != '\0') {
6000 if (c == expected_delimiter)
6001 expected_delimiter = '\0';
6002 } else
6003 expected_delimiter = c;
6004 break;
6006 case '\\':
6007 /* Backslash quotes delimiters and itself, but not macro args. */
6008 if (expected_delimiter != 0 && p < limit
6009 && (*p == expected_delimiter || *p == '\\')) {
6010 *exp_p++ = *p++;
6011 continue;
6013 break;
6015 case '/':
6016 if (expected_delimiter != '\0') /* No comments inside strings. */
6017 break;
6018 if (*p == '*') {
6019 /* If we find a comment that wasn't removed by handle_directive,
6020 this must be -traditional. So replace the comment with
6021 nothing at all. */
6022 exp_p--;
6023 while (++p < limit) {
6024 if (p[0] == '*' && p[1] == '/') {
6025 p += 2;
6026 break;
6029 #if 0
6030 /* Mark this as a concatenation-point, as if it had been ##. */
6031 concat = p;
6032 #endif
6034 break;
6038 /* Handle the start of a symbol. */
6039 if (is_idchar[c] && nargs > 0) {
6040 U_CHAR *id_beg = p - 1;
6041 int id_len;
6043 --exp_p;
6044 while (p != limit && is_idchar[*p]) p++;
6045 id_len = p - id_beg;
6047 if (is_idstart[c]
6048 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6049 register struct arglist *arg;
6051 for (arg = arglist; arg != NULL; arg = arg->next) {
6052 struct reflist *tpat;
6054 if (arg->name[0] == c
6055 && arg->length == id_len
6056 && bcmp (arg->name, id_beg, id_len) == 0) {
6057 enum sharp_token_type tpat_stringify;
6058 if (expected_delimiter) {
6059 if (warn_stringify) {
6060 if (traditional) {
6061 warning ("macro argument `%.*s' is stringified.",
6062 id_len, arg->name);
6063 } else {
6064 warning ("macro arg `%.*s' would be stringified with -traditional.",
6065 id_len, arg->name);
6068 /* If ANSI, don't actually substitute inside a string. */
6069 if (!traditional)
6070 break;
6071 tpat_stringify = SHARP_TOKEN;
6072 } else {
6073 tpat_stringify
6074 = (stringify == id_beg
6075 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6077 /* make a pat node for this arg and append it to the end of
6078 the pat list */
6079 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6080 tpat->next = NULL;
6081 tpat->raw_before
6082 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6083 tpat->raw_after = NO_SHARP_TOKEN;
6084 tpat->rest_args = arg->rest_args;
6085 tpat->stringify = tpat_stringify;
6087 if (endpat == NULL)
6088 defn->pattern = tpat;
6089 else
6090 endpat->next = tpat;
6091 endpat = tpat;
6093 tpat->argno = arg->argno;
6094 tpat->nchars = exp_p - lastp;
6096 register U_CHAR *p1 = p;
6097 SKIP_WHITE_SPACE (p1);
6098 if (p1[0]=='#'
6099 ? p1[1]=='#'
6100 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6101 tpat->raw_after = p1[0] + (p != p1);
6103 lastp = exp_p; /* place to start copying from next time */
6104 skipped_arg = 1;
6105 break;
6110 /* If this was not a macro arg, copy it into the expansion. */
6111 if (! skipped_arg) {
6112 register U_CHAR *lim1 = p;
6113 p = id_beg;
6114 while (p != lim1)
6115 *exp_p++ = *p++;
6116 if (stringify == id_beg)
6117 error ("`#' operator should be followed by a macro argument name");
6122 if (!traditional && expected_delimiter == 0) {
6123 /* If ANSI, put in a newline-space marker to prevent token pasting.
6124 But not if "inside a string" (which in ANSI mode happens only for
6125 -D option). */
6126 *exp_p++ = '\n';
6127 *exp_p++ = ' ';
6130 *exp_p = '\0';
6132 defn->length = exp_p - defn->expansion;
6134 /* Crash now if we overrun the allocated size. */
6135 if (defn->length + 1 > maxsize)
6136 abort ();
6138 #if 0
6139 /* This isn't worth the time it takes. */
6140 /* give back excess storage */
6141 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6142 #endif
6144 return defn;
6147 static int
6148 do_assert (buf, limit, op, keyword)
6149 U_CHAR *buf, *limit;
6150 FILE_BUF *op;
6151 struct directive *keyword;
6153 U_CHAR *bp; /* temp ptr into input buffer */
6154 U_CHAR *symname; /* remember where symbol name starts */
6155 int sym_length; /* and how long it is */
6156 struct arglist *tokens = NULL;
6158 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6159 pedwarn ("ANSI C does not allow `#assert'");
6161 bp = buf;
6163 while (is_hor_space[*bp])
6164 bp++;
6166 symname = bp; /* remember where it starts */
6167 sym_length = check_macro_name (bp, "assertion");
6168 bp += sym_length;
6169 /* #define doesn't do this, but we should. */
6170 SKIP_WHITE_SPACE (bp);
6172 /* Lossage will occur if identifiers or control tokens are broken
6173 across lines using backslash. This is not the right place to take
6174 care of that. */
6176 if (*bp != '(') {
6177 error ("missing token-sequence in `#assert'");
6178 return 1;
6182 int error_flag = 0;
6184 bp++; /* skip '(' */
6185 SKIP_WHITE_SPACE (bp);
6187 tokens = read_token_list (&bp, limit, &error_flag);
6188 if (error_flag)
6189 return 1;
6190 if (tokens == 0) {
6191 error ("empty token-sequence in `#assert'");
6192 return 1;
6195 ++bp; /* skip paren */
6196 SKIP_WHITE_SPACE (bp);
6199 /* If this name isn't already an assertion name, make it one.
6200 Error if it was already in use in some other way. */
6203 ASSERTION_HASHNODE *hp;
6204 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6205 struct tokenlist_list *value
6206 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6208 hp = assertion_lookup (symname, sym_length, hashcode);
6209 if (hp == NULL) {
6210 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6211 error ("`defined' redefined as assertion");
6212 hp = assertion_install (symname, sym_length, hashcode);
6215 /* Add the spec'd token-sequence to the list of such. */
6216 value->tokens = tokens;
6217 value->next = hp->value;
6218 hp->value = value;
6221 return 0;
6224 static int
6225 do_unassert (buf, limit, op, keyword)
6226 U_CHAR *buf, *limit;
6227 FILE_BUF *op;
6228 struct directive *keyword;
6230 U_CHAR *bp; /* temp ptr into input buffer */
6231 U_CHAR *symname; /* remember where symbol name starts */
6232 int sym_length; /* and how long it is */
6234 struct arglist *tokens = NULL;
6235 int tokens_specified = 0;
6237 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6238 pedwarn ("ANSI C does not allow `#unassert'");
6240 bp = buf;
6242 while (is_hor_space[*bp])
6243 bp++;
6245 symname = bp; /* remember where it starts */
6246 sym_length = check_macro_name (bp, "assertion");
6247 bp += sym_length;
6248 /* #define doesn't do this, but we should. */
6249 SKIP_WHITE_SPACE (bp);
6251 /* Lossage will occur if identifiers or control tokens are broken
6252 across lines using backslash. This is not the right place to take
6253 care of that. */
6255 if (*bp == '(') {
6256 int error_flag = 0;
6258 bp++; /* skip '(' */
6259 SKIP_WHITE_SPACE (bp);
6261 tokens = read_token_list (&bp, limit, &error_flag);
6262 if (error_flag)
6263 return 1;
6264 if (tokens == 0) {
6265 error ("empty token list in `#unassert'");
6266 return 1;
6269 tokens_specified = 1;
6271 ++bp; /* skip paren */
6272 SKIP_WHITE_SPACE (bp);
6276 ASSERTION_HASHNODE *hp;
6277 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6278 struct tokenlist_list *tail, *prev;
6280 hp = assertion_lookup (symname, sym_length, hashcode);
6281 if (hp == NULL)
6282 return 1;
6284 /* If no token list was specified, then eliminate this assertion
6285 entirely. */
6286 if (! tokens_specified) {
6287 struct tokenlist_list *next;
6288 for (tail = hp->value; tail; tail = next) {
6289 next = tail->next;
6290 free_token_list (tail->tokens);
6291 free (tail);
6293 delete_assertion (hp);
6294 } else {
6295 /* If a list of tokens was given, then delete any matching list. */
6297 tail = hp->value;
6298 prev = 0;
6299 while (tail) {
6300 struct tokenlist_list *next = tail->next;
6301 if (compare_token_lists (tail->tokens, tokens)) {
6302 if (prev)
6303 prev->next = next;
6304 else
6305 hp->value = tail->next;
6306 free_token_list (tail->tokens);
6307 free (tail);
6308 } else {
6309 prev = tail;
6311 tail = next;
6316 return 0;
6319 /* Test whether there is an assertion named NAME
6320 and optionally whether it has an asserted token list TOKENS.
6321 NAME is not null terminated; its length is SYM_LENGTH.
6322 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6325 check_assertion (name, sym_length, tokens_specified, tokens)
6326 U_CHAR *name;
6327 int sym_length;
6328 int tokens_specified;
6329 struct arglist *tokens;
6331 ASSERTION_HASHNODE *hp;
6332 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6334 if (pedantic && !instack[indepth].system_header_p)
6335 pedwarn ("ANSI C does not allow testing assertions");
6337 hp = assertion_lookup (name, sym_length, hashcode);
6338 if (hp == NULL)
6339 /* It is not an assertion; just return false. */
6340 return 0;
6342 /* If no token list was specified, then value is 1. */
6343 if (! tokens_specified)
6344 return 1;
6347 struct tokenlist_list *tail;
6349 tail = hp->value;
6351 /* If a list of tokens was given,
6352 then succeed if the assertion records a matching list. */
6354 while (tail) {
6355 if (compare_token_lists (tail->tokens, tokens))
6356 return 1;
6357 tail = tail->next;
6360 /* Fail if the assertion has no matching list. */
6361 return 0;
6365 /* Compare two lists of tokens for equality including order of tokens. */
6367 static int
6368 compare_token_lists (l1, l2)
6369 struct arglist *l1, *l2;
6371 while (l1 && l2) {
6372 if (l1->length != l2->length)
6373 return 0;
6374 if (bcmp (l1->name, l2->name, l1->length))
6375 return 0;
6376 l1 = l1->next;
6377 l2 = l2->next;
6380 /* Succeed if both lists end at the same time. */
6381 return l1 == l2;
6384 /* Read a space-separated list of tokens ending in a close parenthesis.
6385 Return a list of strings, in the order they were written.
6386 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6387 Parse the text starting at *BPP, and update *BPP.
6388 Don't parse beyond LIMIT. */
6390 static struct arglist *
6391 read_token_list (bpp, limit, error_flag)
6392 U_CHAR **bpp;
6393 U_CHAR *limit;
6394 int *error_flag;
6396 struct arglist *token_ptrs = 0;
6397 U_CHAR *bp = *bpp;
6398 int depth = 1;
6400 *error_flag = 0;
6402 /* Loop over the assertion value tokens. */
6403 while (depth > 0) {
6404 struct arglist *temp;
6405 int eofp = 0;
6406 U_CHAR *beg = bp;
6408 /* Find the end of the token. */
6409 if (*bp == '(') {
6410 bp++;
6411 depth++;
6412 } else if (*bp == ')') {
6413 depth--;
6414 if (depth == 0)
6415 break;
6416 bp++;
6417 } else if (*bp == '"' || *bp == '\'')
6418 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6419 else
6420 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6421 && *bp != '"' && *bp != '\'' && bp != limit)
6422 bp++;
6424 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6425 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6426 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6427 temp->name[bp - beg] = 0;
6428 temp->next = token_ptrs;
6429 token_ptrs = temp;
6430 temp->length = bp - beg;
6432 SKIP_WHITE_SPACE (bp);
6434 if (bp >= limit) {
6435 error ("unterminated token sequence in `#assert' or `#unassert'");
6436 *error_flag = -1;
6437 return 0;
6440 *bpp = bp;
6442 /* We accumulated the names in reverse order.
6443 Now reverse them to get the proper order. */
6445 register struct arglist *prev = 0, *this, *next;
6446 for (this = token_ptrs; this; this = next) {
6447 next = this->next;
6448 this->next = prev;
6449 prev = this;
6451 return prev;
6455 static void
6456 free_token_list (tokens)
6457 struct arglist *tokens;
6459 while (tokens) {
6460 struct arglist *next = tokens->next;
6461 free (tokens->name);
6462 free (tokens);
6463 tokens = next;
6467 /* Install a name in the assertion hash table.
6469 If LEN is >= 0, it is the length of the name.
6470 Otherwise, compute the length by scanning the entire name.
6472 If HASH is >= 0, it is the precomputed hash code.
6473 Otherwise, compute the hash code. */
6475 static ASSERTION_HASHNODE *
6476 assertion_install (name, len, hash)
6477 U_CHAR *name;
6478 int len;
6479 int hash;
6481 register ASSERTION_HASHNODE *hp;
6482 register int i, bucket;
6483 register U_CHAR *p, *q;
6485 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6486 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6487 bucket = hash;
6488 hp->bucket_hdr = &assertion_hashtab[bucket];
6489 hp->next = assertion_hashtab[bucket];
6490 assertion_hashtab[bucket] = hp;
6491 hp->prev = NULL;
6492 if (hp->next != NULL)
6493 hp->next->prev = hp;
6494 hp->length = len;
6495 hp->value = 0;
6496 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6497 p = hp->name;
6498 q = name;
6499 for (i = 0; i < len; i++)
6500 *p++ = *q++;
6501 hp->name[len] = 0;
6502 return hp;
6505 /* Find the most recent hash node for name name (ending with first
6506 non-identifier char) installed by install
6508 If LEN is >= 0, it is the length of the name.
6509 Otherwise, compute the length by scanning the entire name.
6511 If HASH is >= 0, it is the precomputed hash code.
6512 Otherwise, compute the hash code. */
6514 static ASSERTION_HASHNODE *
6515 assertion_lookup (name, len, hash)
6516 U_CHAR *name;
6517 int len;
6518 int hash;
6520 register ASSERTION_HASHNODE *bucket;
6522 bucket = assertion_hashtab[hash];
6523 while (bucket) {
6524 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6525 return bucket;
6526 bucket = bucket->next;
6528 return NULL;
6531 static void
6532 delete_assertion (hp)
6533 ASSERTION_HASHNODE *hp;
6536 if (hp->prev != NULL)
6537 hp->prev->next = hp->next;
6538 if (hp->next != NULL)
6539 hp->next->prev = hp->prev;
6541 /* Make sure that the bucket chain header that the deleted guy was
6542 on points to the right thing afterwards. */
6543 if (hp == *hp->bucket_hdr)
6544 *hp->bucket_hdr = hp->next;
6546 free (hp);
6550 * interpret #line directive. Remembers previously seen fnames
6551 * in its very own hash table.
6553 #define FNAME_HASHSIZE 37
6555 static int
6556 do_line (buf, limit, op, keyword)
6557 U_CHAR *buf, *limit;
6558 FILE_BUF *op;
6559 struct directive *keyword;
6561 register U_CHAR *bp;
6562 FILE_BUF *ip = &instack[indepth];
6563 FILE_BUF tem;
6564 int new_lineno;
6565 enum file_change_code file_change = same_file;
6567 /* Expand any macros. */
6568 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6570 /* Point to macroexpanded line, which is null-terminated now. */
6571 bp = tem.buf;
6572 SKIP_WHITE_SPACE (bp);
6574 if (!isdigit (*bp)) {
6575 error ("invalid format `#line' directive");
6576 return 0;
6579 /* The Newline at the end of this line remains to be processed.
6580 To put the next line at the specified line number,
6581 we must store a line number now that is one less. */
6582 new_lineno = atoi ((char *) bp) - 1;
6584 /* NEW_LINENO is one less than the actual line number here. */
6585 if (pedantic && new_lineno < 0)
6586 pedwarn ("line number out of range in `#line' directive");
6588 /* skip over the line number. */
6589 while (isdigit (*bp))
6590 bp++;
6592 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6593 if (*bp && !is_space[*bp]) {
6594 error ("invalid format `#line' directive");
6595 return;
6597 #endif
6599 SKIP_WHITE_SPACE (bp);
6601 if (*bp == '\"') {
6602 static HASHNODE *fname_table[FNAME_HASHSIZE];
6603 HASHNODE *hp, **hash_bucket;
6604 U_CHAR *fname, *p;
6605 int fname_length;
6607 fname = ++bp;
6609 /* Turn the file name, which is a character string literal,
6610 into a null-terminated string. Do this in place. */
6611 p = bp;
6612 for (;;)
6613 switch ((*p++ = *bp++)) {
6614 case '\0':
6615 error ("invalid format `#line' directive");
6616 return 0;
6618 case '\\':
6620 char *bpc = (char *) bp;
6621 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6622 bp = (U_CHAR *) bpc;
6623 if (c < 0)
6624 p--;
6625 else
6626 p[-1] = c;
6628 break;
6630 case '\"':
6631 p[-1] = 0;
6632 goto fname_done;
6634 fname_done:
6635 fname_length = p - fname;
6637 SKIP_WHITE_SPACE (bp);
6638 if (*bp) {
6639 if (pedantic)
6640 pedwarn ("garbage at end of `#line' directive");
6641 if (*bp == '1')
6642 file_change = enter_file;
6643 else if (*bp == '2')
6644 file_change = leave_file;
6645 else if (*bp == '3')
6646 ip->system_header_p = 1;
6647 else if (*bp == '4')
6648 ip->system_header_p = 2;
6649 else {
6650 error ("invalid format `#line' directive");
6651 return 0;
6654 bp++;
6655 SKIP_WHITE_SPACE (bp);
6656 if (*bp == '3') {
6657 ip->system_header_p = 1;
6658 bp++;
6659 SKIP_WHITE_SPACE (bp);
6661 if (*bp == '4') {
6662 ip->system_header_p = 2;
6663 bp++;
6664 SKIP_WHITE_SPACE (bp);
6666 if (*bp) {
6667 error ("invalid format `#line' directive");
6668 return 0;
6672 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6673 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6674 if (hp->length == fname_length &&
6675 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6676 ip->nominal_fname = hp->value.cpval;
6677 break;
6679 if (hp == 0) {
6680 /* Didn't find it; cons up a new one. */
6681 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6682 hp->next = *hash_bucket;
6683 *hash_bucket = hp;
6685 hp->length = fname_length;
6686 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6687 bcopy (fname, hp->value.cpval, fname_length);
6689 } else if (*bp) {
6690 error ("invalid format `#line' directive");
6691 return 0;
6694 ip->lineno = new_lineno;
6695 output_line_directive (ip, op, 0, file_change);
6696 check_expand (op, ip->length - (ip->bufp - ip->buf));
6697 return 0;
6700 /* Remove the definition of a symbol from the symbol table.
6701 according to un*x /lib/cpp, it is not an error to undef
6702 something that has no definitions, so it isn't one here either. */
6704 static int
6705 do_undef (buf, limit, op, keyword)
6706 U_CHAR *buf, *limit;
6707 FILE_BUF *op;
6708 struct directive *keyword;
6710 int sym_length;
6711 HASHNODE *hp;
6712 U_CHAR *orig_buf = buf;
6714 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6715 if (pcp_outfile && op)
6716 pass_thru_directive (buf, limit, op, keyword);
6718 SKIP_WHITE_SPACE (buf);
6719 sym_length = check_macro_name (buf, "macro");
6721 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6722 /* If we are generating additional info for debugging (with -g) we
6723 need to pass through all effective #undef directives. */
6724 if (debug_output && op)
6725 pass_thru_directive (orig_buf, limit, op, keyword);
6726 if (hp->type != T_MACRO)
6727 warning ("undefining `%s'", hp->name);
6728 delete_macro (hp);
6731 if (pedantic) {
6732 buf += sym_length;
6733 SKIP_WHITE_SPACE (buf);
6734 if (buf != limit)
6735 pedwarn ("garbage after `#undef' directive");
6737 return 0;
6740 /* Report an error detected by the program we are processing.
6741 Use the text of the line in the error message.
6742 (We use error because it prints the filename & line#.) */
6744 static int
6745 do_error (buf, limit, op, keyword)
6746 U_CHAR *buf, *limit;
6747 FILE_BUF *op;
6748 struct directive *keyword;
6750 int length = limit - buf;
6751 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6752 bcopy ((char *) buf, (char *) copy, length);
6753 copy[length] = 0;
6754 SKIP_WHITE_SPACE (copy);
6755 error ("#error %s", copy);
6756 return 0;
6759 /* Report a warning detected by the program we are processing.
6760 Use the text of the line in the warning message, then continue.
6761 (We use error because it prints the filename & line#.) */
6763 static int
6764 do_warning (buf, limit, op, keyword)
6765 U_CHAR *buf, *limit;
6766 FILE_BUF *op;
6767 struct directive *keyword;
6769 int length = limit - buf;
6770 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6771 bcopy ((char *) buf, (char *) copy, length);
6772 copy[length] = 0;
6773 SKIP_WHITE_SPACE (copy);
6774 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
6775 if -pedantic-errors is given, #warning should cause an error. */
6776 pedwarn ("#warning %s", copy);
6777 return 0;
6780 /* Remember the name of the current file being read from so that we can
6781 avoid ever including it again. */
6783 static void
6784 do_once ()
6786 int i;
6788 for (i = indepth; i >= 0; i--)
6789 if (instack[i].inc) {
6790 record_control_macro (instack[i].inc, (U_CHAR *) "");
6791 break;
6795 /* Report program identification. */
6797 static int
6798 do_ident (buf, limit, op, keyword)
6799 U_CHAR *buf, *limit;
6800 FILE_BUF *op;
6801 struct directive *keyword;
6803 FILE_BUF trybuf;
6804 int len;
6806 /* Allow #ident in system headers, since that's not user's fault. */
6807 if (pedantic && !instack[indepth].system_header_p)
6808 pedwarn ("ANSI C does not allow `#ident'");
6810 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6811 buf = trybuf.buf;
6812 len = trybuf.bufp - buf;
6814 /* Output expanded directive. */
6815 check_expand (op, 7 + len);
6816 bcopy ("#ident ", (char *) op->bufp, 7);
6817 op->bufp += 7;
6818 bcopy ((char *) buf, (char *) op->bufp, len);
6819 op->bufp += len;
6821 free (buf);
6822 return 0;
6825 /* #pragma and its argument line have already been copied to the output file.
6826 Just check for some recognized pragmas that need validation here. */
6828 static int
6829 do_pragma (buf, limit, op, keyword)
6830 U_CHAR *buf, *limit;
6831 FILE_BUF *op;
6832 struct directive *keyword;
6834 SKIP_WHITE_SPACE (buf);
6835 if (!strncmp ((char *) buf, "once", 4)) {
6836 /* Allow #pragma once in system headers, since that's not the user's
6837 fault. */
6838 if (!instack[indepth].system_header_p)
6839 warning ("`#pragma once' is obsolete");
6840 do_once ();
6843 if (!strncmp ((char *) buf, "implementation", 14)) {
6844 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6845 been included yet. */
6847 int h;
6848 U_CHAR *p = buf + 14, *fname;
6849 SKIP_WHITE_SPACE (p);
6850 if (*p != '\"')
6851 return 0;
6853 fname = p + 1;
6854 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6855 *p = '\0';
6857 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6858 struct include_file *inc;
6859 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6860 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6861 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6862 return 0;
6867 return 0;
6870 #if 0
6871 /* This was a fun hack, but #pragma seems to start to be useful.
6872 By failing to recognize it, we pass it through unchanged to cc1. */
6874 /* The behavior of the #pragma directive is implementation defined.
6875 this implementation defines it as follows. */
6877 static int
6878 do_pragma ()
6880 close (0);
6881 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6882 goto nope;
6883 close (1);
6884 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6885 goto nope;
6886 execl ("/usr/games/hack", "#pragma", 0);
6887 execl ("/usr/games/rogue", "#pragma", 0);
6888 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6889 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6890 nope:
6891 fatal ("You are in a maze of twisty compiler features, all different");
6893 #endif
6895 #ifdef SCCS_DIRECTIVE
6897 /* Just ignore #sccs, on systems where we define it at all. */
6899 static int
6900 do_sccs (buf, limit, op, keyword)
6901 U_CHAR *buf, *limit;
6902 FILE_BUF *op;
6903 struct directive *keyword;
6905 if (pedantic)
6906 pedwarn ("ANSI C does not allow `#sccs'");
6907 return 0;
6910 #endif /* defined (SCCS_DIRECTIVE) */
6912 /* Handle #if directive by
6913 1) inserting special `defined' keyword into the hash table
6914 that gets turned into 0 or 1 by special_symbol (thus,
6915 if the luser has a symbol called `defined' already, it won't
6916 work inside the #if directive)
6917 2) rescan the input into a temporary output buffer
6918 3) pass the output buffer to the yacc parser and collect a value
6919 4) clean up the mess left from steps 1 and 2.
6920 5) call conditional_skip to skip til the next #endif (etc.),
6921 or not, depending on the value from step 3. */
6923 static int
6924 do_if (buf, limit, op, keyword)
6925 U_CHAR *buf, *limit;
6926 FILE_BUF *op;
6927 struct directive *keyword;
6929 HOST_WIDE_INT value;
6930 FILE_BUF *ip = &instack[indepth];
6932 value = eval_if_expression (buf, limit - buf);
6933 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6934 return 0;
6937 /* Handle a #elif directive by not changing if_stack either.
6938 see the comment above do_else. */
6940 static int
6941 do_elif (buf, limit, op, keyword)
6942 U_CHAR *buf, *limit;
6943 FILE_BUF *op;
6944 struct directive *keyword;
6946 HOST_WIDE_INT value;
6947 FILE_BUF *ip = &instack[indepth];
6949 if (if_stack == instack[indepth].if_stack) {
6950 error ("`#elif' not within a conditional");
6951 return 0;
6952 } else {
6953 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6954 error ("`#elif' after `#else'");
6955 fprintf (stderr, " (matches line %d", if_stack->lineno);
6956 if (if_stack->fname != NULL && ip->fname != NULL
6957 && strcmp (if_stack->fname, ip->nominal_fname) != 0)
6958 fprintf (stderr, ", file %s", if_stack->fname);
6959 fprintf (stderr, ")\n");
6961 if_stack->type = T_ELIF;
6964 if (if_stack->if_succeeded)
6965 skip_if_group (ip, 0, op);
6966 else {
6967 value = eval_if_expression (buf, limit - buf);
6968 if (value == 0)
6969 skip_if_group (ip, 0, op);
6970 else {
6971 ++if_stack->if_succeeded; /* continue processing input */
6972 output_line_directive (ip, op, 1, same_file);
6975 return 0;
6978 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
6979 result as a C expression and return the value as an int. */
6981 static HOST_WIDE_INT
6982 eval_if_expression (buf, length)
6983 U_CHAR *buf;
6984 int length;
6986 FILE_BUF temp_obuf;
6987 HASHNODE *save_defined;
6988 HOST_WIDE_INT value;
6990 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
6991 NULL_PTR, -1);
6992 pcp_inside_if = 1;
6993 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6994 pcp_inside_if = 0;
6995 delete_macro (save_defined); /* clean up special symbol */
6997 temp_obuf.buf[temp_obuf.length] = '\n';
6998 value = parse_c_expression ((char *) temp_obuf.buf,
6999 warn_undef && !instack[indepth].system_header_p);
7001 free (temp_obuf.buf);
7003 return value;
7006 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7007 or don't skip to the #endif/#else/#elif depending on what directive
7008 is actually being processed. */
7010 static int
7011 do_xifdef (buf, limit, op, keyword)
7012 U_CHAR *buf, *limit;
7013 FILE_BUF *op;
7014 struct directive *keyword;
7016 int skip;
7017 FILE_BUF *ip = &instack[indepth];
7018 U_CHAR *end;
7019 int start_of_file = 0;
7020 U_CHAR *control_macro = 0;
7022 /* Detect a #ifndef at start of file (not counting comments). */
7023 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7024 U_CHAR *p = ip->buf;
7025 while (p != directive_start) {
7026 U_CHAR c = *p++;
7027 if (is_space[c])
7029 /* Make no special provision for backslash-newline here; this is
7030 slower if backslash-newlines are present, but it's correct,
7031 and it's not worth it to tune for the rare backslash-newline. */
7032 else if (c == '/'
7033 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7034 /* Skip this comment. */
7035 int junk = 0;
7036 U_CHAR *save_bufp = ip->bufp;
7037 ip->bufp = p + 1;
7038 p = skip_to_end_of_comment (ip, &junk, 1);
7039 ip->bufp = save_bufp;
7040 } else {
7041 goto fail;
7044 /* If we get here, this conditional is the beginning of the file. */
7045 start_of_file = 1;
7046 fail: ;
7049 /* Discard leading and trailing whitespace. */
7050 SKIP_WHITE_SPACE (buf);
7051 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7053 /* Find the end of the identifier at the beginning. */
7054 for (end = buf; is_idchar[*end]; end++);
7056 if (end == buf) {
7057 skip = (keyword->type == T_IFDEF);
7058 if (! traditional)
7059 pedwarn (end == limit ? "`#%s' with no argument"
7060 : "`#%s' argument starts with punctuation",
7061 keyword->name);
7062 } else {
7063 HASHNODE *hp;
7065 if (! traditional) {
7066 if (isdigit (buf[0]))
7067 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7068 else if (end != limit)
7069 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7072 hp = lookup (buf, end-buf, -1);
7074 if (pcp_outfile) {
7075 /* Output a precondition for this macro. */
7076 if (hp
7077 && (hp->type == T_CONST
7078 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7079 fprintf (pcp_outfile, "#define %s\n", hp->name);
7080 else {
7081 U_CHAR *cp = buf;
7082 fprintf (pcp_outfile, "#undef ");
7083 while (is_idchar[*cp]) /* Ick! */
7084 fputc (*cp++, pcp_outfile);
7085 putc ('\n', pcp_outfile);
7089 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7090 if (start_of_file && !skip) {
7091 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7092 bcopy ((char *) buf, (char *) control_macro, end - buf);
7093 control_macro[end - buf] = 0;
7097 conditional_skip (ip, skip, T_IF, control_macro, op);
7098 return 0;
7101 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7102 If this is a #ifndef starting at the beginning of a file,
7103 CONTROL_MACRO is the macro name tested by the #ifndef.
7104 Otherwise, CONTROL_MACRO is 0. */
7106 static void
7107 conditional_skip (ip, skip, type, control_macro, op)
7108 FILE_BUF *ip;
7109 int skip;
7110 enum node_type type;
7111 U_CHAR *control_macro;
7112 FILE_BUF *op;
7114 IF_STACK_FRAME *temp;
7116 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7117 temp->fname = ip->nominal_fname;
7118 temp->lineno = ip->lineno;
7119 temp->next = if_stack;
7120 temp->control_macro = control_macro;
7121 if_stack = temp;
7123 if_stack->type = type;
7125 if (skip != 0) {
7126 skip_if_group (ip, 0, op);
7127 return;
7128 } else {
7129 ++if_stack->if_succeeded;
7130 output_line_directive (ip, &outbuf, 1, same_file);
7134 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7135 Leaves input ptr at the sharp sign found.
7136 If ANY is nonzero, return at next directive of any sort. */
7138 static void
7139 skip_if_group (ip, any, op)
7140 FILE_BUF *ip;
7141 int any;
7142 FILE_BUF *op;
7144 register U_CHAR *bp = ip->bufp, *cp;
7145 register U_CHAR *endb = ip->buf + ip->length;
7146 struct directive *kt;
7147 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7148 U_CHAR *beg_of_line = bp;
7149 register int ident_length;
7150 U_CHAR *ident, *after_ident;
7151 /* Save info about where the group starts. */
7152 U_CHAR *beg_of_group = bp;
7153 int beg_lineno = ip->lineno;
7154 int skipping_include_directive = 0;
7156 if (output_conditionals && op != 0) {
7157 char *ptr = "#failed\n";
7158 int len = strlen (ptr);
7160 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7162 *op->bufp++ = '\n';
7163 op->lineno++;
7165 check_expand (op, len);
7166 bcopy (ptr, (char *) op->bufp, len);
7167 op->bufp += len;
7168 op->lineno++;
7169 output_line_directive (ip, op, 1, 0);
7172 while (bp < endb) {
7173 switch (*bp++) {
7174 case '/': /* possible comment */
7175 if (*bp == '\\' && bp[1] == '\n')
7176 newline_fix (bp);
7177 if (*bp == '*'
7178 || (cplusplus_comments && *bp == '/')) {
7179 ip->bufp = ++bp;
7180 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7182 break;
7183 case '<':
7184 if (skipping_include_directive) {
7185 while (bp < endb && *bp != '>' && *bp != '\n') {
7186 if (*bp == '\\' && bp[1] == '\n') {
7187 ip->lineno++;
7188 bp++;
7190 bp++;
7193 break;
7194 case '\"':
7195 if (skipping_include_directive) {
7196 while (bp < endb && *bp != '\n') {
7197 if (*bp == '"') {
7198 bp++;
7199 break;
7201 if (*bp == '\\' && bp[1] == '\n') {
7202 ip->lineno++;
7203 bp++;
7205 bp++;
7207 break;
7209 /* Fall through. */
7210 case '\'':
7211 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7212 NULL_PTR, NULL_PTR);
7213 break;
7214 case '\\':
7215 /* Char after backslash loses its special meaning in some cases. */
7216 if (*bp == '\n') {
7217 ++ip->lineno;
7218 bp++;
7219 } else if (traditional && bp < endb)
7220 bp++;
7221 break;
7222 case '\n':
7223 ++ip->lineno;
7224 beg_of_line = bp;
7225 skipping_include_directive = 0;
7226 break;
7227 case '%':
7228 if (beg_of_line == 0 || traditional)
7229 break;
7230 ip->bufp = bp - 1;
7231 while (bp[0] == '\\' && bp[1] == '\n')
7232 bp += 2;
7233 if (*bp == ':')
7234 goto sharp_token;
7235 break;
7236 case '#':
7237 /* # keyword: a # must be first nonblank char on the line */
7238 if (beg_of_line == 0)
7239 break;
7240 ip->bufp = bp - 1;
7241 sharp_token:
7242 /* Scan from start of line, skipping whitespace, comments
7243 and backslash-newlines, and see if we reach this #.
7244 If not, this # is not special. */
7245 bp = beg_of_line;
7246 /* If -traditional, require # to be at beginning of line. */
7247 if (!traditional) {
7248 while (1) {
7249 if (is_hor_space[*bp])
7250 bp++;
7251 else if (*bp == '\\' && bp[1] == '\n')
7252 bp += 2;
7253 else if (*bp == '/' && bp[1] == '*') {
7254 bp += 2;
7255 while (!(*bp == '*' && bp[1] == '/'))
7256 bp++;
7257 bp += 2;
7259 /* There is no point in trying to deal with C++ // comments here,
7260 because if there is one, then this # must be part of the
7261 comment and we would never reach here. */
7262 else break;
7265 if (bp != ip->bufp) {
7266 bp = ip->bufp + 1; /* Reset bp to after the #. */
7267 break;
7270 bp = ip->bufp + 1; /* Point after the '#' */
7271 if (ip->bufp[0] == '%') {
7272 /* Skip past the ':' again. */
7273 while (*bp == '\\') {
7274 ip->lineno++;
7275 bp += 2;
7277 bp++;
7280 /* Skip whitespace and \-newline. */
7281 while (1) {
7282 if (is_hor_space[*bp])
7283 bp++;
7284 else if (*bp == '\\' && bp[1] == '\n')
7285 bp += 2;
7286 else if (*bp == '/') {
7287 if (bp[1] == '\\' && bp[2] == '\n')
7288 newline_fix (bp + 1);
7289 if (bp[1] == '*') {
7290 for (bp += 2; ; bp++) {
7291 if (*bp == '\n')
7292 ip->lineno++;
7293 else if (*bp == '*') {
7294 if (bp[-1] == '/' && warn_comments)
7295 warning ("`/*' within comment");
7296 if (bp[1] == '\\' && bp[2] == '\n')
7297 newline_fix (bp + 1);
7298 if (bp[1] == '/')
7299 break;
7302 bp += 2;
7303 } else if (bp[1] == '/' && cplusplus_comments) {
7304 for (bp += 2; ; bp++) {
7305 if (*bp == '\n') {
7306 if (bp[-1] != '\\')
7307 break;
7308 if (warn_comments)
7309 warning ("multiline `//' comment");
7310 ip->lineno++;
7313 } else
7314 break;
7315 } else
7316 break;
7319 cp = bp;
7321 /* Now find end of directive name.
7322 If we encounter a backslash-newline, exchange it with any following
7323 symbol-constituents so that we end up with a contiguous name. */
7325 while (1) {
7326 if (is_idchar[*bp])
7327 bp++;
7328 else {
7329 if (*bp == '\\' && bp[1] == '\n')
7330 name_newline_fix (bp);
7331 if (is_idchar[*bp])
7332 bp++;
7333 else break;
7336 ident_length = bp - cp;
7337 ident = cp;
7338 after_ident = bp;
7340 /* A line of just `#' becomes blank. */
7342 if (ident_length == 0 && *after_ident == '\n') {
7343 continue;
7346 if (ident_length == 0 || !is_idstart[*ident]) {
7347 U_CHAR *p = ident;
7348 while (is_idchar[*p]) {
7349 if (*p < '0' || *p > '9')
7350 break;
7351 p++;
7353 /* Handle # followed by a line number. */
7354 if (p != ident && !is_idchar[*p]) {
7355 if (pedantic)
7356 pedwarn ("`#' followed by integer");
7357 continue;
7360 /* Avoid error for `###' and similar cases unless -pedantic. */
7361 if (p == ident) {
7362 while (*p == '#' || is_hor_space[*p]) p++;
7363 if (*p == '\n') {
7364 if (pedantic && !lang_asm)
7365 pedwarn ("invalid preprocessing directive");
7366 continue;
7370 if (!lang_asm && pedantic)
7371 pedwarn ("invalid preprocessing directive name");
7372 continue;
7375 for (kt = directive_table; kt->length >= 0; kt++) {
7376 IF_STACK_FRAME *temp;
7377 if (ident_length == kt->length
7378 && bcmp (cp, kt->name, kt->length) == 0) {
7379 /* If we are asked to return on next directive, do so now. */
7380 if (any)
7381 goto done;
7383 switch (kt->type) {
7384 case T_IF:
7385 case T_IFDEF:
7386 case T_IFNDEF:
7387 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7388 temp->next = if_stack;
7389 if_stack = temp;
7390 temp->lineno = ip->lineno;
7391 temp->fname = ip->nominal_fname;
7392 temp->type = kt->type;
7393 break;
7394 case T_ELSE:
7395 case T_ENDIF:
7396 if (pedantic && if_stack != save_if_stack)
7397 validate_else (bp, endb);
7398 case T_ELIF:
7399 if (if_stack == instack[indepth].if_stack) {
7400 error ("`#%s' not within a conditional", kt->name);
7401 break;
7403 else if (if_stack == save_if_stack)
7404 goto done; /* found what we came for */
7406 if (kt->type != T_ENDIF) {
7407 if (if_stack->type == T_ELSE)
7408 error ("`#else' or `#elif' after `#else'");
7409 if_stack->type = kt->type;
7410 break;
7413 temp = if_stack;
7414 if_stack = if_stack->next;
7415 free (temp);
7416 break;
7418 case T_INCLUDE:
7419 case T_INCLUDE_NEXT:
7420 case T_IMPORT:
7421 skipping_include_directive = 1;
7422 break;
7424 default:
7425 break;
7427 break;
7430 /* Don't let erroneous code go by. */
7431 if (kt->length < 0 && !lang_asm && pedantic)
7432 pedwarn ("invalid preprocessing directive name");
7436 ip->bufp = bp;
7437 /* after this returns, rescan will exit because ip->bufp
7438 now points to the end of the buffer.
7439 rescan is responsible for the error message also. */
7441 done:
7442 if (output_conditionals && op != 0) {
7443 char *ptr = "#endfailed\n";
7444 int len = strlen (ptr);
7446 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7448 *op->bufp++ = '\n';
7449 op->lineno++;
7451 check_expand (op, beg_of_line - beg_of_group);
7452 bcopy ((char *) beg_of_group, (char *) op->bufp,
7453 beg_of_line - beg_of_group);
7454 op->bufp += beg_of_line - beg_of_group;
7455 op->lineno += ip->lineno - beg_lineno;
7456 check_expand (op, len);
7457 bcopy (ptr, (char *) op->bufp, len);
7458 op->bufp += len;
7459 op->lineno++;
7463 /* Handle a #else directive. Do this by just continuing processing
7464 without changing if_stack ; this is so that the error message
7465 for missing #endif's etc. will point to the original #if. It
7466 is possible that something different would be better. */
7468 static int
7469 do_else (buf, limit, op, keyword)
7470 U_CHAR *buf, *limit;
7471 FILE_BUF *op;
7472 struct directive *keyword;
7474 FILE_BUF *ip = &instack[indepth];
7476 if (pedantic) {
7477 SKIP_WHITE_SPACE (buf);
7478 if (buf != limit)
7479 pedwarn ("text following `#else' violates ANSI standard");
7482 if (if_stack == instack[indepth].if_stack) {
7483 error ("`#else' not within a conditional");
7484 return 0;
7485 } else {
7486 /* #ifndef can't have its special treatment for containing the whole file
7487 if it has a #else clause. */
7488 if_stack->control_macro = 0;
7490 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7491 error ("`#else' after `#else'");
7492 fprintf (stderr, " (matches line %d", if_stack->lineno);
7493 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7494 fprintf (stderr, ", file %s", if_stack->fname);
7495 fprintf (stderr, ")\n");
7497 if_stack->type = T_ELSE;
7500 if (if_stack->if_succeeded)
7501 skip_if_group (ip, 0, op);
7502 else {
7503 ++if_stack->if_succeeded; /* continue processing input */
7504 output_line_directive (ip, op, 1, same_file);
7506 return 0;
7509 /* Unstack after #endif directive. */
7511 static int
7512 do_endif (buf, limit, op, keyword)
7513 U_CHAR *buf, *limit;
7514 FILE_BUF *op;
7515 struct directive *keyword;
7517 if (pedantic) {
7518 SKIP_WHITE_SPACE (buf);
7519 if (buf != limit)
7520 pedwarn ("text following `#endif' violates ANSI standard");
7523 if (if_stack == instack[indepth].if_stack)
7524 error ("unbalanced `#endif'");
7525 else {
7526 IF_STACK_FRAME *temp = if_stack;
7527 if_stack = if_stack->next;
7528 if (temp->control_macro != 0) {
7529 /* This #endif matched a #ifndef at the start of the file.
7530 See if it is at the end of the file. */
7531 FILE_BUF *ip = &instack[indepth];
7532 U_CHAR *p = ip->bufp;
7533 U_CHAR *ep = ip->buf + ip->length;
7535 while (p != ep) {
7536 U_CHAR c = *p++;
7537 if (!is_space[c]) {
7538 if (c == '/'
7539 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7540 /* Skip this comment. */
7541 int junk = 0;
7542 U_CHAR *save_bufp = ip->bufp;
7543 ip->bufp = p + 1;
7544 p = skip_to_end_of_comment (ip, &junk, 1);
7545 ip->bufp = save_bufp;
7546 } else
7547 goto fail;
7550 /* If we get here, this #endif ends a #ifndef
7551 that contains all of the file (aside from whitespace).
7552 Arrange not to include the file again
7553 if the macro that was tested is defined.
7555 Do not do this for the top-level file in a -include or any
7556 file in a -imacros. */
7557 if (indepth != 0
7558 && ! (indepth == 1 && no_record_file)
7559 && ! (no_record_file && no_output))
7560 record_control_macro (ip->inc, temp->control_macro);
7561 fail: ;
7563 free (temp);
7564 output_line_directive (&instack[indepth], op, 1, same_file);
7566 return 0;
7569 /* When an #else or #endif is found while skipping failed conditional,
7570 if -pedantic was specified, this is called to warn about text after
7571 the directive name. P points to the first char after the directive
7572 name. */
7574 static void
7575 validate_else (p, limit)
7576 register U_CHAR *p;
7577 register U_CHAR *limit;
7579 /* Advance P over whitespace and comments. */
7580 while (1) {
7581 while (*p == '\\' && p[1] == '\n')
7582 p += 2;
7583 if (is_hor_space[*p])
7584 p++;
7585 else if (*p == '/') {
7586 while (p[1] == '\\' && p[2] == '\n')
7587 p += 2;
7588 if (p[1] == '*') {
7589 /* Don't bother warning about unterminated comments
7590 since that will happen later. Just be sure to exit. */
7591 for (p += 2; ; p++) {
7592 if (p == limit)
7593 return;
7594 if (*p == '*') {
7595 while (p[1] == '\\' && p[2] == '\n')
7596 p += 2;
7597 if (p[1] == '/') {
7598 p += 2;
7599 break;
7604 else if (cplusplus_comments && p[1] == '/')
7605 return;
7606 else break;
7607 } else break;
7609 if (*p != '\n')
7610 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7613 /* Skip a comment, assuming the input ptr immediately follows the
7614 initial slash-star. Bump *LINE_COUNTER for each newline.
7615 (The canonical line counter is &ip->lineno.)
7616 Don't use this routine (or the next one) if bumping the line
7617 counter is not sufficient to deal with newlines in the string.
7619 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7620 This feature is useful when processing a comment that is going to
7621 be processed or was processed at another point in the preprocessor,
7622 to avoid a duplicate warning. Likewise for unterminated comment
7623 errors. */
7625 static U_CHAR *
7626 skip_to_end_of_comment (ip, line_counter, nowarn)
7627 register FILE_BUF *ip;
7628 int *line_counter; /* place to remember newlines, or NULL */
7629 int nowarn;
7631 register U_CHAR *limit = ip->buf + ip->length;
7632 register U_CHAR *bp = ip->bufp;
7633 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7634 int start_line = line_counter ? *line_counter : 0;
7636 /* JF this line_counter stuff is a crock to make sure the
7637 comment is only put out once, no matter how many times
7638 the comment is skipped. It almost works */
7639 if (op) {
7640 *op->bufp++ = '/';
7641 *op->bufp++ = bp[-1];
7643 if (cplusplus_comments && bp[-1] == '/') {
7644 for (; bp < limit; bp++) {
7645 if (*bp == '\n') {
7646 if (bp[-1] != '\\')
7647 break;
7648 if (!nowarn && warn_comments)
7649 warning ("multiline `//' comment");
7650 if (line_counter)
7651 ++*line_counter;
7652 if (op)
7653 ++op->lineno;
7655 if (op)
7656 *op->bufp++ = *bp;
7658 ip->bufp = bp;
7659 return bp;
7661 while (bp < limit) {
7662 if (op)
7663 *op->bufp++ = *bp;
7664 switch (*bp++) {
7665 case '\n':
7666 /* If this is the end of the file, we have an unterminated comment.
7667 Don't swallow the newline. We are guaranteed that there will be a
7668 trailing newline and various pieces assume it's there. */
7669 if (bp == limit)
7671 --bp;
7672 --limit;
7673 break;
7675 if (line_counter != NULL)
7676 ++*line_counter;
7677 if (op)
7678 ++op->lineno;
7679 break;
7680 case '*':
7681 if (bp[-2] == '/' && !nowarn && warn_comments)
7682 warning ("`/*' within comment");
7683 if (*bp == '\\' && bp[1] == '\n')
7684 newline_fix (bp);
7685 if (*bp == '/') {
7686 if (op)
7687 *op->bufp++ = '/';
7688 ip->bufp = ++bp;
7689 return bp;
7691 break;
7695 if (!nowarn)
7696 error_with_line (line_for_error (start_line), "unterminated comment");
7697 ip->bufp = bp;
7698 return bp;
7701 /* Skip over a quoted string. BP points to the opening quote.
7702 Returns a pointer after the closing quote. Don't go past LIMIT.
7703 START_LINE is the line number of the starting point (but it need
7704 not be valid if the starting point is inside a macro expansion).
7706 The input stack state is not changed.
7708 If COUNT_NEWLINES is nonzero, it points to an int to increment
7709 for each newline passed.
7711 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7712 if we pass a backslash-newline.
7714 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
7716 static U_CHAR *
7717 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7718 register U_CHAR *bp;
7719 register U_CHAR *limit;
7720 int start_line;
7721 int *count_newlines;
7722 int *backslash_newlines_p;
7723 int *eofp;
7725 register U_CHAR c, match;
7727 match = *bp++;
7728 while (1) {
7729 if (bp >= limit) {
7730 error_with_line (line_for_error (start_line),
7731 "unterminated string or character constant");
7732 error_with_line (multiline_string_line,
7733 "possible real start of unterminated constant");
7734 multiline_string_line = 0;
7735 if (eofp)
7736 *eofp = 1;
7737 break;
7739 c = *bp++;
7740 if (c == '\\') {
7741 while (*bp == '\\' && bp[1] == '\n') {
7742 if (backslash_newlines_p)
7743 *backslash_newlines_p = 1;
7744 if (count_newlines)
7745 ++*count_newlines;
7746 bp += 2;
7748 if (*bp == '\n') {
7749 if (backslash_newlines_p)
7750 *backslash_newlines_p = 1;
7751 if (count_newlines)
7752 ++*count_newlines;
7754 bp++;
7755 } else if (c == '\n') {
7756 if (traditional) {
7757 /* Unterminated strings and character constants are 'valid'. */
7758 bp--; /* Don't consume the newline. */
7759 if (eofp)
7760 *eofp = 1;
7761 break;
7763 if (match == '\'') {
7764 error_with_line (line_for_error (start_line),
7765 "unterminated string or character constant");
7766 bp--;
7767 if (eofp)
7768 *eofp = 1;
7769 break;
7771 /* If not traditional, then allow newlines inside strings. */
7772 if (count_newlines)
7773 ++*count_newlines;
7774 if (multiline_string_line == 0) {
7775 if (pedantic)
7776 pedwarn_with_line (line_for_error (start_line),
7777 "string constant runs past end of line");
7778 multiline_string_line = start_line;
7780 } else if (c == match)
7781 break;
7783 return bp;
7786 /* Place into DST a quoted string representing the string SRC.
7787 Return the address of DST's terminating null. */
7789 static char *
7790 quote_string (dst, src)
7791 char *dst, *src;
7793 U_CHAR c;
7795 *dst++ = '\"';
7796 for (;;)
7797 switch ((c = *src++))
7799 default:
7800 if (isprint (c))
7801 *dst++ = c;
7802 else
7804 sprintf (dst, "\\%03o", c);
7805 dst += 4;
7807 break;
7809 case '\"':
7810 case '\\':
7811 *dst++ = '\\';
7812 *dst++ = c;
7813 break;
7815 case '\0':
7816 *dst++ = '\"';
7817 *dst = '\0';
7818 return dst;
7822 /* Skip across a group of balanced parens, starting from IP->bufp.
7823 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7825 This does not handle newlines, because it's used for the arg of #if,
7826 where there aren't any newlines. Also, backslash-newline can't appear. */
7828 static U_CHAR *
7829 skip_paren_group (ip)
7830 register FILE_BUF *ip;
7832 U_CHAR *limit = ip->buf + ip->length;
7833 U_CHAR *p = ip->bufp;
7834 int depth = 0;
7835 int lines_dummy = 0;
7837 while (p != limit) {
7838 int c = *p++;
7839 switch (c) {
7840 case '(':
7841 depth++;
7842 break;
7844 case ')':
7845 depth--;
7846 if (depth == 0)
7847 return ip->bufp = p;
7848 break;
7850 case '/':
7851 if (*p == '*') {
7852 ip->bufp = p;
7853 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7854 p = ip->bufp;
7857 case '"':
7858 case '\'':
7860 int eofp = 0;
7861 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7862 if (eofp)
7863 return ip->bufp = p;
7865 break;
7869 ip->bufp = p;
7870 return p;
7873 /* Write out a #line directive, for instance, after an #include file.
7874 If CONDITIONAL is nonzero, we can omit the #line if it would
7875 appear to be a no-op, and we can output a few newlines instead
7876 if we want to increase the line number by a small amount.
7877 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
7879 static void
7880 output_line_directive (ip, op, conditional, file_change)
7881 FILE_BUF *ip, *op;
7882 int conditional;
7883 enum file_change_code file_change;
7885 int len;
7886 char *line_directive_buf, *line_end;
7888 if (no_line_directives
7889 || ip->fname == NULL
7890 || no_output) {
7891 op->lineno = ip->lineno;
7892 return;
7895 if (conditional) {
7896 if (ip->lineno == op->lineno)
7897 return;
7899 /* If the inherited line number is a little too small,
7900 output some newlines instead of a #line directive. */
7901 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7902 check_expand (op, 10);
7903 while (ip->lineno > op->lineno) {
7904 *op->bufp++ = '\n';
7905 op->lineno++;
7907 return;
7911 /* Output a positive line number if possible. */
7912 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
7913 && *ip->bufp == '\n') {
7914 ip->lineno++;
7915 ip->bufp++;
7918 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7919 sprintf (line_directive_buf, "# %d ", ip->lineno);
7920 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7921 ip->nominal_fname);
7922 if (file_change != same_file) {
7923 *line_end++ = ' ';
7924 *line_end++ = file_change == enter_file ? '1' : '2';
7926 /* Tell cc1 if following text comes from a system header file. */
7927 if (ip->system_header_p) {
7928 *line_end++ = ' ';
7929 *line_end++ = '3';
7931 #ifndef NO_IMPLICIT_EXTERN_C
7932 /* Tell cc1plus if following text should be treated as C. */
7933 if (ip->system_header_p == 2 && cplusplus) {
7934 *line_end++ = ' ';
7935 *line_end++ = '4';
7937 #endif
7938 *line_end++ = '\n';
7939 len = line_end - line_directive_buf;
7940 check_expand (op, len + 1);
7941 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7942 *op->bufp++ = '\n';
7943 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7944 op->bufp += len;
7945 op->lineno = ip->lineno;
7948 /* This structure represents one parsed argument in a macro call.
7949 `raw' points to the argument text as written (`raw_length' is its length).
7950 `expanded' points to the argument's macro-expansion
7951 (its length is `expand_length').
7952 `stringified_length' is the length the argument would have
7953 if stringified.
7954 `use_count' is the number of times this macro arg is substituted
7955 into the macro. If the actual use count exceeds 10,
7956 the value stored is 10.
7957 `free1' and `free2', if nonzero, point to blocks to be freed
7958 when the macro argument data is no longer needed. */
7960 struct argdata {
7961 U_CHAR *raw, *expanded;
7962 int raw_length, expand_length;
7963 int stringified_length;
7964 U_CHAR *free1, *free2;
7965 char newlines;
7966 char use_count;
7969 /* Expand a macro call.
7970 HP points to the symbol that is the macro being called.
7971 Put the result of expansion onto the input stack
7972 so that subsequent input by our caller will use it.
7974 If macro wants arguments, caller has already verified that
7975 an argument list follows; arguments come from the input stack. */
7977 static void
7978 macroexpand (hp, op)
7979 HASHNODE *hp;
7980 FILE_BUF *op;
7982 int nargs;
7983 DEFINITION *defn = hp->value.defn;
7984 register U_CHAR *xbuf;
7985 int xbuf_len;
7986 int start_line = instack[indepth].lineno;
7987 int rest_args, rest_zero;
7989 CHECK_DEPTH (return;);
7991 /* it might not actually be a macro. */
7992 if (hp->type != T_MACRO) {
7993 special_symbol (hp, op);
7994 return;
7997 /* This macro is being used inside a #if, which means it must be */
7998 /* recorded as a precondition. */
7999 if (pcp_inside_if && pcp_outfile && defn->predefined)
8000 dump_single_macro (hp, pcp_outfile);
8002 nargs = defn->nargs;
8004 if (nargs >= 0) {
8005 register int i;
8006 struct argdata *args;
8007 char *parse_error = 0;
8009 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8011 for (i = 0; i < nargs; i++) {
8012 args[i].raw = (U_CHAR *) "";
8013 args[i].expanded = 0;
8014 args[i].raw_length = args[i].expand_length
8015 = args[i].stringified_length = 0;
8016 args[i].free1 = args[i].free2 = 0;
8017 args[i].use_count = 0;
8020 /* Parse all the macro args that are supplied. I counts them.
8021 The first NARGS args are stored in ARGS.
8022 The rest are discarded.
8023 If rest_args is set then we assume macarg absorbed the rest of the args.
8025 i = 0;
8026 rest_args = 0;
8027 do {
8028 /* Discard the open-parenthesis or comma before the next arg. */
8029 ++instack[indepth].bufp;
8030 if (rest_args)
8031 continue;
8032 if (i < nargs || (nargs == 0 && i == 0)) {
8033 /* If we are working on last arg which absorbs rest of args... */
8034 if (i == nargs - 1 && defn->rest_args)
8035 rest_args = 1;
8036 parse_error = macarg (&args[i], rest_args);
8038 else
8039 parse_error = macarg (NULL_PTR, 0);
8040 if (parse_error) {
8041 error_with_line (line_for_error (start_line), parse_error);
8042 break;
8044 i++;
8045 } while (*instack[indepth].bufp != ')');
8047 /* If we got one arg but it was just whitespace, call that 0 args. */
8048 if (i == 1) {
8049 register U_CHAR *bp = args[0].raw;
8050 register U_CHAR *lim = bp + args[0].raw_length;
8051 /* cpp.texi says for foo ( ) we provide one argument.
8052 However, if foo wants just 0 arguments, treat this as 0. */
8053 if (nargs == 0)
8054 while (bp != lim && is_space[*bp]) bp++;
8055 if (bp == lim)
8056 i = 0;
8059 /* Don't output an error message if we have already output one for
8060 a parse error above. */
8061 rest_zero = 0;
8062 if (nargs == 0 && i > 0) {
8063 if (! parse_error)
8064 error ("arguments given to macro `%s'", hp->name);
8065 } else if (i < nargs) {
8066 /* traditional C allows foo() if foo wants one argument. */
8067 if (nargs == 1 && i == 0 && traditional)
8069 /* the rest args token is allowed to absorb 0 tokens */
8070 else if (i == nargs - 1 && defn->rest_args)
8071 rest_zero = 1;
8072 else if (parse_error)
8074 else if (i == 0)
8075 error ("macro `%s' used without args", hp->name);
8076 else if (i == 1)
8077 error ("macro `%s' used with just one arg", hp->name);
8078 else
8079 error ("macro `%s' used with only %d args", hp->name, i);
8080 } else if (i > nargs) {
8081 if (! parse_error)
8082 error ("macro `%s' used with too many (%d) args", hp->name, i);
8085 /* Swallow the closeparen. */
8086 ++instack[indepth].bufp;
8088 /* If macro wants zero args, we parsed the arglist for checking only.
8089 Read directly from the macro definition. */
8090 if (nargs == 0) {
8091 xbuf = defn->expansion;
8092 xbuf_len = defn->length;
8093 } else {
8094 register U_CHAR *exp = defn->expansion;
8095 register int offset; /* offset in expansion,
8096 copied a piece at a time */
8097 register int totlen; /* total amount of exp buffer filled so far */
8099 register struct reflist *ap, *last_ap;
8101 /* Macro really takes args. Compute the expansion of this call. */
8103 /* Compute length in characters of the macro's expansion.
8104 Also count number of times each arg is used. */
8105 xbuf_len = defn->length;
8106 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8107 if (ap->stringify)
8108 xbuf_len += args[ap->argno].stringified_length;
8109 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8110 /* Add 4 for two newline-space markers to prevent
8111 token concatenation. */
8112 xbuf_len += args[ap->argno].raw_length + 4;
8113 else {
8114 /* We have an ordinary (expanded) occurrence of the arg.
8115 So compute its expansion, if we have not already. */
8116 if (args[ap->argno].expanded == 0) {
8117 FILE_BUF obuf;
8118 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8119 args[ap->argno].raw + args[ap->argno].raw_length,
8120 1, 0);
8122 args[ap->argno].expanded = obuf.buf;
8123 args[ap->argno].expand_length = obuf.length;
8124 args[ap->argno].free2 = obuf.buf;
8127 /* Add 4 for two newline-space markers to prevent
8128 token concatenation. */
8129 xbuf_len += args[ap->argno].expand_length + 4;
8131 if (args[ap->argno].use_count < 10)
8132 args[ap->argno].use_count++;
8135 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8137 /* Generate in XBUF the complete expansion
8138 with arguments substituted in.
8139 TOTLEN is the total size generated so far.
8140 OFFSET is the index in the definition
8141 of where we are copying from. */
8142 offset = totlen = 0;
8143 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8144 last_ap = ap, ap = ap->next) {
8145 register struct argdata *arg = &args[ap->argno];
8146 int count_before = totlen;
8148 /* Add chars to XBUF. */
8149 for (i = 0; i < ap->nchars; i++, offset++)
8150 xbuf[totlen++] = exp[offset];
8152 /* If followed by an empty rest arg with concatenation,
8153 delete the last run of nonwhite chars. */
8154 if (rest_zero && totlen > count_before
8155 && ((ap->rest_args && ap->raw_before != 0)
8156 || (last_ap != NULL && last_ap->rest_args
8157 && last_ap->raw_after != 0))) {
8158 /* Delete final whitespace. */
8159 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8160 totlen--;
8163 /* Delete the nonwhites before them. */
8164 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8165 totlen--;
8169 if (ap->stringify != 0) {
8170 int arglen = arg->raw_length;
8171 int escaped = 0;
8172 int in_string = 0;
8173 int c;
8174 i = 0;
8175 while (i < arglen
8176 && (c = arg->raw[i], is_space[c]))
8177 i++;
8178 while (i < arglen
8179 && (c = arg->raw[arglen - 1], is_space[c]))
8180 arglen--;
8181 if (!traditional)
8182 xbuf[totlen++] = '\"'; /* insert beginning quote */
8183 for (; i < arglen; i++) {
8184 c = arg->raw[i];
8186 if (! in_string) {
8187 /* Special markers Newline Space
8188 generate nothing for a stringified argument. */
8189 if (c == '\n' && arg->raw[i+1] != '\n') {
8190 i++;
8191 continue;
8194 /* Internal sequences of whitespace are replaced by one space
8195 except within an string or char token. */
8196 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8197 while (1) {
8198 /* Note that Newline Space does occur within whitespace
8199 sequences; consider it part of the sequence. */
8200 if (c == '\n' && is_space[arg->raw[i+1]])
8201 i += 2;
8202 else if (c != '\n' && is_space[c])
8203 i++;
8204 else break;
8205 c = arg->raw[i];
8207 i--;
8208 c = ' ';
8212 if (escaped)
8213 escaped = 0;
8214 else {
8215 if (c == '\\')
8216 escaped = 1;
8217 if (in_string) {
8218 if (c == in_string)
8219 in_string = 0;
8220 } else if (c == '\"' || c == '\'')
8221 in_string = c;
8224 /* Escape these chars */
8225 if (c == '\"' || (in_string && c == '\\'))
8226 xbuf[totlen++] = '\\';
8227 /* We used to output e.g. \008 for control characters here,
8228 but this doesn't conform to the C Standard.
8229 Just output the characters as-is. */
8230 xbuf[totlen++] = c;
8232 if (!traditional)
8233 xbuf[totlen++] = '\"'; /* insert ending quote */
8234 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8235 U_CHAR *p1 = arg->raw;
8236 U_CHAR *l1 = p1 + arg->raw_length;
8237 if (ap->raw_before != 0) {
8238 while (p1 != l1 && is_space[*p1]) p1++;
8239 while (p1 != l1 && is_idchar[*p1])
8240 xbuf[totlen++] = *p1++;
8241 /* Delete any no-reexpansion marker that follows
8242 an identifier at the beginning of the argument
8243 if the argument is concatenated with what precedes it. */
8244 if (p1[0] == '\n' && p1[1] == '-')
8245 p1 += 2;
8246 } else if (!traditional) {
8247 /* Ordinary expanded use of the argument.
8248 Put in newline-space markers to prevent token pasting. */
8249 xbuf[totlen++] = '\n';
8250 xbuf[totlen++] = ' ';
8252 if (ap->raw_after != 0) {
8253 /* Arg is concatenated after: delete trailing whitespace,
8254 whitespace markers, and no-reexpansion markers. */
8255 while (p1 != l1) {
8256 if (is_space[l1[-1]]) l1--;
8257 else if (l1[-1] == '-') {
8258 U_CHAR *p2 = l1 - 1;
8259 /* If a `-' is preceded by an odd number of newlines then it
8260 and the last newline are a no-reexpansion marker. */
8261 while (p2 != p1 && p2[-1] == '\n') p2--;
8262 if ((l1 - 1 - p2) & 1) {
8263 l1 -= 2;
8265 else break;
8267 else break;
8271 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8272 totlen += l1 - p1;
8273 if (!traditional && ap->raw_after == 0) {
8274 /* Ordinary expanded use of the argument.
8275 Put in newline-space markers to prevent token pasting. */
8276 xbuf[totlen++] = '\n';
8277 xbuf[totlen++] = ' ';
8279 } else {
8280 /* Ordinary expanded use of the argument.
8281 Put in newline-space markers to prevent token pasting. */
8282 if (!traditional) {
8283 xbuf[totlen++] = '\n';
8284 xbuf[totlen++] = ' ';
8286 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8287 arg->expand_length);
8288 totlen += arg->expand_length;
8289 if (!traditional) {
8290 xbuf[totlen++] = '\n';
8291 xbuf[totlen++] = ' ';
8293 /* If a macro argument with newlines is used multiple times,
8294 then only expand the newlines once. This avoids creating output
8295 lines which don't correspond to any input line, which confuses
8296 gdb and gcov. */
8297 if (arg->use_count > 1 && arg->newlines > 0) {
8298 /* Don't bother doing change_newlines for subsequent
8299 uses of arg. */
8300 arg->use_count = 1;
8301 arg->expand_length
8302 = change_newlines (arg->expanded, arg->expand_length);
8306 if (totlen > xbuf_len)
8307 abort ();
8310 /* If there is anything left of the definition after handling
8311 the arg list, copy that in too. */
8313 for (i = offset; i < defn->length; i++) {
8314 /* if we've reached the end of the macro */
8315 if (exp[i] == ')')
8316 rest_zero = 0;
8317 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8318 && last_ap->raw_after != 0))
8319 xbuf[totlen++] = exp[i];
8322 xbuf[totlen] = 0;
8323 xbuf_len = totlen;
8325 for (i = 0; i < nargs; i++) {
8326 if (args[i].free1 != 0)
8327 free (args[i].free1);
8328 if (args[i].free2 != 0)
8329 free (args[i].free2);
8332 } else {
8333 xbuf = defn->expansion;
8334 xbuf_len = defn->length;
8337 /* Now put the expansion on the input stack
8338 so our caller will commence reading from it. */
8340 register FILE_BUF *ip2;
8342 ip2 = &instack[++indepth];
8344 ip2->fname = 0;
8345 ip2->nominal_fname = 0;
8346 ip2->inc = 0;
8347 /* This may not be exactly correct, but will give much better error
8348 messages for nested macro calls than using a line number of zero. */
8349 ip2->lineno = start_line;
8350 ip2->buf = xbuf;
8351 ip2->length = xbuf_len;
8352 ip2->bufp = xbuf;
8353 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8354 ip2->macro = hp;
8355 ip2->if_stack = if_stack;
8356 ip2->system_header_p = 0;
8358 /* Recursive macro use sometimes works traditionally.
8359 #define foo(x,y) bar (x (y,0), y)
8360 foo (foo, baz) */
8362 if (!traditional)
8363 hp->type = T_DISABLED;
8367 /* Parse a macro argument and store the info on it into *ARGPTR.
8368 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8369 Return nonzero to indicate a syntax error. */
8371 static char *
8372 macarg (argptr, rest_args)
8373 register struct argdata *argptr;
8374 int rest_args;
8376 FILE_BUF *ip = &instack[indepth];
8377 int paren = 0;
8378 int newlines = 0;
8379 int comments = 0;
8380 char *result = 0;
8382 /* Try to parse as much of the argument as exists at this
8383 input stack level. */
8384 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8385 &paren, &newlines, &comments, rest_args);
8387 /* If we find the end of the argument at this level,
8388 set up *ARGPTR to point at it in the input stack. */
8389 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8390 && bp != ip->buf + ip->length) {
8391 if (argptr != 0) {
8392 argptr->raw = ip->bufp;
8393 argptr->raw_length = bp - ip->bufp;
8394 argptr->newlines = newlines;
8396 ip->bufp = bp;
8397 } else {
8398 /* This input stack level ends before the macro argument does.
8399 We must pop levels and keep parsing.
8400 Therefore, we must allocate a temporary buffer and copy
8401 the macro argument into it. */
8402 int bufsize = bp - ip->bufp;
8403 int extra = newlines;
8404 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8405 int final_start = 0;
8407 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8408 ip->bufp = bp;
8409 ip->lineno += newlines;
8411 while (bp == ip->buf + ip->length) {
8412 if (instack[indepth].macro == 0) {
8413 result = "unterminated macro call";
8414 break;
8416 ip->macro->type = T_MACRO;
8417 if (ip->free_ptr)
8418 free (ip->free_ptr);
8419 ip = &instack[--indepth];
8420 newlines = 0;
8421 comments = 0;
8422 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8423 &newlines, &comments, rest_args);
8424 final_start = bufsize;
8425 bufsize += bp - ip->bufp;
8426 extra += newlines;
8427 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8428 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8429 bp - ip->bufp);
8430 ip->bufp = bp;
8431 ip->lineno += newlines;
8434 /* Now, if arg is actually wanted, record its raw form,
8435 discarding comments and duplicating newlines in whatever
8436 part of it did not come from a macro expansion.
8437 EXTRA space has been preallocated for duplicating the newlines.
8438 FINAL_START is the index of the start of that part. */
8439 if (argptr != 0) {
8440 argptr->raw = buffer;
8441 argptr->raw_length = bufsize;
8442 argptr->free1 = buffer;
8443 argptr->newlines = newlines;
8444 if ((newlines || comments) && ip->fname != 0)
8445 argptr->raw_length
8446 = final_start +
8447 discard_comments (argptr->raw + final_start,
8448 argptr->raw_length - final_start,
8449 newlines);
8450 argptr->raw[argptr->raw_length] = 0;
8451 if (argptr->raw_length > bufsize + extra)
8452 abort ();
8456 /* If we are not discarding this argument,
8457 macroexpand it and compute its length as stringified.
8458 All this info goes into *ARGPTR. */
8460 if (argptr != 0) {
8461 register U_CHAR *buf, *lim;
8462 register int totlen;
8464 buf = argptr->raw;
8465 lim = buf + argptr->raw_length;
8467 while (buf != lim && is_space[*buf])
8468 buf++;
8469 while (buf != lim && is_space[lim[-1]])
8470 lim--;
8471 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8472 while (buf != lim) {
8473 register U_CHAR c = *buf++;
8474 totlen++;
8475 /* Internal sequences of whitespace are replaced by one space
8476 in most cases, but not always. So count all the whitespace
8477 in case we need to keep it all. */
8478 #if 0
8479 if (is_space[c])
8480 SKIP_ALL_WHITE_SPACE (buf);
8481 else
8482 #endif
8483 if (c == '\"' || c == '\\') /* escape these chars */
8484 totlen++;
8486 argptr->stringified_length = totlen;
8488 return result;
8491 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8492 taken from the expansion of MACRO,
8493 counting parens in *DEPTHPTR,
8494 and return if reach LIMIT
8495 or before a `)' that would make *DEPTHPTR negative
8496 or before a comma when *DEPTHPTR is zero.
8497 Single and double quotes are matched and termination
8498 is inhibited within them. Comments also inhibit it.
8499 Value returned is pointer to stopping place.
8501 Increment *NEWLINES each time a newline is passed.
8502 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8503 Set *COMMENTS to 1 if a comment is seen. */
8505 static U_CHAR *
8506 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8507 U_CHAR *start;
8508 register U_CHAR *limit;
8509 struct hashnode *macro;
8510 int *depthptr, *newlines, *comments;
8511 int rest_args;
8513 register U_CHAR *bp = start;
8515 while (bp < limit) {
8516 switch (*bp) {
8517 case '(':
8518 (*depthptr)++;
8519 break;
8520 case ')':
8521 if (--(*depthptr) < 0)
8522 return bp;
8523 break;
8524 case '\\':
8525 /* Traditionally, backslash makes following char not special. */
8526 if (traditional && bp + 1 < limit && bp[1] != '\n')
8527 bp++;
8528 break;
8529 case '\n':
8530 ++*newlines;
8531 break;
8532 case '/':
8533 if (macro)
8534 break;
8535 if (bp[1] == '\\' && bp[2] == '\n')
8536 newline_fix (bp + 1);
8537 if (bp[1] == '*') {
8538 *comments = 1;
8539 for (bp += 2; bp < limit; bp++) {
8540 if (*bp == '\n')
8541 ++*newlines;
8542 else if (*bp == '*') {
8543 if (bp[-1] == '/' && warn_comments)
8544 warning ("`/*' within comment");
8545 if (bp[1] == '\\' && bp[2] == '\n')
8546 newline_fix (bp + 1);
8547 if (bp[1] == '/') {
8548 bp++;
8549 break;
8553 } else if (bp[1] == '/' && cplusplus_comments) {
8554 *comments = 1;
8555 for (bp += 2; bp < limit; bp++) {
8556 if (*bp == '\n') {
8557 ++*newlines;
8558 if (bp[-1] != '\\')
8559 break;
8560 if (warn_comments)
8561 warning ("multiline `//' comment");
8565 break;
8566 case '\'':
8567 case '\"':
8569 int quotec;
8570 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8571 if (*bp == '\\') {
8572 bp++;
8573 if (*bp == '\n')
8574 ++*newlines;
8575 if (!macro) {
8576 while (*bp == '\\' && bp[1] == '\n') {
8577 bp += 2;
8578 ++*newlines;
8581 } else if (*bp == '\n') {
8582 ++*newlines;
8583 if (quotec == '\'')
8584 break;
8588 break;
8589 case ',':
8590 /* if we've returned to lowest level and we aren't absorbing all args */
8591 if ((*depthptr) == 0 && rest_args == 0)
8592 return bp;
8593 break;
8595 bp++;
8598 return bp;
8601 /* Discard comments and duplicate newlines
8602 in the string of length LENGTH at START,
8603 except inside of string constants.
8604 The string is copied into itself with its beginning staying fixed.
8606 NEWLINES is the number of newlines that must be duplicated.
8607 We assume that that much extra space is available past the end
8608 of the string. */
8610 static int
8611 discard_comments (start, length, newlines)
8612 U_CHAR *start;
8613 int length;
8614 int newlines;
8616 register U_CHAR *ibp;
8617 register U_CHAR *obp;
8618 register U_CHAR *limit;
8619 register int c;
8621 /* If we have newlines to duplicate, copy everything
8622 that many characters up. Then, in the second part,
8623 we will have room to insert the newlines
8624 while copying down.
8625 NEWLINES may actually be too large, because it counts
8626 newlines in string constants, and we don't duplicate those.
8627 But that does no harm. */
8628 if (newlines > 0) {
8629 ibp = start + length;
8630 obp = ibp + newlines;
8631 limit = start;
8632 while (limit != ibp)
8633 *--obp = *--ibp;
8636 ibp = start + newlines;
8637 limit = start + length + newlines;
8638 obp = start;
8640 while (ibp < limit) {
8641 *obp++ = c = *ibp++;
8642 switch (c) {
8643 case '\n':
8644 /* Duplicate the newline. */
8645 *obp++ = '\n';
8646 break;
8648 case '\\':
8649 if (*ibp == '\n') {
8650 obp--;
8651 ibp++;
8653 break;
8655 case '/':
8656 if (*ibp == '\\' && ibp[1] == '\n')
8657 newline_fix (ibp);
8658 /* Delete any comment. */
8659 if (cplusplus_comments && ibp[0] == '/') {
8660 /* Comments are equivalent to spaces. */
8661 obp[-1] = ' ';
8662 ibp++;
8663 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8664 ibp++;
8665 break;
8667 if (ibp[0] != '*' || ibp + 1 >= limit)
8668 break;
8669 /* Comments are equivalent to spaces.
8670 For -traditional, a comment is equivalent to nothing. */
8671 if (traditional)
8672 obp--;
8673 else
8674 obp[-1] = ' ';
8675 while (++ibp < limit) {
8676 if (ibp[0] == '*') {
8677 if (ibp[1] == '\\' && ibp[2] == '\n')
8678 newline_fix (ibp + 1);
8679 if (ibp[1] == '/') {
8680 ibp += 2;
8681 break;
8685 break;
8687 case '\'':
8688 case '\"':
8689 /* Notice and skip strings, so that we don't
8690 think that comments start inside them,
8691 and so we don't duplicate newlines in them. */
8693 int quotec = c;
8694 while (ibp < limit) {
8695 *obp++ = c = *ibp++;
8696 if (c == quotec)
8697 break;
8698 if (c == '\n' && quotec == '\'')
8699 break;
8700 if (c == '\\') {
8701 if (ibp < limit && *ibp == '\n') {
8702 ibp++;
8703 obp--;
8704 } else {
8705 while (*ibp == '\\' && ibp[1] == '\n')
8706 ibp += 2;
8707 if (ibp < limit)
8708 *obp++ = *ibp++;
8713 break;
8717 return obp - start;
8720 /* Turn newlines to spaces in the string of length LENGTH at START,
8721 except inside of string constants.
8722 The string is copied into itself with its beginning staying fixed. */
8724 static int
8725 change_newlines (start, length)
8726 U_CHAR *start;
8727 int length;
8729 register U_CHAR *ibp;
8730 register U_CHAR *obp;
8731 register U_CHAR *limit;
8732 register int c;
8734 ibp = start;
8735 limit = start + length;
8736 obp = start;
8738 while (ibp < limit) {
8739 *obp++ = c = *ibp++;
8740 switch (c) {
8741 case '\n':
8742 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8743 string. Skip past the newline and its duplicate.
8744 Put a space in the output. */
8745 if (*ibp == '\n')
8747 ibp++;
8748 obp--;
8749 *obp++ = ' ';
8751 break;
8753 case '\'':
8754 case '\"':
8755 /* Notice and skip strings, so that we don't delete newlines in them. */
8757 int quotec = c;
8758 while (ibp < limit) {
8759 *obp++ = c = *ibp++;
8760 if (c == quotec && ibp[-2] != '\\')
8761 break;
8762 if (c == '\n' && quotec == '\'')
8763 break;
8766 break;
8770 return obp - start;
8773 /* my_strerror - return the descriptive text associated with an
8774 `errno' code. */
8776 char *
8777 my_strerror (errnum)
8778 int errnum;
8780 char *result;
8782 #ifndef VMS
8783 #ifndef HAVE_STRERROR
8784 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8785 #else
8786 result = strerror (errnum);
8787 #endif
8788 #else /* VMS */
8789 /* VAXCRTL's strerror() takes an optional second argument, which only
8790 matters when the first argument is EVMSERR. However, it's simplest
8791 just to pass it unconditionally. `vaxc$errno' is declared in
8792 <errno.h>, and maintained by the library in parallel with `errno'.
8793 We assume that caller's `errnum' either matches the last setting of
8794 `errno' by the library or else does not have the value `EVMSERR'. */
8796 result = strerror (errnum, vaxc$errno);
8797 #endif
8799 if (!result)
8800 result = "undocumented I/O error";
8802 return result;
8805 /* error - print error message and increment count of errors. */
8807 void
8808 error (PRINTF_ALIST (msg))
8809 PRINTF_DCL (msg)
8811 va_list args;
8813 VA_START (args, msg);
8814 verror (msg, args);
8815 va_end (args);
8818 static void
8819 verror (msg, args)
8820 char *msg;
8821 va_list args;
8823 int i;
8824 FILE_BUF *ip = NULL;
8826 print_containing_files ();
8828 for (i = indepth; i >= 0; i--)
8829 if (instack[i].fname != NULL) {
8830 ip = &instack[i];
8831 break;
8834 if (ip != NULL)
8835 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8836 vfprintf (stderr, msg, args);
8837 fprintf (stderr, "\n");
8838 errors++;
8841 /* Error including a message from `errno'. */
8843 static void
8844 error_from_errno (name)
8845 char *name;
8847 int e = errno;
8848 int i;
8849 FILE_BUF *ip = NULL;
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);
8862 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
8864 errors++;
8867 /* Print error message but don't count it. */
8869 void
8870 warning (PRINTF_ALIST (msg))
8871 PRINTF_DCL (msg)
8873 va_list args;
8875 VA_START (args, msg);
8876 vwarning (msg, args);
8877 va_end (args);
8880 static void
8881 vwarning (msg, args)
8882 char *msg;
8883 va_list args;
8885 int i;
8886 FILE_BUF *ip = NULL;
8888 if (inhibit_warnings)
8889 return;
8891 if (warnings_are_errors)
8892 errors++;
8894 print_containing_files ();
8896 for (i = indepth; i >= 0; i--)
8897 if (instack[i].fname != NULL) {
8898 ip = &instack[i];
8899 break;
8902 if (ip != NULL)
8903 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8904 fprintf (stderr, "warning: ");
8905 vfprintf (stderr, msg, args);
8906 fprintf (stderr, "\n");
8909 static void
8910 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8911 error_with_line (int line, PRINTF_ALIST (msg))
8912 #else
8913 error_with_line (line, PRINTF_ALIST (msg))
8914 int line;
8915 PRINTF_DCL (msg)
8916 #endif
8918 va_list args;
8920 VA_START (args, msg);
8921 verror_with_line (line, msg, args);
8922 va_end (args);
8925 static void
8926 verror_with_line (line, msg, args)
8927 int line;
8928 char *msg;
8929 va_list args;
8931 int i;
8932 FILE_BUF *ip = NULL;
8934 print_containing_files ();
8936 for (i = indepth; i >= 0; i--)
8937 if (instack[i].fname != NULL) {
8938 ip = &instack[i];
8939 break;
8942 if (ip != NULL)
8943 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8944 vfprintf (stderr, msg, args);
8945 fprintf (stderr, "\n");
8946 errors++;
8949 static void
8950 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8951 warning_with_line (int line, PRINTF_ALIST (msg))
8952 #else
8953 warning_with_line (line, PRINTF_ALIST (msg))
8954 int line;
8955 PRINTF_DCL (msg)
8956 #endif
8958 va_list args;
8960 VA_START (args, msg);
8961 vwarning_with_line (line, msg, args);
8962 va_end (args);
8965 static void
8966 vwarning_with_line (line, msg, args)
8967 int line;
8968 char *msg;
8969 va_list args;
8971 int i;
8972 FILE_BUF *ip = NULL;
8974 if (inhibit_warnings)
8975 return;
8977 if (warnings_are_errors)
8978 errors++;
8980 print_containing_files ();
8982 for (i = indepth; i >= 0; i--)
8983 if (instack[i].fname != NULL) {
8984 ip = &instack[i];
8985 break;
8988 if (ip != NULL)
8989 fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
8990 fprintf (stderr, "warning: ");
8991 vfprintf (stderr, msg, args);
8992 fprintf (stderr, "\n");
8995 /* Print an error message and maybe count it. */
8997 void
8998 pedwarn (PRINTF_ALIST (msg))
8999 PRINTF_DCL (msg)
9001 va_list args;
9003 VA_START (args, msg);
9004 if (pedantic_errors)
9005 verror (msg, args);
9006 else
9007 vwarning (msg, args);
9008 va_end (args);
9011 void
9012 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9013 pedwarn_with_line (int line, PRINTF_ALIST (msg))
9014 #else
9015 pedwarn_with_line (line, PRINTF_ALIST (msg))
9016 int line;
9017 PRINTF_DCL (msg)
9018 #endif
9020 va_list args;
9022 VA_START (args, msg);
9023 if (pedantic_errors)
9024 verror_with_line (line, msg, args);
9025 else
9026 vwarning_with_line (line, msg, args);
9027 va_end (args);
9030 /* Report a warning (or an error if pedantic_errors)
9031 giving specified file name and line number, not current. */
9033 static void
9034 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9035 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
9036 #else
9037 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
9038 char *file;
9039 int line;
9040 PRINTF_DCL (msg)
9041 #endif
9043 va_list args;
9045 if (!pedantic_errors && inhibit_warnings)
9046 return;
9047 if (file != NULL)
9048 fprintf (stderr, "%s:%d: ", file, line);
9049 if (pedantic_errors)
9050 errors++;
9051 if (!pedantic_errors)
9052 fprintf (stderr, "warning: ");
9053 VA_START (args, msg);
9054 vfprintf (stderr, msg, args);
9055 va_end (args);
9056 fprintf (stderr, "\n");
9059 /* Print the file names and line numbers of the #include
9060 directives which led to the current file. */
9062 static void
9063 print_containing_files ()
9065 FILE_BUF *ip = NULL;
9066 int i;
9067 int first = 1;
9069 /* If stack of files hasn't changed since we last printed
9070 this info, don't repeat it. */
9071 if (last_error_tick == input_file_stack_tick)
9072 return;
9074 for (i = indepth; i >= 0; i--)
9075 if (instack[i].fname != NULL) {
9076 ip = &instack[i];
9077 break;
9080 /* Give up if we don't find a source file. */
9081 if (ip == NULL)
9082 return;
9084 /* Find the other, outer source files. */
9085 for (i--; i >= 0; i--)
9086 if (instack[i].fname != NULL) {
9087 ip = &instack[i];
9088 if (first) {
9089 first = 0;
9090 fprintf (stderr, "In file included");
9091 } else {
9092 fprintf (stderr, ",\n ");
9095 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9097 if (! first)
9098 fprintf (stderr, ":\n");
9100 /* Record we have printed the status as of this time. */
9101 last_error_tick = input_file_stack_tick;
9104 /* Return the line at which an error occurred.
9105 The error is not necessarily associated with the current spot
9106 in the input stack, so LINE says where. LINE will have been
9107 copied from ip->lineno for the current input level.
9108 If the current level is for a file, we return LINE.
9109 But if the current level is not for a file, LINE is meaningless.
9110 In that case, we return the lineno of the innermost file. */
9112 static int
9113 line_for_error (line)
9114 int line;
9116 int i;
9117 int line1 = line;
9119 for (i = indepth; i >= 0; ) {
9120 if (instack[i].fname != 0)
9121 return line1;
9122 i--;
9123 if (i < 0)
9124 return 0;
9125 line1 = instack[i].lineno;
9127 abort ();
9128 /*NOTREACHED*/
9129 return 0;
9133 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9135 * As things stand, nothing is ever placed in the output buffer to be
9136 * removed again except when it's KNOWN to be part of an identifier,
9137 * so flushing and moving down everything left, instead of expanding,
9138 * should work ok.
9141 /* You might think void was cleaner for the return type,
9142 but that would get type mismatch in check_expand in strict ANSI. */
9144 static int
9145 grow_outbuf (obuf, needed)
9146 register FILE_BUF *obuf;
9147 register int needed;
9149 register U_CHAR *p;
9150 int minsize;
9152 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9153 return 0;
9155 /* Make it at least twice as big as it is now. */
9156 obuf->length *= 2;
9157 /* Make it have at least 150% of the free space we will need. */
9158 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9159 if (minsize > obuf->length)
9160 obuf->length = minsize;
9162 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9163 memory_full ();
9165 obuf->bufp = p + (obuf->bufp - obuf->buf);
9166 obuf->buf = p;
9168 return 0;
9171 /* Symbol table for macro names and special symbols */
9174 * install a name in the main hash table, even if it is already there.
9175 * name stops with first non alphanumeric, except leading '#'.
9176 * caller must check against redefinition if that is desired.
9177 * delete_macro () removes things installed by install () in fifo order.
9178 * this is important because of the `defined' special symbol used
9179 * in #if, and also if pushdef/popdef directives are ever implemented.
9181 * If LEN is >= 0, it is the length of the name.
9182 * Otherwise, compute the length by scanning the entire name.
9184 * If HASH is >= 0, it is the precomputed hash code.
9185 * Otherwise, compute the hash code.
9188 static HASHNODE *
9189 install (name, len, type, value, hash)
9190 U_CHAR *name;
9191 int len;
9192 enum node_type type;
9193 char *value;
9194 int hash;
9196 register HASHNODE *hp;
9197 register int i, bucket;
9198 register U_CHAR *p, *q;
9200 if (len < 0) {
9201 p = name;
9202 while (is_idchar[*p])
9203 p++;
9204 len = p - name;
9207 if (hash < 0)
9208 hash = hashf (name, len, HASHSIZE);
9210 i = sizeof (HASHNODE) + len + 1;
9211 hp = (HASHNODE *) xmalloc (i);
9212 bucket = hash;
9213 hp->bucket_hdr = &hashtab[bucket];
9214 hp->next = hashtab[bucket];
9215 hashtab[bucket] = hp;
9216 hp->prev = NULL;
9217 if (hp->next != NULL)
9218 hp->next->prev = hp;
9219 hp->type = type;
9220 hp->length = len;
9221 hp->value.cpval = value;
9222 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9223 p = hp->name;
9224 q = name;
9225 for (i = 0; i < len; i++)
9226 *p++ = *q++;
9227 hp->name[len] = 0;
9228 return hp;
9232 * find the most recent hash node for name name (ending with first
9233 * non-identifier char) installed by install
9235 * If LEN is >= 0, it is the length of the name.
9236 * Otherwise, compute the length by scanning the entire name.
9238 * If HASH is >= 0, it is the precomputed hash code.
9239 * Otherwise, compute the hash code.
9242 HASHNODE *
9243 lookup (name, len, hash)
9244 U_CHAR *name;
9245 int len;
9246 int hash;
9248 register U_CHAR *bp;
9249 register HASHNODE *bucket;
9251 if (len < 0) {
9252 for (bp = name; is_idchar[*bp]; bp++) ;
9253 len = bp - name;
9256 if (hash < 0)
9257 hash = hashf (name, len, HASHSIZE);
9259 bucket = hashtab[hash];
9260 while (bucket) {
9261 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9262 return bucket;
9263 bucket = bucket->next;
9265 return NULL;
9269 * Delete a hash node. Some weirdness to free junk from macros.
9270 * More such weirdness will have to be added if you define more hash
9271 * types that need it.
9274 /* Note that the DEFINITION of a macro is removed from the hash table
9275 but its storage is not freed. This would be a storage leak
9276 except that it is not reasonable to keep undefining and redefining
9277 large numbers of macros many times.
9278 In any case, this is necessary, because a macro can be #undef'd
9279 in the middle of reading the arguments to a call to it.
9280 If #undef freed the DEFINITION, that would crash. */
9282 static void
9283 delete_macro (hp)
9284 HASHNODE *hp;
9287 if (hp->prev != NULL)
9288 hp->prev->next = hp->next;
9289 if (hp->next != NULL)
9290 hp->next->prev = hp->prev;
9292 /* Make sure that the bucket chain header that the deleted guy was
9293 on points to the right thing afterwards. */
9294 if (hp == *hp->bucket_hdr)
9295 *hp->bucket_hdr = hp->next;
9297 #if 0
9298 if (hp->type == T_MACRO) {
9299 DEFINITION *d = hp->value.defn;
9300 struct reflist *ap, *nextap;
9302 for (ap = d->pattern; ap != NULL; ap = nextap) {
9303 nextap = ap->next;
9304 free (ap);
9306 free (d);
9308 #endif
9309 free (hp);
9313 * return hash function on name. must be compatible with the one
9314 * computed a step at a time, elsewhere
9317 static int
9318 hashf (name, len, hashsize)
9319 register U_CHAR *name;
9320 register int len;
9321 int hashsize;
9323 register int r = 0;
9325 while (len--)
9326 r = HASHSTEP (r, *name++);
9328 return MAKE_POS (r) % hashsize;
9332 /* Dump the definition of a single macro HP to OF. */
9334 static void
9335 dump_single_macro (hp, of)
9336 register HASHNODE *hp;
9337 FILE *of;
9339 register DEFINITION *defn = hp->value.defn;
9340 struct reflist *ap;
9341 int offset;
9342 int concat;
9345 /* Print the definition of the macro HP. */
9347 fprintf (of, "#define %s", hp->name);
9349 if (defn->nargs >= 0) {
9350 int i;
9352 fprintf (of, "(");
9353 for (i = 0; i < defn->nargs; i++) {
9354 dump_arg_n (defn, i, of);
9355 if (i + 1 < defn->nargs)
9356 fprintf (of, ", ");
9358 fprintf (of, ")");
9361 fprintf (of, " ");
9363 offset = 0;
9364 concat = 0;
9365 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9366 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9367 offset += ap->nchars;
9368 if (!traditional) {
9369 if (ap->nchars != 0)
9370 concat = 0;
9371 if (ap->stringify) {
9372 switch (ap->stringify) {
9373 case SHARP_TOKEN: fprintf (of, "#"); break;
9374 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9375 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9376 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9377 default: abort ();
9380 if (ap->raw_before != 0) {
9381 if (concat) {
9382 switch (ap->raw_before) {
9383 case WHITE_SHARP_TOKEN:
9384 case WHITE_PERCENT_COLON_TOKEN:
9385 fprintf (of, " ");
9386 break;
9387 default:
9388 break;
9390 } else {
9391 switch (ap->raw_before) {
9392 case SHARP_TOKEN: fprintf (of, "##"); break;
9393 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9394 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9395 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9396 default: abort ();
9400 concat = 0;
9402 dump_arg_n (defn, ap->argno, of);
9403 if (!traditional && ap->raw_after != 0) {
9404 switch (ap->raw_after) {
9405 case SHARP_TOKEN: fprintf (of, "##"); break;
9406 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9407 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9408 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9409 default: abort ();
9411 concat = 1;
9414 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9415 fprintf (of, "\n");
9418 /* Dump all macro definitions as #defines to stdout. */
9420 static void
9421 dump_all_macros ()
9423 int bucket;
9425 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9426 register HASHNODE *hp;
9428 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9429 if (hp->type == T_MACRO)
9430 dump_single_macro (hp, stdout);
9435 /* Output to OF a substring of a macro definition.
9436 BASE is the beginning of the definition.
9437 Output characters START thru LENGTH.
9438 Unless traditional, discard newlines outside of strings, thus
9439 converting funny-space markers to ordinary spaces. */
9441 static void
9442 dump_defn_1 (base, start, length, of)
9443 U_CHAR *base;
9444 int start;
9445 int length;
9446 FILE *of;
9448 U_CHAR *p = base + start;
9449 U_CHAR *limit = base + start + length;
9451 if (traditional)
9452 fwrite (p, sizeof (*p), length, of);
9453 else {
9454 while (p < limit) {
9455 if (*p == '\"' || *p =='\'') {
9456 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9457 NULL_PTR, NULL_PTR);
9458 fwrite (p, sizeof (*p), p1 - p, of);
9459 p = p1;
9460 } else {
9461 if (*p != '\n')
9462 putc (*p, of);
9463 p++;
9469 /* Print the name of argument number ARGNUM of macro definition DEFN
9470 to OF.
9471 Recall that DEFN->args.argnames contains all the arg names
9472 concatenated in reverse order with comma-space in between. */
9474 static void
9475 dump_arg_n (defn, argnum, of)
9476 DEFINITION *defn;
9477 int argnum;
9478 FILE *of;
9480 register U_CHAR *p = defn->args.argnames;
9481 while (argnum + 1 < defn->nargs) {
9482 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9483 argnum++;
9486 while (*p && *p != ',') {
9487 putc (*p, of);
9488 p++;
9492 /* Initialize syntactic classifications of characters. */
9494 static void
9495 initialize_char_syntax ()
9497 register int i;
9500 * Set up is_idchar and is_idstart tables. These should be
9501 * faster than saying (is_alpha (c) || c == '_'), etc.
9502 * Set up these things before calling any routines tthat
9503 * refer to them.
9505 for (i = 'a'; i <= 'z'; i++) {
9506 is_idchar[i - 'a' + 'A'] = 1;
9507 is_idchar[i] = 1;
9508 is_idstart[i - 'a' + 'A'] = 1;
9509 is_idstart[i] = 1;
9511 for (i = '0'; i <= '9'; i++)
9512 is_idchar[i] = 1;
9513 is_idchar['_'] = 1;
9514 is_idstart['_'] = 1;
9515 is_idchar['$'] = 1;
9516 is_idstart['$'] = 1;
9518 /* horizontal space table */
9519 is_hor_space[' '] = 1;
9520 is_hor_space['\t'] = 1;
9521 is_hor_space['\v'] = 1;
9522 is_hor_space['\f'] = 1;
9523 is_hor_space['\r'] = 1;
9525 is_space[' '] = 1;
9526 is_space['\t'] = 1;
9527 is_space['\v'] = 1;
9528 is_space['\f'] = 1;
9529 is_space['\n'] = 1;
9530 is_space['\r'] = 1;
9532 char_name['\v'] = "vertical tab";
9533 char_name['\f'] = "formfeed";
9534 char_name['\r'] = "carriage return";
9537 /* Initialize the built-in macros. */
9539 static void
9540 initialize_builtins (inp, outp)
9541 FILE_BUF *inp;
9542 FILE_BUF *outp;
9544 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9545 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9546 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9547 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9548 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9549 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9550 #ifndef NO_BUILTIN_SIZE_TYPE
9551 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9552 #endif
9553 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9554 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9555 #endif
9556 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9557 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9558 NULL_PTR, -1);
9559 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9560 NULL_PTR, -1);
9561 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9562 NULL_PTR, -1);
9563 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9564 if (!traditional) {
9565 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9566 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9568 if (objc)
9569 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9570 /* This is supplied using a -D by the compiler driver
9571 so that it is present only when truly compiling with GNU C. */
9572 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9573 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9575 if (debug_output)
9577 char directive[2048];
9578 U_CHAR *udirective = (U_CHAR *) directive;
9579 register struct directive *dp = &directive_table[0];
9580 struct tm *timebuf = timestamp ();
9582 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9583 instack[0].nominal_fname);
9584 output_line_directive (inp, outp, 0, same_file);
9585 pass_thru_directive (udirective, &udirective[strlen (directive)],
9586 outp, dp);
9588 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9589 output_line_directive (inp, outp, 0, same_file);
9590 pass_thru_directive (udirective, &udirective[strlen (directive)],
9591 outp, dp);
9593 #ifndef NO_BUILTIN_SIZE_TYPE
9594 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9595 output_line_directive (inp, outp, 0, same_file);
9596 pass_thru_directive (udirective, &udirective[strlen (directive)],
9597 outp, dp);
9598 #endif
9600 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9601 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9602 output_line_directive (inp, outp, 0, same_file);
9603 pass_thru_directive (udirective, &udirective[strlen (directive)],
9604 outp, dp);
9605 #endif
9607 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9608 output_line_directive (inp, outp, 0, same_file);
9609 pass_thru_directive (udirective, &udirective[strlen (directive)],
9610 outp, dp);
9612 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9613 monthnames[timebuf->tm_mon],
9614 timebuf->tm_mday, timebuf->tm_year + 1900);
9615 output_line_directive (inp, outp, 0, same_file);
9616 pass_thru_directive (udirective, &udirective[strlen (directive)],
9617 outp, dp);
9619 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9620 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9621 output_line_directive (inp, outp, 0, same_file);
9622 pass_thru_directive (udirective, &udirective[strlen (directive)],
9623 outp, dp);
9625 if (!traditional)
9627 sprintf (directive, " __STDC__ 1");
9628 output_line_directive (inp, outp, 0, same_file);
9629 pass_thru_directive (udirective, &udirective[strlen (directive)],
9630 outp, dp);
9632 if (objc)
9634 sprintf (directive, " __OBJC__ 1");
9635 output_line_directive (inp, outp, 0, same_file);
9636 pass_thru_directive (udirective, &udirective[strlen (directive)],
9637 outp, dp);
9643 * process a given definition string, for initialization
9644 * If STR is just an identifier, define it with value 1.
9645 * If STR has anything after the identifier, then it should
9646 * be identifier=definition.
9649 static void
9650 make_definition (str, op)
9651 char *str;
9652 FILE_BUF *op;
9654 FILE_BUF *ip;
9655 struct directive *kt;
9656 U_CHAR *buf, *p;
9658 p = buf = (U_CHAR *) str;
9659 if (!is_idstart[*p]) {
9660 error ("malformed option `-D %s'", str);
9661 return;
9663 while (is_idchar[*++p])
9665 if (*p == '(') {
9666 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9668 if (*p++ != ')')
9669 p = (U_CHAR *) str; /* Error */
9671 if (*p == 0) {
9672 buf = (U_CHAR *) alloca (p - buf + 4);
9673 strcpy ((char *)buf, str);
9674 strcat ((char *)buf, " 1");
9675 } else if (*p != '=') {
9676 error ("malformed option `-D %s'", str);
9677 return;
9678 } else {
9679 U_CHAR *q;
9680 /* Copy the entire option so we can modify it. */
9681 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9682 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9683 /* Change the = to a space. */
9684 buf[p - (U_CHAR *) str] = ' ';
9685 /* Scan for any backslash-newline and remove it. */
9686 p++;
9687 q = &buf[p - (U_CHAR *) str];
9688 while (*p) {
9689 if (*p == '\"' || *p == '\'') {
9690 int unterminated = 0;
9691 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9692 NULL_PTR, NULL_PTR, &unterminated);
9693 if (unterminated)
9694 return;
9695 while (p != p1)
9696 *q++ = *p++;
9697 } else if (*p == '\\' && p[1] == '\n')
9698 p += 2;
9699 /* Change newline chars into newline-markers. */
9700 else if (*p == '\n')
9702 *q++ = '\n';
9703 *q++ = '\n';
9704 p++;
9706 else
9707 *q++ = *p++;
9709 *q = 0;
9712 ip = &instack[++indepth];
9713 ip->nominal_fname = ip->fname = "*Initialization*";
9715 ip->buf = ip->bufp = buf;
9716 ip->length = strlen ((char *) buf);
9717 ip->lineno = 1;
9718 ip->macro = 0;
9719 ip->free_ptr = 0;
9720 ip->if_stack = if_stack;
9721 ip->system_header_p = 0;
9723 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9726 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9727 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9728 --indepth;
9731 /* JF, this does the work for the -U option */
9733 static void
9734 make_undef (str, op)
9735 char *str;
9736 FILE_BUF *op;
9738 FILE_BUF *ip;
9739 struct directive *kt;
9741 ip = &instack[++indepth];
9742 ip->nominal_fname = ip->fname = "*undef*";
9744 ip->buf = ip->bufp = (U_CHAR *) str;
9745 ip->length = strlen (str);
9746 ip->lineno = 1;
9747 ip->macro = 0;
9748 ip->free_ptr = 0;
9749 ip->if_stack = if_stack;
9750 ip->system_header_p = 0;
9752 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9755 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9756 --indepth;
9759 /* Process the string STR as if it appeared as the body of a #assert.
9760 OPTION is the option name for which STR was the argument. */
9762 static void
9763 make_assertion (option, str)
9764 char *option;
9765 char *str;
9767 FILE_BUF *ip;
9768 struct directive *kt;
9769 U_CHAR *buf, *p, *q;
9771 /* Copy the entire option so we can modify it. */
9772 buf = (U_CHAR *) alloca (strlen (str) + 1);
9773 strcpy ((char *) buf, str);
9774 /* Scan for any backslash-newline and remove it. */
9775 p = q = buf;
9776 while (*p) {
9777 if (*p == '\\' && p[1] == '\n')
9778 p += 2;
9779 else
9780 *q++ = *p++;
9782 *q = 0;
9784 p = buf;
9785 if (!is_idstart[*p]) {
9786 error ("malformed option `%s %s'", option, str);
9787 return;
9789 while (is_idchar[*++p])
9791 SKIP_WHITE_SPACE (p);
9792 if (! (*p == 0 || *p == '(')) {
9793 error ("malformed option `%s %s'", option, str);
9794 return;
9797 ip = &instack[++indepth];
9798 ip->nominal_fname = ip->fname = "*Initialization*";
9800 ip->buf = ip->bufp = buf;
9801 ip->length = strlen ((char *) buf);
9802 ip->lineno = 1;
9803 ip->macro = 0;
9804 ip->free_ptr = 0;
9805 ip->if_stack = if_stack;
9806 ip->system_header_p = 0;
9808 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9811 /* Pass NULL as output ptr to do_define since we KNOW it never does
9812 any output.... */
9813 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9814 --indepth;
9817 #ifndef DIR_SEPARATOR
9818 #define DIR_SEPARATOR '/'
9819 #endif
9821 /* The previous include prefix, if any, is PREV_FILE_NAME.
9822 Translate any pathnames with COMPONENT.
9823 Allocate a new include prefix whose name is the
9824 simplified concatenation of PREFIX and NAME,
9825 with a trailing / added if needed.
9826 But return 0 if the include prefix should be ignored,
9827 e.g. because it is a duplicate of PREV_FILE_NAME. */
9829 static struct file_name_list *
9830 new_include_prefix (prev_file_name, component, prefix, name)
9831 struct file_name_list *prev_file_name;
9832 char *component;
9833 char *prefix;
9834 char *name;
9836 if (name == 0)
9837 fatal ("Directory name missing after command line option");
9839 if (*name == 0)
9840 /* Ignore the empty string. */
9841 return 0;
9843 prefix = update_path (prefix, component);
9844 name = update_path (name, component);
9847 struct file_name_list *dir
9848 = ((struct file_name_list *)
9849 xmalloc (sizeof (struct file_name_list)
9850 + strlen (prefix) + strlen (name) + 2));
9851 size_t len;
9852 strcpy (dir->fname, prefix);
9853 strcat (dir->fname, name);
9854 len = simplify_filename (dir->fname);
9856 /* Convert directory name to a prefix. */
9857 if (dir->fname[len - 1] != DIR_SEPARATOR) {
9858 if (len == 1 && dir->fname[len - 1] == '.')
9859 len = 0;
9860 else
9861 dir->fname[len++] = DIR_SEPARATOR;
9862 dir->fname[len] = 0;
9865 /* Ignore a directory whose name matches the previous one. */
9866 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9867 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9868 if (!first_bracket_include)
9869 first_bracket_include = prev_file_name;
9870 free (dir);
9871 return 0;
9874 #ifndef VMS
9875 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
9877 /* Add a trailing "." if there is a filename. This increases the number
9878 of systems that can stat directories. We remove it below. */
9879 if (len != 0)
9881 dir->fname[len] = '.';
9882 dir->fname[len + 1] = 0;
9885 /* Ignore a nonexistent directory. */
9886 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9887 if (errno != ENOENT && errno != ENOTDIR)
9888 error_from_errno (dir->fname);
9889 free (dir);
9890 return 0;
9893 if (len != 0)
9894 dir->fname[len] = 0;
9896 /* Ignore a directory whose identity matches the previous one. */
9897 if (prev_file_name
9898 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9899 && prev_file_name->st.st_dev == dir->st.st_dev) {
9900 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9901 if (!first_bracket_include)
9902 first_bracket_include = prev_file_name;
9903 free (dir);
9904 return 0;
9906 #endif /* ! VMS */
9908 dir->next = 0;
9909 dir->c_system_include_path = 0;
9910 dir->got_name_map = 0;
9912 return dir;
9916 /* Append a chain of `struct file_name_list's
9917 to the end of the main include chain.
9918 FIRST is the beginning of the chain to append, and LAST is the end. */
9920 static void
9921 append_include_chain (first, last)
9922 struct file_name_list *first, *last;
9924 struct file_name_list *dir;
9926 if (!first || !last)
9927 return;
9929 if (include == 0)
9930 include = first;
9931 else
9932 last_include->next = first;
9934 if (first_bracket_include == 0)
9935 first_bracket_include = first;
9937 for (dir = first; ; dir = dir->next) {
9938 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9939 if (len > max_include_len)
9940 max_include_len = len;
9941 if (dir == last)
9942 break;
9945 last->next = NULL;
9946 last_include = last;
9949 /* Place into DST a representation of the file named SRC that is suitable
9950 for `make'. Do not null-terminate DST. Return its length. */
9951 static int
9952 quote_string_for_make (dst, src)
9953 char *dst;
9954 char *src;
9956 char *p = src;
9957 int i = 0;
9958 for (;;)
9960 char c = *p++;
9961 switch (c)
9963 case '\0':
9964 case ' ':
9965 case '\t':
9967 /* GNU make uses a weird quoting scheme for white space.
9968 A space or tab preceded by 2N+1 backslashes represents
9969 N backslashes followed by space; a space or tab
9970 preceded by 2N backslashes represents N backslashes at
9971 the end of a file name; and backslashes in other
9972 contexts should not be doubled. */
9973 char *q;
9974 for (q = p - 1; src < q && q[-1] == '\\'; q--)
9976 if (dst)
9977 dst[i] = '\\';
9978 i++;
9981 if (!c)
9982 return i;
9983 if (dst)
9984 dst[i] = '\\';
9985 i++;
9986 goto ordinary_char;
9988 case '$':
9989 if (dst)
9990 dst[i] = c;
9991 i++;
9992 /* Fall through. This can mishandle things like "$(" but
9993 there's no easy fix. */
9994 default:
9995 ordinary_char:
9996 /* This can mishandle characters in the string "\0\n%*?[\\~";
9997 exactly which chars are mishandled depends on the `make' version.
9998 We know of no portable solution for this;
9999 even GNU make 3.76.1 doesn't solve the problem entirely.
10000 (Also, '\0' is mishandled due to our calling conventions.) */
10001 if (dst)
10002 dst[i] = c;
10003 i++;
10004 break;
10010 /* Add output to `deps_buffer' for the -M switch.
10011 STRING points to the text to be output.
10012 SPACER is ':' for targets, ' ' for dependencies. */
10014 static void
10015 deps_output (string, spacer)
10016 char *string;
10017 int spacer;
10019 int size = quote_string_for_make ((char *) 0, string);
10021 if (size == 0)
10022 return;
10024 #ifndef MAX_OUTPUT_COLUMNS
10025 #define MAX_OUTPUT_COLUMNS 72
10026 #endif
10027 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10028 && 1 < deps_column) {
10029 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10030 deps_size += 4;
10031 deps_column = 1;
10032 if (spacer == ' ')
10033 spacer = 0;
10036 if (deps_size + size + 8 > deps_allocated_size) {
10037 deps_allocated_size = (deps_size + size + 50) * 2;
10038 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10040 if (spacer == ' ') {
10041 deps_buffer[deps_size++] = ' ';
10042 deps_column++;
10044 quote_string_for_make (&deps_buffer[deps_size], string);
10045 deps_size += size;
10046 deps_column += size;
10047 if (spacer == ':') {
10048 deps_buffer[deps_size++] = ':';
10049 deps_column++;
10051 deps_buffer[deps_size] = 0;
10054 static void
10055 fatal (PRINTF_ALIST (msg))
10056 PRINTF_DCL (msg)
10058 va_list args;
10060 fprintf (stderr, "%s: ", progname);
10061 VA_START (args, msg);
10062 vfprintf (stderr, msg, args);
10063 va_end (args);
10064 fprintf (stderr, "\n");
10065 exit (FATAL_EXIT_CODE);
10068 /* More 'friendly' abort that prints the line and file.
10069 config.h can #define abort fancy_abort if you like that sort of thing. */
10071 void
10072 fancy_abort ()
10074 fatal ("Internal gcc abort.");
10077 static void
10078 perror_with_name (name)
10079 char *name;
10081 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10082 errors++;
10085 static void
10086 pfatal_with_name (name)
10087 char *name;
10089 perror_with_name (name);
10090 #ifdef VMS
10091 exit (vaxc$errno);
10092 #else
10093 exit (FATAL_EXIT_CODE);
10094 #endif
10097 /* Handler for SIGPIPE. */
10099 static void
10100 pipe_closed (signo)
10101 /* If this is missing, some compilers complain. */
10102 int signo;
10104 fatal ("output pipe has been closed");
10107 static void
10108 memory_full ()
10110 fatal ("Memory exhausted.");
10114 GENERIC_PTR
10115 xmalloc (size)
10116 size_t size;
10118 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10119 if (!ptr)
10120 memory_full ();
10121 return ptr;
10124 static GENERIC_PTR
10125 xrealloc (old, size)
10126 GENERIC_PTR old;
10127 size_t size;
10129 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10130 if (!ptr)
10131 memory_full ();
10132 return ptr;
10135 static GENERIC_PTR
10136 xcalloc (number, size)
10137 size_t number, size;
10139 register size_t total = number * size;
10140 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10141 if (!ptr)
10142 memory_full ();
10143 bzero (ptr, total);
10144 return ptr;
10147 static char *
10148 savestring (input)
10149 char *input;
10151 size_t size = strlen (input);
10152 char *output = xmalloc (size + 1);
10153 strcpy (output, input);
10154 return output;
10157 #ifdef VMS
10159 /* Under VMS we need to fix up the "include" specification filename so
10160 that everything following the 1st slash is changed into its correct
10161 VMS file specification. */
10163 static void
10164 hack_vms_include_specification (fname, vaxc_include)
10165 char *fname;
10166 int vaxc_include;
10168 register char *cp, *cp1, *cp2;
10169 int f, check_filename_before_returning;
10170 char Local[512];
10172 check_filename_before_returning = 0;
10174 cp = base_name (fname);
10177 * Check if we have a vax-c style '#include filename'
10178 * and add the missing .h
10180 if (vaxc_include && !index (cp,'.'))
10181 strcat (cp, ".h");
10183 cp2 = Local; /* initialize */
10185 /* We are trying to do a number of things here. First of all, we are
10186 trying to hammer the filenames into a standard format, such that later
10187 processing can handle them.
10189 If the file name contains something like [dir.], then it recognizes this
10190 as a root, and strips the ".]". Later processing will add whatever is
10191 needed to get things working properly.
10193 If no device is specified, then the first directory name is taken to be
10194 a device name (or a rooted logical). */
10196 /* See if we found that 1st slash */
10197 if (cp == 0) return; /* Nothing to do!!! */
10198 if (*cp != '/') return; /* Nothing to do!!! */
10199 /* Point to the UNIX filename part (which needs to be fixed!) */
10200 cp1 = cp+1;
10201 /* If the directory spec is not rooted, we can just copy
10202 the UNIX filename part and we are done */
10203 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10204 if (cp[-2] != '.') {
10206 * The VMS part ends in a `]', and the preceding character is not a `.'.
10207 * We strip the `]', and then splice the two parts of the name in the
10208 * usual way. Given the default locations for include files in cccp.c,
10209 * we will only use this code if the user specifies alternate locations
10210 * with the /include (-I) switch on the command line. */
10211 cp -= 1; /* Strip "]" */
10212 cp1--; /* backspace */
10213 } else {
10215 * The VMS part has a ".]" at the end, and this will not do. Later
10216 * processing will add a second directory spec, and this would be a syntax
10217 * error. Thus we strip the ".]", and thus merge the directory specs.
10218 * We also backspace cp1, so that it points to a '/'. This inhibits the
10219 * generation of the 000000 root directory spec (which does not belong here
10220 * in this case).
10222 cp -= 2; /* Strip ".]" */
10223 cp1--; }; /* backspace */
10224 } else {
10226 /* We drop in here if there is no VMS style directory specification yet.
10227 * If there is no device specification either, we make the first dir a
10228 * device and try that. If we do not do this, then we will be essentially
10229 * searching the users default directory (as if they did a #include "asdf.h").
10231 * Then all we need to do is to push a '[' into the output string. Later
10232 * processing will fill this in, and close the bracket.
10234 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10235 *cp2++ = '['; /* Open the directory specification */
10238 /* at this point we assume that we have the device spec, and (at least
10239 the opening "[" for a directory specification. We may have directories
10240 specified already */
10242 /* If there are no other slashes then the filename will be
10243 in the "root" directory. Otherwise, we need to add
10244 directory specifications. */
10245 if (index (cp1, '/') == 0) {
10246 /* Just add "000000]" as the directory string */
10247 strcpy (cp2, "000000]");
10248 cp2 += strlen (cp2);
10249 check_filename_before_returning = 1; /* we might need to fool with this later */
10250 } else {
10251 /* As long as there are still subdirectories to add, do them. */
10252 while (index (cp1, '/') != 0) {
10253 /* If this token is "." we can ignore it */
10254 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10255 cp1 += 2;
10256 continue;
10258 /* Add a subdirectory spec. Do not duplicate "." */
10259 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10260 *cp2++ = '.';
10261 /* If this is ".." then the spec becomes "-" */
10262 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10263 /* Add "-" and skip the ".." */
10264 *cp2++ = '-';
10265 cp1 += 3;
10266 continue;
10268 /* Copy the subdirectory */
10269 while (*cp1 != '/') *cp2++= *cp1++;
10270 cp1++; /* Skip the "/" */
10272 /* Close the directory specification */
10273 if (cp2[-1] == '.') /* no trailing periods */
10274 cp2--;
10275 *cp2++ = ']';
10277 /* Now add the filename */
10278 while (*cp1) *cp2++ = *cp1++;
10279 *cp2 = 0;
10280 /* Now append it to the original VMS spec. */
10281 strcpy (cp, Local);
10283 /* If we put a [000000] in the filename, try to open it first. If this fails,
10284 remove the [000000], and return that name. This provides flexibility
10285 to the user in that they can use both rooted and non-rooted logical names
10286 to point to the location of the file. */
10288 if (check_filename_before_returning) {
10289 f = open (fname, O_RDONLY, 0666);
10290 if (f >= 0) {
10291 /* The file name is OK as it is, so return it as is. */
10292 close (f);
10293 return;
10295 /* The filename did not work. Try to remove the [000000] from the name,
10296 and return it. */
10297 cp = index (fname, '[');
10298 cp2 = index (fname, ']') + 1;
10299 strcpy (cp, cp2); /* this gets rid of it */
10301 return;
10303 #endif /* VMS */
10305 #ifdef VMS
10307 /* The following wrapper functions supply additional arguments to the VMS
10308 I/O routines to optimize performance with file handling. The arguments
10309 are:
10310 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10311 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10312 "fop=tef"- Truncate unused portions of file when closing file.
10313 "shr=nil"- Disallow file sharing while file is open. */
10315 static FILE *
10316 VMS_freopen (fname, type, oldfile)
10317 char *fname;
10318 char *type;
10319 FILE *oldfile;
10321 #undef freopen /* Get back the real freopen routine. */
10322 if (strcmp (type, "w") == 0)
10323 return freopen (fname, type, oldfile,
10324 "mbc=16", "deq=64", "fop=tef", "shr=nil");
10325 return freopen (fname, type, oldfile, "mbc=16");
10328 static FILE *
10329 VMS_fopen (fname, type)
10330 char *fname;
10331 char *type;
10333 #undef fopen /* Get back the real fopen routine. */
10334 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10335 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10336 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10337 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10339 if (*type == 'w')
10340 return (*vmslib_fopen) (fname, type, "mbc=32",
10341 "deq=64", "fop=tef", "shr=nil");
10342 else
10343 return (*vmslib_fopen) (fname, type, "mbc=32");
10346 static int
10347 VMS_open (fname, flags, prot)
10348 char *fname;
10349 int flags;
10350 int prot;
10352 #undef open /* Get back the real open routine. */
10353 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10356 /* more VMS hackery */
10357 #include <fab.h>
10358 #include <nam.h>
10360 extern unsigned long sys$parse(), sys$search();
10362 /* Work around another library bug. If a file is located via a searchlist,
10363 and if the device it's on is not the same device as the one specified
10364 in the first element of that searchlist, then both stat() and fstat()
10365 will fail to return info about it. `errno' will be set to EVMSERR, and
10366 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10367 We can get around this by fully parsing the filename and then passing
10368 that absolute name to stat().
10370 Without this fix, we can end up failing to find header files, which is
10371 bad enough, but then compounding the problem by reporting the reason for
10372 failure as "normal successful completion." */
10374 #undef fstat /* Get back to the library version. */
10376 static int
10377 VMS_fstat (fd, statbuf)
10378 int fd;
10379 struct stat *statbuf;
10381 int result = fstat (fd, statbuf);
10383 if (result < 0)
10385 FILE *fp;
10386 char nambuf[NAM$C_MAXRSS+1];
10388 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10389 result = VMS_stat (nambuf, statbuf);
10390 /* No fclose(fp) here; that would close(fd) as well. */
10393 return result;
10396 static int
10397 VMS_stat (name, statbuf)
10398 const char *name;
10399 struct stat *statbuf;
10401 int result = stat (name, statbuf);
10403 if (result < 0)
10405 struct FAB fab;
10406 struct NAM nam;
10407 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for sys$parse */
10408 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for sys$search */
10410 fab = cc$rms_fab;
10411 fab.fab$l_fna = (char *) name;
10412 fab.fab$b_fns = (unsigned char) strlen (name);
10413 fab.fab$l_nam = (void *) &nam;
10414 nam = cc$rms_nam;
10415 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10416 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10417 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10418 if (sys$parse (&fab) & 1)
10420 if (sys$search (&fab) & 1)
10422 res_nam[nam.nam$b_rsl] = '\0';
10423 result = stat (res_nam, statbuf);
10425 /* Clean up searchlist context cached by the system. */
10426 nam.nam$b_nop = NAM$M_SYNCHK;
10427 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10428 (void) sys$parse (&fab);
10432 return result;
10434 #endif /* VMS */