--with-gnu-ld uses different x- fiile under aix 4.1
[official-gcc.git] / gcc / cccp.c
blob39f2dac3580f5e84a327b4144a6fd01f2962c2ab
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-98, 1999 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"
23 #define PRINTF_PROTO(ARGS, m, n) PVPROTO (ARGS) ATTRIBUTE_PRINTF(m, n)
25 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
26 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
27 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
28 #define PRINTF_PROTO_4(ARGS) PRINTF_PROTO(ARGS, 4, 5)
30 #include "system.h"
31 #include <signal.h>
33 #ifdef HAVE_SYS_RESOURCE_H
34 # include <sys/resource.h>
35 #endif
37 typedef unsigned char U_CHAR;
39 #include "pcp.h"
40 #include "prefix.h"
42 #ifdef MULTIBYTE_CHARS
43 #include "mbchar.h"
44 #include <locale.h>
45 #endif /* MULTIBYTE_CHARS */
47 #ifndef GET_ENV_PATH_LIST
48 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
49 #endif
51 #ifndef STANDARD_INCLUDE_DIR
52 # define STANDARD_INCLUDE_DIR "/usr/include"
53 #endif
55 /* By default, colon separates directories in a path. */
56 #ifndef PATH_SEPARATOR
57 # define PATH_SEPARATOR ':'
58 #endif
60 /* By default, the suffix for object files is ".o". */
61 #ifdef OBJECT_SUFFIX
62 # define HAVE_OBJECT_SUFFIX
63 #else
64 # define OBJECT_SUFFIX ".o"
65 #endif
67 /* VMS-specific definitions */
68 #ifdef VMS
69 #include <descrip.h>
70 #include <ssdef.h>
71 #include <syidef.h>
72 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
73 #define fopen(fname,mode) VMS_fopen (fname,mode)
74 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
75 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
76 static int VMS_fstat (), VMS_stat ();
77 static int VMS_open ();
78 static FILE *VMS_fopen ();
79 static FILE *VMS_freopen ();
80 static int hack_vms_include_specification ();
81 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
82 #define INO_T_HASH(a) 0
83 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
84 #endif /* VMS */
86 /* Windows does not natively support inodes, and neither does MSDOS. */
87 #if (defined (_WIN32) && ! defined (__CYGWIN__)) || defined (__MSDOS__)
88 #define INO_T_EQ(a, b) 0
89 #endif
91 /* Find the largest host integer type and set its size and type.
92 Watch out: on some crazy hosts `long' is shorter than `int'. */
94 #ifndef HOST_WIDE_INT
95 # if HAVE_INTTYPES_H
96 # include <inttypes.h>
97 # define HOST_WIDE_INT intmax_t
98 # else
99 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
100 # define HOST_WIDE_INT int
101 # else
102 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
103 # define HOST_WIDE_INT long
104 # else
105 # define HOST_WIDE_INT long long
106 # endif
107 # endif
108 # endif
109 #endif
111 #ifndef INO_T_EQ
112 #define INO_T_EQ(a, b) ((a) == (b))
113 #endif
115 #ifndef INO_T_HASH
116 #define INO_T_HASH(a) (a)
117 #endif
119 #ifndef INCLUDE_LEN_FUDGE
120 #define INCLUDE_LEN_FUDGE 0
121 #endif
123 /* External declarations. */
125 extern char *version_string;
126 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
127 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
129 /* Name under which this program was invoked. */
131 static char *progname;
133 /* Nonzero means use extra default include directories for C++. */
135 static int cplusplus;
137 /* Nonzero means handle cplusplus style comments */
139 static int cplusplus_comments;
141 /* Nonzero means handle #import, for objective C. */
143 static int objc;
145 /* Nonzero means this is an assembly file, and allow
146 unknown directives, which could be comments. */
148 static int lang_asm;
150 /* Current maximum length of directory names in the search path
151 for include files. (Altered as we get more of them.) */
153 static int max_include_len;
155 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
157 static int for_lint = 0;
159 /* Nonzero means copy comments into the output file. */
161 static int put_out_comments = 0;
163 /* Nonzero means don't process the ANSI trigraph sequences. */
165 static int no_trigraphs = 0;
167 /* Nonzero means print the names of included files rather than
168 the preprocessed output. 1 means just the #include "...",
169 2 means #include <...> as well. */
171 static int print_deps = 0;
173 /* Nonzero if missing .h files in -M output are assumed to be generated
174 files and not errors. */
176 static int print_deps_missing_files = 0;
178 /* Nonzero means print names of header files (-H). */
180 static int print_include_names = 0;
182 /* Nonzero means don't output line number information. */
184 static int no_line_directives;
186 /* Nonzero means output the text in failing conditionals,
187 inside #failed ... #endfailed. */
189 static int output_conditionals;
191 /* dump_only means inhibit output of the preprocessed text
192 and instead output the definitions of all user-defined
193 macros in a form suitable for use as input to cccp.
194 dump_names means pass #define and the macro name through to output.
195 dump_definitions means pass the whole definition (plus #define) through
198 static enum {dump_none, dump_only, dump_names, dump_definitions}
199 dump_macros = dump_none;
201 /* Nonzero means pass all #define and #undef directives which we actually
202 process through to the output stream. This feature is used primarily
203 to allow cc1 to record the #defines and #undefs for the sake of
204 debuggers which understand about preprocessor macros, but it may
205 also be useful with -E to figure out how symbols are defined, and
206 where they are defined. */
207 static int debug_output = 0;
209 /* Nonzero means pass #include lines through to the output,
210 even if they are ifdefed out. */
211 static int dump_includes;
213 /* Nonzero indicates special processing used by the pcp program. The
214 special effects of this mode are:
216 Inhibit all macro expansion, except those inside #if directives.
218 Process #define directives normally, and output their contents
219 to the output file.
221 Output preconditions to pcp_outfile indicating all the relevant
222 preconditions for use of this file in a later cpp run.
224 static FILE *pcp_outfile;
226 /* Nonzero means we are inside an IF during a -pcp run. In this mode
227 macro expansion is done, and preconditions are output for all macro
228 uses requiring them. */
229 static int pcp_inside_if;
231 /* Nonzero means never to include precompiled files.
232 This is 1 since there's no way now to make precompiled files,
233 so it's not worth testing for them. */
234 static int no_precomp = 1;
236 /* Nonzero means give all the error messages the ANSI standard requires. */
238 int pedantic;
240 /* Nonzero means try to make failure to fit ANSI C an error. */
242 static int pedantic_errors;
244 /* Nonzero means don't print warning messages. -w. */
246 static int inhibit_warnings = 0;
248 /* Nonzero means warn if slash-star appears in a slash-star comment,
249 or if newline-backslash appears in a slash-slash comment. */
251 static int warn_comments;
253 /* Nonzero means warn if a macro argument is (or would be)
254 stringified with -traditional. */
256 static int warn_stringify;
258 /* Nonzero means warn if there are any trigraphs. */
260 static int warn_trigraphs;
262 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
264 static int warn_undef;
266 /* Nonzero means warn if #import is used. */
268 static int warn_import = 1;
270 /* Nonzero means turn warnings into errors. */
272 static int warnings_are_errors;
274 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
276 int traditional;
278 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
280 int c89;
282 /* Nonzero for the 199x C Standard. */
284 int c9x;
286 /* Nonzero causes output not to be done,
287 but directives such as #define that have side effects
288 are still obeyed. */
290 static int no_output;
292 /* Nonzero means we should look for header.gcc files that remap file names. */
293 static int remap;
295 /* Nonzero means this file was included with a -imacros or -include
296 command line and should not be recorded as an include file. */
298 static int no_record_file;
300 /* Nonzero means that we have finished processing the command line options.
301 This flag is used to decide whether or not to issue certain errors
302 and/or warnings. */
304 static int done_initializing = 0;
306 /* Line where a newline was first seen in a string constant. */
308 static int multiline_string_line = 0;
310 /* I/O buffer structure.
311 The `fname' field is nonzero for source files and #include files
312 and for the dummy text used for -D and -U.
313 It is zero for rescanning results of macro expansion
314 and for expanding macro arguments. */
315 #define INPUT_STACK_MAX 400
316 static struct file_buf {
317 char *fname;
318 /* Filename specified with #line directive. */
319 char *nominal_fname;
320 /* The length of nominal_fname, which may contain embedded NULs. */
321 size_t nominal_fname_len;
322 /* Include file description. */
323 struct include_file *inc;
324 /* Record where in the search path this file was found.
325 For #include_next. */
326 struct file_name_list *dir;
327 int lineno;
328 int length;
329 U_CHAR *buf;
330 U_CHAR *bufp;
331 /* Macro that this level is the expansion of.
332 Included so that we can reenable the macro
333 at the end of this level. */
334 struct hashnode *macro;
335 /* Value of if_stack at start of this file.
336 Used to prohibit unmatched #endif (etc) in an include file. */
337 struct if_stack *if_stack;
338 /* Object to be freed at end of input at this level. */
339 U_CHAR *free_ptr;
340 /* True if this is a system header file; see is_system_include. */
341 char system_header_p;
342 } instack[INPUT_STACK_MAX];
344 static int last_error_tick; /* Incremented each time we print it. */
345 static int input_file_stack_tick; /* Incremented when the status changes. */
347 /* Current nesting level of input sources.
348 `instack[indepth]' is the level currently being read. */
349 static int indepth = -1;
350 #define CHECK_DEPTH(code) \
351 if (indepth >= (INPUT_STACK_MAX - 1)) \
353 error_with_line (line_for_error (instack[indepth].lineno), \
354 "macro or `#include' recursion too deep"); \
355 code; \
358 /* Current depth in #include directives that use <...>. */
359 static int system_include_depth = 0;
361 typedef struct file_buf FILE_BUF;
363 /* The output buffer. Its LENGTH field is the amount of room allocated
364 for the buffer, not the number of chars actually present. To get
365 that, subtract outbuf.buf from outbuf.bufp. */
367 #define OUTBUF_SIZE 10 /* initial size of output buffer */
368 static FILE_BUF outbuf;
370 /* Grow output buffer OBUF points at
371 so it can hold at least NEEDED more chars. */
373 #define check_expand(OBUF, NEEDED) \
374 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
375 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
377 struct file_name_list
379 struct file_name_list *next;
380 /* If the following is 1, it is a C-language system include
381 directory. */
382 int c_system_include_path;
383 /* Mapping of file names for this directory. */
384 struct file_name_map *name_map;
385 /* Non-zero if name_map is valid. */
386 int got_name_map;
387 /* The include directory status. */
388 struct stat st;
389 /* The include prefix: "" denotes the working directory,
390 otherwise fname must end in '/'.
391 The actual size is dynamically allocated. */
392 char fname[1];
395 /* #include "file" looks in source file dir, then stack. */
396 /* #include <file> just looks in the stack. */
397 /* -I directories are added to the end, then the defaults are added. */
398 /* The */
399 static struct default_include {
400 char *fname; /* The name of the directory. */
401 char *component; /* The component containing the directory */
402 int cplusplus; /* Only look here if we're compiling C++. */
403 int cxx_aware; /* Includes in this directory don't need to
404 be wrapped in extern "C" when compiling
405 C++. */
406 } include_defaults_array[]
407 #ifdef INCLUDE_DEFAULTS
408 = INCLUDE_DEFAULTS;
409 #else
411 /* Pick up GNU C++ specific include files. */
412 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
413 #ifdef CROSS_COMPILE
414 /* This is the dir for fixincludes. Put it just before
415 the files that we fix. */
416 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
417 /* For cross-compilation, this dir name is generated
418 automatically in Makefile.in. */
419 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
420 #ifdef TOOL_INCLUDE_DIR
421 /* This is another place that the target system's headers might be. */
422 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
423 #endif
424 #else /* not CROSS_COMPILE */
425 #ifdef LOCAL_INCLUDE_DIR
426 /* This should be /usr/local/include and should come before
427 the fixincludes-fixed header files. */
428 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
429 #endif
430 #ifdef TOOL_INCLUDE_DIR
431 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
432 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
433 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
434 #endif
435 /* This is the dir for fixincludes. Put it just before
436 the files that we fix. */
437 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
438 /* Some systems have an extra dir of include files. */
439 #ifdef SYSTEM_INCLUDE_DIR
440 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
441 #endif
442 #ifndef STANDARD_INCLUDE_COMPONENT
443 #define STANDARD_INCLUDE_COMPONENT 0
444 #endif
445 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
446 #endif /* not CROSS_COMPILE */
447 { 0, 0, 0, 0 }
449 #endif /* no INCLUDE_DEFAULTS */
451 /* The code looks at the defaults through this pointer, rather than through
452 the constant structure above. This pointer gets changed if an environment
453 variable specifies other defaults. */
454 static struct default_include *include_defaults = include_defaults_array;
456 static struct file_name_list *include = 0; /* First dir to search */
457 /* First dir to search for <file> */
458 /* This is the first element to use for #include <...>.
459 If it is 0, use the entire chain for such includes. */
460 static struct file_name_list *first_bracket_include = 0;
461 /* This is the first element in the chain that corresponds to
462 a directory of system header files. */
463 static struct file_name_list *first_system_include = 0;
464 static struct file_name_list *last_include = 0; /* Last in chain */
466 /* Chain of include directories to put at the end of the other chain. */
467 static struct file_name_list *after_include = 0;
468 static struct file_name_list *last_after_include = 0; /* Last in chain */
470 /* Chain to put at the start of the system include files. */
471 static struct file_name_list *before_system = 0;
472 static struct file_name_list *last_before_system = 0; /* Last in chain */
474 /* Directory prefix that should replace `/usr' in the standard
475 include file directories. */
476 static char *include_prefix;
478 /* Maintain and search list of included files. */
480 struct include_file {
481 struct include_file *next; /* for include_hashtab */
482 struct include_file *next_ino; /* for include_ino_hashtab */
483 char *fname;
484 /* If the following is the empty string, it means #pragma once
485 was seen in this include file, or #import was applied to the file.
486 Otherwise, if it is nonzero, it is a macro name.
487 Don't include the file again if that macro is defined. */
488 U_CHAR *control_macro;
489 /* Nonzero if the dependency on this include file has been output. */
490 int deps_output;
491 struct stat st;
494 /* Hash tables of files already included with #include or #import.
495 include_hashtab is by full name; include_ino_hashtab is by inode number. */
497 #define INCLUDE_HASHSIZE 61
498 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
499 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
501 /* Global list of strings read in from precompiled files. This list
502 is kept in the order the strings are read in, with new strings being
503 added at the end through stringlist_tailp. We use this list to output
504 the strings at the end of the run.
506 static STRINGDEF *stringlist;
507 static STRINGDEF **stringlist_tailp = &stringlist;
510 /* Structure returned by create_definition */
511 typedef struct macrodef MACRODEF;
512 struct macrodef
514 struct definition *defn;
515 U_CHAR *symnam;
516 int symlen;
519 enum sharp_token_type {
520 NO_SHARP_TOKEN = 0, /* token not present */
522 SHARP_TOKEN = '#', /* token spelled with # only */
523 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
525 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
526 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
529 /* Structure allocated for every #define. For a simple replacement
530 such as
531 #define foo bar ,
532 nargs = -1, the `pattern' list is null, and the expansion is just
533 the replacement text. Nargs = 0 means a functionlike macro with no args,
534 e.g.,
535 #define getchar() getc (stdin) .
536 When there are args, the expansion is the replacement text with the
537 args squashed out, and the reflist is a list describing how to
538 build the output from the input: e.g., "3 chars, then the 1st arg,
539 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
540 The chars here come from the expansion. Whatever is left of the
541 expansion after the last arg-occurrence is copied after that arg.
542 Note that the reflist can be arbitrarily long---
543 its length depends on the number of times the arguments appear in
544 the replacement text, not how many args there are. Example:
545 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
546 pattern list
547 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
548 where (x, y) means (nchars, argno). */
550 typedef struct definition DEFINITION;
551 struct definition {
552 int nargs;
553 int length; /* length of expansion string */
554 int predefined; /* True if the macro was builtin or */
555 /* came from the command line */
556 U_CHAR *expansion;
557 int line; /* Line number of definition */
558 char *file; /* File of definition */
559 size_t file_len; /* Length of file (which can contain NULs) */
560 char rest_args; /* Nonzero if last arg. absorbs the rest */
561 struct reflist {
562 struct reflist *next;
564 enum sharp_token_type stringify; /* set if a # operator before arg */
565 enum sharp_token_type raw_before; /* set if a ## operator before arg */
566 enum sharp_token_type raw_after; /* set if a ## operator after arg */
568 char rest_args; /* Nonzero if this arg. absorbs the rest */
569 int nchars; /* Number of literal chars to copy before
570 this arg occurrence. */
571 int argno; /* Number of arg to substitute (origin-0) */
572 } *pattern;
573 union {
574 /* Names of macro args, concatenated in reverse order
575 with comma-space between them.
576 The only use of this is that we warn on redefinition
577 if this differs between the old and new definitions. */
578 U_CHAR *argnames;
579 } args;
582 /* different kinds of things that can appear in the value field
583 of a hash node. Actually, this may be useless now. */
584 union hashval {
585 char *cpval;
586 DEFINITION *defn;
587 KEYDEF *keydef;
591 * special extension string that can be added to the last macro argument to
592 * allow it to absorb the "rest" of the arguments when expanded. Ex:
593 * #define wow(a, b...) process (b, a, b)
594 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
595 * { wow (one, two); } -> { process (two, one, two); }
596 * if this "rest_arg" is used with the concat token '##' and if it is not
597 * supplied then the token attached to with ## will not be outputted. Ex:
598 * #define wow (a, b...) process (b ## , a, ## b)
599 * { wow (1, 2); } -> { process (2, 1, 2); }
600 * { wow (one); } -> { process (one); {
602 static char rest_extension[] = "...";
603 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
605 /* This is the implicit parameter name when using variable number of
606 parameters for macros using the ISO C 9x extension. */
607 static char va_args_name[] = "__VA_ARGS__";
608 #define VA_ARGS_NAME_LENGTH (sizeof (va_args_name) - 1)
610 /* The structure of a node in the hash table. The hash table
611 has entries for all tokens defined by #define directives (type T_MACRO),
612 plus some special tokens like __LINE__ (these each have their own
613 type, and the appropriate code is run when that type of node is seen.
614 It does not contain control words like "#define", which are recognized
615 by a separate piece of code. */
617 /* different flavors of hash nodes --- also used in keyword table */
618 enum node_type {
619 T_DEFINE = 1, /* the `#define' keyword */
620 T_INCLUDE, /* the `#include' keyword */
621 T_INCLUDE_NEXT, /* the `#include_next' keyword */
622 T_IMPORT, /* the `#import' keyword */
623 T_IFDEF, /* the `#ifdef' keyword */
624 T_IFNDEF, /* the `#ifndef' keyword */
625 T_IF, /* the `#if' keyword */
626 T_ELSE, /* `#else' */
627 T_PRAGMA, /* `#pragma' */
628 T_ELIF, /* `#elif' */
629 T_UNDEF, /* `#undef' */
630 T_LINE, /* `#line' */
631 T_ERROR, /* `#error' */
632 T_WARNING, /* `#warning' */
633 T_ENDIF, /* `#endif' */
634 T_SCCS, /* `#sccs', used on system V. */
635 T_IDENT, /* `#ident', used on system V. */
636 T_ASSERT, /* `#assert', taken from system V. */
637 T_UNASSERT, /* `#unassert', taken from system V. */
638 T_SPECLINE, /* special symbol `__LINE__' */
639 T_DATE, /* `__DATE__' */
640 T_FILE, /* `__FILE__' */
641 T_BASE_FILE, /* `__BASE_FILE__' */
642 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
643 T_VERSION, /* `__VERSION__' */
644 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
645 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
646 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
647 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
648 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
649 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
650 T_TIME, /* `__TIME__' */
651 T_CONST, /* Constant value, used by `__STDC__' */
652 T_MACRO, /* macro defined by `#define' */
653 T_DISABLED, /* macro temporarily turned off for rescan */
654 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
655 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
656 T_UNUSED /* Used for something not defined. */
659 struct hashnode {
660 struct hashnode *next; /* double links for easy deletion */
661 struct hashnode *prev;
662 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
663 chain is kept, in case the node is the head
664 of the chain and gets deleted. */
665 enum node_type type; /* type of special token */
666 int length; /* length of token, for quick comparison */
667 U_CHAR *name; /* the actual name */
668 union hashval value; /* pointer to expansion, or whatever */
671 typedef struct hashnode HASHNODE;
673 /* Some definitions for the hash table. The hash function MUST be
674 computed as shown in hashf () below. That is because the rescan
675 loop computes the hash value `on the fly' for most tokens,
676 in order to avoid the overhead of a lot of procedure calls to
677 the hashf () function. Hashf () only exists for the sake of
678 politeness, for use when speed isn't so important. */
680 #define HASHSIZE 1403
681 static HASHNODE *hashtab[HASHSIZE];
682 #define HASHSTEP(old, c) ((old << 2) + c)
683 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
685 /* Symbols to predefine. */
687 #ifdef CPP_PREDEFINES
688 static char *predefs = CPP_PREDEFINES;
689 #else
690 static char *predefs = "";
691 #endif
693 /* We let tm.h override the types used here, to handle trivial differences
694 such as the choice of unsigned int or long unsigned int for size_t.
695 When machines start needing nontrivial differences in the size type,
696 it would be best to do something here to figure out automatically
697 from other information what type to use. */
699 /* The string value for __SIZE_TYPE__. */
701 #ifndef SIZE_TYPE
702 #define SIZE_TYPE "long unsigned int"
703 #endif
705 /* The string value for __PTRDIFF_TYPE__. */
707 #ifndef PTRDIFF_TYPE
708 #define PTRDIFF_TYPE "long int"
709 #endif
711 /* The string value for __WCHAR_TYPE__. */
713 #ifndef WCHAR_TYPE
714 #define WCHAR_TYPE "int"
715 #endif
716 char * wchar_type = WCHAR_TYPE;
717 #undef WCHAR_TYPE
719 /* The string value for __USER_LABEL_PREFIX__ */
721 #ifndef USER_LABEL_PREFIX
722 #define USER_LABEL_PREFIX ""
723 #endif
724 char * user_label_prefix = USER_LABEL_PREFIX;
725 #undef USER_LABEL_PREFIX
727 /* The string value for __REGISTER_PREFIX__ */
729 #ifndef REGISTER_PREFIX
730 #define REGISTER_PREFIX ""
731 #endif
733 /* The string value for __IMMEDIATE_PREFIX__ */
735 #ifndef IMMEDIATE_PREFIX
736 #define IMMEDIATE_PREFIX ""
737 #endif
739 /* In the definition of a #assert name, this structure forms
740 a list of the individual values asserted.
741 Each value is itself a list of "tokens".
742 These are strings that are compared by name. */
744 struct tokenlist_list {
745 struct tokenlist_list *next;
746 struct arglist *tokens;
749 struct assertion_hashnode {
750 struct assertion_hashnode *next; /* double links for easy deletion */
751 struct assertion_hashnode *prev;
752 /* also, a back pointer to this node's hash
753 chain is kept, in case the node is the head
754 of the chain and gets deleted. */
755 struct assertion_hashnode **bucket_hdr;
756 int length; /* length of token, for quick comparison */
757 U_CHAR *name; /* the actual name */
758 /* List of token-sequences. */
759 struct tokenlist_list *value;
762 typedef struct assertion_hashnode ASSERTION_HASHNODE;
764 /* Some definitions for the hash table. The hash function MUST be
765 computed as shown in hashf below. That is because the rescan
766 loop computes the hash value `on the fly' for most tokens,
767 in order to avoid the overhead of a lot of procedure calls to
768 the hashf function. hashf only exists for the sake of
769 politeness, for use when speed isn't so important. */
771 #define ASSERTION_HASHSIZE 37
772 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
774 /* Nonzero means inhibit macroexpansion of what seem to be
775 assertion tests, in rescan. For #if. */
776 static int assertions_flag;
778 /* `struct directive' defines one #-directive, including how to handle it. */
780 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
782 struct directive {
783 int length; /* Length of name */
784 int (*func) DO_PROTO; /* Function to handle directive */
785 char *name; /* Name of directive */
786 enum node_type type; /* Code which describes which directive. */
789 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
790 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
792 /* These functions are declared to return int instead of void since they
793 are going to be placed in the table and some old compilers have trouble with
794 pointers to functions returning void. */
796 static int do_assert DO_PROTO;
797 static int do_define DO_PROTO;
798 static int do_elif DO_PROTO;
799 static int do_else DO_PROTO;
800 static int do_endif DO_PROTO;
801 static int do_error DO_PROTO;
802 static int do_ident DO_PROTO;
803 static int do_if DO_PROTO;
804 static int do_include DO_PROTO;
805 static int do_line DO_PROTO;
806 static int do_pragma DO_PROTO;
807 #ifdef SCCS_DIRECTIVE
808 static int do_sccs DO_PROTO;
809 #endif
810 static int do_unassert DO_PROTO;
811 static int do_undef DO_PROTO;
812 static int do_warning DO_PROTO;
813 static int do_xifdef DO_PROTO;
815 /* Here is the actual list of #-directives, most-often-used first. */
817 static struct directive directive_table[] = {
818 { 6, do_define, "define", T_DEFINE},
819 { 2, do_if, "if", T_IF},
820 { 5, do_xifdef, "ifdef", T_IFDEF},
821 { 6, do_xifdef, "ifndef", T_IFNDEF},
822 { 5, do_endif, "endif", T_ENDIF},
823 { 4, do_else, "else", T_ELSE},
824 { 4, do_elif, "elif", T_ELIF},
825 { 4, do_line, "line", T_LINE},
826 { 7, do_include, "include", T_INCLUDE},
827 { 12, do_include, "include_next", T_INCLUDE_NEXT},
828 { 6, do_include, "import", T_IMPORT},
829 { 5, do_undef, "undef", T_UNDEF},
830 { 5, do_error, "error", T_ERROR},
831 { 7, do_warning, "warning", T_WARNING},
832 #ifdef SCCS_DIRECTIVE
833 { 4, do_sccs, "sccs", T_SCCS},
834 #endif
835 { 6, do_pragma, "pragma", T_PRAGMA},
836 { 5, do_ident, "ident", T_IDENT},
837 { 6, do_assert, "assert", T_ASSERT},
838 { 8, do_unassert, "unassert", T_UNASSERT},
839 { -1, 0, "", T_UNUSED},
842 /* When a directive handler is called,
843 this points to the # (or the : of the %:) that started the directive. */
844 U_CHAR *directive_start;
846 /* table to tell if char can be part of a C identifier. */
847 U_CHAR is_idchar[256];
848 /* table to tell if char can be first char of a c identifier. */
849 U_CHAR is_idstart[256];
850 /* table to tell if c is horizontal space. */
851 static U_CHAR is_hor_space[256];
852 /* table to tell if c is horizontal or vertical space. */
853 U_CHAR is_space[256];
854 /* names of some characters */
855 static char *char_name[256];
857 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
858 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
860 static int errors = 0; /* Error counter for exit code */
862 /* Name of output file, for error messages. */
863 static char *out_fname;
865 /* Nonzero to ignore \ in string constants. Use to treat #line 1 "A:\file.h
866 as a non-form feed. If you want it to be a form feed, you must use
867 # 1 "\f". */
868 static int ignore_escape_flag = 1;
870 /* Stack of conditionals currently in progress
871 (including both successful and failing conditionals). */
873 struct if_stack {
874 struct if_stack *next; /* for chaining to the next stack frame */
875 char *fname; /* copied from input when frame is made */
876 size_t fname_len; /* similarly */
877 int lineno; /* similarly */
878 int if_succeeded; /* true if a leg of this if-group
879 has been passed through rescan */
880 U_CHAR *control_macro; /* For #ifndef at start of file,
881 this is the macro name tested. */
882 enum node_type type; /* type of last directive seen in this group */
884 typedef struct if_stack IF_STACK_FRAME;
885 static IF_STACK_FRAME *if_stack = NULL;
887 /* Buffer of -M output. */
888 static char *deps_buffer;
890 /* Number of bytes allocated in above. */
891 static int deps_allocated_size;
893 /* Number of bytes used. */
894 static int deps_size;
896 /* Number of bytes since the last newline. */
897 static int deps_column;
899 /* Nonzero means -I- has been seen,
900 so don't look for #include "foo" the source-file directory. */
901 static int ignore_srcdir;
903 static int safe_read PROTO((int, char *, int));
904 static void safe_write PROTO((int, char *, int));
905 static void eprint_string PROTO((char *, size_t));
907 int main PROTO((int, char **));
909 static void path_include PROTO((char *));
911 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
913 static void trigraph_pcp PROTO((FILE_BUF *));
915 static void newline_fix PROTO((U_CHAR *));
916 static void name_newline_fix PROTO((U_CHAR *));
918 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
920 static void rescan PROTO((FILE_BUF *, int));
922 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
924 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
926 static struct tm *timestamp PROTO((void));
927 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
929 static int is_system_include PROTO((char *));
930 static char *base_name PROTO((char *));
931 static int absolute_filename PROTO((char *));
932 static size_t simplify_filename PROTO((char *));
934 static char *read_filename_string PROTO((int, FILE *));
935 static struct file_name_map *read_name_map PROTO((char *));
936 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
937 static char *remap_include_file PROTO((char *, struct file_name_list *));
938 static int lookup_ino_include PROTO((struct include_file *));
940 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
941 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
943 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
944 static int check_preconditions PROTO((char *));
945 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
946 static void pcstring_used PROTO((HASHNODE *));
947 static void write_output PROTO((void));
948 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
950 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
952 static int check_macro_name PROTO((U_CHAR *, char *));
953 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
954 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
956 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
958 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
959 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
961 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
962 static void free_token_list PROTO((struct arglist *));
964 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
965 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
966 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
968 static void do_once PROTO((void));
970 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
971 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
972 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
973 static void validate_else PROTO((U_CHAR *, U_CHAR *));
975 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
976 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
977 static char *quote_string PROTO((char *, char *, size_t));
978 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
980 /* Last arg to output_line_directive. */
981 enum file_change_code {same_file, enter_file, leave_file};
982 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
984 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
986 struct argdata;
987 static char *macarg PROTO((struct argdata *, int));
989 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
991 static int discard_comments PROTO((U_CHAR *, int, int));
993 static int change_newlines PROTO((U_CHAR *, int));
995 static char *my_strerror PROTO((int));
996 void error PRINTF_PROTO_1((char *, ...));
997 static void verror PROTO((char *, va_list));
998 static void error_from_errno PROTO((char *));
999 void warning PRINTF_PROTO_1((char *, ...));
1000 static void vwarning PROTO((char *, va_list));
1001 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1002 static void verror_with_line PROTO((int, char *, va_list));
1003 static void vwarning_with_line PROTO((int, char *, va_list));
1004 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1005 void pedwarn PRINTF_PROTO_1((char *, ...));
1006 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1007 static void pedwarn_with_file_and_line PRINTF_PROTO_4((char *, size_t, int, char *, ...));
1009 static void print_containing_files PROTO((void));
1011 static int line_for_error PROTO((int));
1012 static int grow_outbuf PROTO((FILE_BUF *, int));
1014 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1015 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1016 static void delete_macro PROTO((HASHNODE *));
1017 static int hashf PROTO((U_CHAR *, int, int));
1019 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1020 static void dump_all_macros PROTO((void));
1021 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1022 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1024 static void initialize_char_syntax PROTO((void));
1025 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1027 static void make_definition PROTO((char *));
1028 static void make_undef PROTO((char *, FILE_BUF *));
1030 static void make_assertion PROTO((char *, char *));
1032 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, const char *, const char *, const char *));
1033 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1035 static int quote_string_for_make PROTO((char *, char *));
1036 static void deps_output PROTO((char *, int));
1038 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1039 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1040 static void perror_with_name PROTO((char *));
1041 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1042 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1044 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1045 static void print_help PROTO((void));
1047 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1048 retrying if necessary. If MAX_READ_LEN is defined, read at most
1049 that bytes at a time. Return a negative value if an error occurs,
1050 otherwise return the actual number of bytes read,
1051 which must be LEN unless end-of-file was reached. */
1053 static int
1054 safe_read (desc, ptr, len)
1055 int desc;
1056 char *ptr;
1057 int len;
1059 int left, rcount, nchars;
1061 left = len;
1062 while (left > 0) {
1063 rcount = left;
1064 #ifdef MAX_READ_LEN
1065 if (rcount > MAX_READ_LEN)
1066 rcount = MAX_READ_LEN;
1067 #endif
1068 nchars = read (desc, ptr, rcount);
1069 if (nchars < 0)
1071 #ifdef EINTR
1072 if (errno == EINTR)
1073 continue;
1074 #endif
1075 return nchars;
1077 if (nchars == 0)
1078 break;
1079 ptr += nchars;
1080 left -= nchars;
1082 return len - left;
1085 /* Write LEN bytes at PTR to descriptor DESC,
1086 retrying if necessary, and treating any real error as fatal.
1087 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1089 static void
1090 safe_write (desc, ptr, len)
1091 int desc;
1092 char *ptr;
1093 int len;
1095 int wcount, written;
1097 while (len > 0) {
1098 wcount = len;
1099 #ifdef MAX_WRITE_LEN
1100 if (wcount > MAX_WRITE_LEN)
1101 wcount = MAX_WRITE_LEN;
1102 #endif
1103 written = write (desc, ptr, wcount);
1104 if (written < 0)
1106 #ifdef EINTR
1107 if (errno == EINTR)
1108 continue;
1109 #endif
1110 pfatal_with_name (out_fname);
1112 ptr += written;
1113 len -= written;
1117 /* Print a string to stderr, with extra handling in case it contains
1118 embedded NUL characters. Any present are written as is.
1120 Using fwrite for this purpose produces undesireable results on VMS
1121 when stderr happens to be a record oriented file, such as a batch log
1122 file, rather than a stream oriented one. */
1124 static void
1125 eprint_string (string, length)
1126 char *string;
1127 size_t length;
1129 size_t segment_length;
1131 do {
1132 fprintf(stderr, "%s", string);
1133 length -= (segment_length = strlen(string));
1134 if (length > 0)
1136 fputc('\0', stderr);
1137 length -= 1;
1138 /* Advance past the portion which has already been printed. */
1139 string += segment_length + 1;
1141 } while (length > 0);
1145 static void
1146 print_help ()
1148 printf ("Usage: %s [switches] input output\n", progname);
1149 printf ("Switches:\n");
1150 printf (" -include <file> Include the contents of <file> before other files\n");
1151 printf (" -imacros <file> Accept definition of marcos in <file>\n");
1152 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
1153 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
1154 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
1155 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
1156 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
1157 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
1158 printf (" -nostdinc Do not search the system include directories\n");
1159 printf (" -nostdinc++ Do not search the system include directories for C++\n");
1160 printf (" -o <file> Put output into <file>\n");
1161 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
1162 printf (" -traditional Follow K&R pre-processor behaviour\n");
1163 printf (" -trigraphs Support ANSI C trigraphs\n");
1164 printf (" -lang-c Assume that the input sources are in C\n");
1165 printf (" -lang-c89 Assume that the input is C89; depricated\n");
1166 printf (" -lang-c++ Assume that the input sources are in C++\n");
1167 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
1168 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
1169 printf (" -lang-asm Assume that the input sources are in assembler\n");
1170 printf (" -lang-chill Assume that the input sources are in Chill\n");
1171 printf (" -std=<std name> Specify the conformance standard; one of:\n");
1172 printf (" gnu89, gnu9x, c89, c9x, iso9899:1990,\n");
1173 printf (" iso9899:199409, iso9899:199x\n");
1174 printf (" -+ Allow parsing of C++ style features\n");
1175 printf (" -w Inhibit warning messages\n");
1176 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
1177 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
1178 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
1179 printf (" -Wno-comment{s} Do not warn about comments\n");
1180 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
1181 printf (" a string if -traditional is specified\n");
1182 printf (" -Wno-traditional Do not warn about stringification\n");
1183 printf (" -Wundef Warn if an undefined macro is used by #if\n");
1184 printf (" -Wno-undef Do not warn about testing undefined macros\n");
1185 printf (" -Wimport Warn about the use of the #import directive\n");
1186 printf (" -Wno-import Do not warn about the use of #import\n");
1187 printf (" -Werror Treat all warnings as errors\n");
1188 printf (" -Wno-error Do not treat warnings as errors\n");
1189 printf (" -Wall Enable all preprocessor warnings\n");
1190 printf (" -M Generate make dependencies\n");
1191 printf (" -MM As -M, but ignore system header files\n");
1192 printf (" -MD As -M, but put output in a .d file\n");
1193 printf (" -MMD As -MD, but ignore system header files\n");
1194 printf (" -MG Treat missing header file as generated files\n");
1195 printf (" -g Include #define and #undef directives in the output\n");
1196 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
1197 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
1198 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
1199 printf (" -U<macro> Undefine <macro> \n");
1200 printf (" -u or -undef Do not predefine any macros\n");
1201 printf (" -v Display the version number\n");
1202 printf (" -H Print the name of header files as they are used\n");
1203 printf (" -C Do not discard comments\n");
1204 printf (" -dM Display a list of macro definitions active at end\n");
1205 printf (" -dD Preserve macro definitions in output\n");
1206 printf (" -dN As -dD except that only the names are preserved\n");
1207 printf (" -dI Include #include directives in the output\n");
1208 printf (" -ifoutput Describe skipped code blocks in output \n");
1209 printf (" -P Do not generate #line directives\n");
1210 printf (" -$ Do not include '$' in identifiers\n");
1211 printf (" -remap Remap file names when including files.\n");
1212 printf (" -h or --help Display this information\n");
1216 main (argc, argv)
1217 int argc;
1218 char **argv;
1220 struct stat st;
1221 char *in_fname;
1222 char *cp;
1223 int f, i;
1224 FILE_BUF *fp;
1225 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1226 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1227 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1228 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1229 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1231 /* Record the option used with each element of pend_assertions.
1232 This is preparation for supporting more than one option for making
1233 an assertion. */
1234 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1235 int inhibit_predefs = 0;
1236 int no_standard_includes = 0;
1237 int no_standard_cplusplus_includes = 0;
1238 int missing_newline = 0;
1240 /* Non-0 means don't output the preprocessed program. */
1241 int inhibit_output = 0;
1242 /* Non-0 means -v, so print the full set of include dirs. */
1243 int verbose = 0;
1245 /* File name which deps are being written to.
1246 This is 0 if deps are being written to stdout. */
1247 char *deps_file = 0;
1248 /* Fopen file mode to open deps_file with. */
1249 char *deps_mode = "a";
1250 /* Stream on which to print the dependency information. */
1251 FILE *deps_stream = 0;
1252 /* Target-name to write with the dependency information. */
1253 char *deps_target = 0;
1255 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1256 /* Get rid of any avoidable limit on stack size. */
1258 struct rlimit rlim;
1260 /* Set the stack limit huge so that alloca (particularly stringtab
1261 in dbxread.c) does not fail. */
1262 getrlimit (RLIMIT_STACK, &rlim);
1263 rlim.rlim_cur = rlim.rlim_max;
1264 setrlimit (RLIMIT_STACK, &rlim);
1266 #endif
1268 #ifdef SIGPIPE
1269 signal (SIGPIPE, pipe_closed);
1270 #endif
1272 progname = base_name (argv[0]);
1274 #ifdef VMS
1276 /* Remove extension from PROGNAME. */
1277 char *p;
1278 char *s = progname = xstrdup (progname);
1280 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1281 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1282 && (p[1] == 'e' || p[1] == 'E')
1283 && (p[2] == 'x' || p[2] == 'X')
1284 && (p[3] == 'e' || p[3] == 'E')
1285 && !p[4])
1286 *p = '\0';
1288 #endif
1290 in_fname = NULL;
1291 out_fname = NULL;
1293 /* Initialize is_idchar. */
1294 initialize_char_syntax ();
1296 no_line_directives = 0;
1297 no_trigraphs = 1;
1298 dump_macros = dump_none;
1299 no_output = 0;
1300 cplusplus = 0;
1301 cplusplus_comments = 1;
1303 bzero ((char *) pend_files, argc * sizeof (char *));
1304 bzero ((char *) pend_defs, argc * sizeof (char *));
1305 bzero ((char *) pend_undefs, argc * sizeof (char *));
1306 bzero ((char *) pend_assertions, argc * sizeof (char *));
1307 bzero ((char *) pend_includes, argc * sizeof (char *));
1309 #ifdef MULTIBYTE_CHARS
1310 /* Change to the native locale for multibyte conversions. */
1311 setlocale (LC_CTYPE, "");
1312 literal_codeset = getenv ("LANG");
1313 #endif
1315 /* Process switches and find input file name. */
1317 for (i = 1; i < argc; i++) {
1318 if (argv[i][0] != '-') {
1319 if (out_fname != NULL)
1321 print_help ();
1322 fatal ("Too many arguments");
1324 else if (in_fname != NULL)
1325 out_fname = argv[i];
1326 else
1327 in_fname = argv[i];
1328 } else {
1329 switch (argv[i][1]) {
1331 case 'i':
1332 if (!strcmp (argv[i], "-include")) {
1333 int temp = i;
1335 if (i + 1 == argc)
1336 fatal ("Filename missing after `-include' option");
1337 else
1338 simplify_filename (pend_includes[temp] = argv[++i]);
1340 if (!strcmp (argv[i], "-imacros")) {
1341 int temp = i;
1343 if (i + 1 == argc)
1344 fatal ("Filename missing after `-imacros' option");
1345 else
1346 simplify_filename (pend_files[temp] = argv[++i]);
1348 if (!strcmp (argv[i], "-iprefix")) {
1349 if (i + 1 == argc)
1350 fatal ("Filename missing after `-iprefix' option");
1351 else
1352 include_prefix = argv[++i];
1354 if (!strcmp (argv[i], "-ifoutput")) {
1355 output_conditionals = 1;
1357 if (!strcmp (argv[i], "-isystem")) {
1358 struct file_name_list *dirtmp;
1360 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1361 "", argv[++i])))
1362 break;
1363 dirtmp->c_system_include_path = 1;
1365 if (before_system == 0)
1366 before_system = dirtmp;
1367 else
1368 last_before_system->next = dirtmp;
1369 last_before_system = dirtmp; /* Tail follows the last one */
1371 /* Add directory to end of path for includes,
1372 with the default prefix at the front of its name. */
1373 if (!strcmp (argv[i], "-iwithprefix")) {
1374 struct file_name_list *dirtmp;
1375 char *prefix;
1377 if (include_prefix != 0)
1378 prefix = include_prefix;
1379 else {
1380 prefix = xstrdup (GCC_INCLUDE_DIR);
1381 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1382 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1383 prefix[strlen (prefix) - 7] = 0;
1386 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1387 prefix, argv[++i])))
1388 break;
1390 if (after_include == 0)
1391 after_include = dirtmp;
1392 else
1393 last_after_include->next = dirtmp;
1394 last_after_include = dirtmp; /* Tail follows the last one */
1396 /* Add directory to main path for includes,
1397 with the default prefix at the front of its name. */
1398 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1399 struct file_name_list *dirtmp;
1400 char *prefix;
1402 if (include_prefix != 0)
1403 prefix = include_prefix;
1404 else {
1405 prefix = xstrdup (GCC_INCLUDE_DIR);
1406 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1407 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1408 prefix[strlen (prefix) - 7] = 0;
1411 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1412 append_include_chain (dirtmp, dirtmp);
1414 /* Add directory to end of path for includes. */
1415 if (!strcmp (argv[i], "-idirafter")) {
1416 struct file_name_list *dirtmp;
1418 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1419 "", argv[++i])))
1420 break;
1422 if (after_include == 0)
1423 after_include = dirtmp;
1424 else
1425 last_after_include->next = dirtmp;
1426 last_after_include = dirtmp; /* Tail follows the last one */
1428 break;
1430 case 'o':
1431 if (out_fname != NULL)
1432 fatal ("Output filename specified twice");
1433 if (i + 1 == argc)
1434 fatal ("Filename missing after -o option");
1435 out_fname = argv[++i];
1436 if (!strcmp (out_fname, "-"))
1437 out_fname = "";
1438 break;
1440 case 'p':
1441 if (!strcmp (argv[i], "-pedantic"))
1442 pedantic = 1;
1443 else if (!strcmp (argv[i], "-pedantic-errors")) {
1444 pedantic = 1;
1445 pedantic_errors = 1;
1446 } else if (!strcmp (argv[i], "-pcp")) {
1447 char *pcp_fname;
1448 if (i + 1 == argc)
1449 fatal ("Filename missing after -pcp option");
1450 pcp_fname = argv[++i];
1451 pcp_outfile
1452 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1453 ? fopen (pcp_fname, "w")
1454 : stdout);
1455 if (pcp_outfile == 0)
1456 pfatal_with_name (pcp_fname);
1457 no_precomp = 1;
1459 break;
1461 case 't':
1462 if (!strcmp (argv[i], "-traditional")) {
1463 traditional = 1;
1464 cplusplus_comments = 0;
1465 } else if (!strcmp (argv[i], "-trigraphs")) {
1466 no_trigraphs = 0;
1468 break;
1470 case 'l':
1471 if (! strcmp (argv[i], "-lang-c"))
1472 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1473 else if (! strcmp (argv[i], "-lang-c89"))
1474 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1475 else if (! strcmp (argv[i], "-lang-c++"))
1476 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 0;
1477 else if (! strcmp (argv[i], "-lang-objc"))
1478 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1479 else if (! strcmp (argv[i], "-lang-objc++"))
1480 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1481 else if (! strcmp (argv[i], "-lang-asm"))
1482 lang_asm = 1;
1483 else if (! strcmp (argv[i], "-lint"))
1484 for_lint = 1;
1485 break;
1487 case '+':
1488 cplusplus = 1, cplusplus_comments = 1;
1489 break;
1491 case 's':
1492 if (!strcmp (argv[i], "-std=iso9899:1990")
1493 || !strcmp (argv[i], "-std=iso9899:199409")
1494 || !strcmp (argv[i], "-std=c89")
1495 || !strcmp (argv[i], "-std=gnu89"))
1496 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1497 else if (!strcmp (argv[i], "-std=iso9899:199x")
1498 || !strcmp (argv[i], "-std=c9x")
1499 || !strcmp (argv[i], "-std=gnu9x"))
1500 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1501 break;
1503 case 'w':
1504 inhibit_warnings = 1;
1505 break;
1507 case 'W':
1508 if (!strcmp (argv[i], "-Wtrigraphs"))
1509 warn_trigraphs = 1;
1510 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1511 warn_trigraphs = 0;
1512 else if (!strcmp (argv[i], "-Wcomment"))
1513 warn_comments = 1;
1514 else if (!strcmp (argv[i], "-Wno-comment"))
1515 warn_comments = 0;
1516 else if (!strcmp (argv[i], "-Wcomments"))
1517 warn_comments = 1;
1518 else if (!strcmp (argv[i], "-Wno-comments"))
1519 warn_comments = 0;
1520 else if (!strcmp (argv[i], "-Wtraditional"))
1521 warn_stringify = 1;
1522 else if (!strcmp (argv[i], "-Wno-traditional"))
1523 warn_stringify = 0;
1524 else if (!strcmp (argv[i], "-Wundef"))
1525 warn_undef = 1;
1526 else if (!strcmp (argv[i], "-Wno-undef"))
1527 warn_undef = 0;
1528 else if (!strcmp (argv[i], "-Wimport"))
1529 warn_import = 1;
1530 else if (!strcmp (argv[i], "-Wno-import"))
1531 warn_import = 0;
1532 else if (!strcmp (argv[i], "-Werror"))
1533 warnings_are_errors = 1;
1534 else if (!strcmp (argv[i], "-Wno-error"))
1535 warnings_are_errors = 0;
1536 else if (!strcmp (argv[i], "-Wall"))
1538 warn_trigraphs = 1;
1539 warn_comments = 1;
1541 break;
1543 case 'f':
1544 if (!strcmp (argv[i], "-fleading-underscore"))
1545 user_label_prefix = "_";
1546 else if (!strcmp (argv[i], "-fno-leading-underscore"))
1547 user_label_prefix = "";
1548 break;
1550 case 'M':
1551 /* The style of the choices here is a bit mixed.
1552 The chosen scheme is a hybrid of keeping all options in one string
1553 and specifying each option in a separate argument:
1554 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1555 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1556 -M[M][G][D file]. This is awkward to handle in specs, and is not
1557 as extensible. */
1558 /* ??? -MG must be specified in addition to one of -M or -MM.
1559 This can be relaxed in the future without breaking anything.
1560 The converse isn't true. */
1562 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1563 if (!strcmp (argv[i], "-MG"))
1565 print_deps_missing_files = 1;
1566 break;
1568 if (!strcmp (argv[i], "-M"))
1569 print_deps = 2;
1570 else if (!strcmp (argv[i], "-MM"))
1571 print_deps = 1;
1572 else if (!strcmp (argv[i], "-MD"))
1573 print_deps = 2;
1574 else if (!strcmp (argv[i], "-MMD"))
1575 print_deps = 1;
1576 /* For -MD and -MMD options, write deps on file named by next arg. */
1577 if (!strcmp (argv[i], "-MD")
1578 || !strcmp (argv[i], "-MMD")) {
1579 if (i + 1 == argc)
1580 fatal ("Filename missing after %s option", argv[i]);
1581 i++;
1582 deps_file = argv[i];
1583 deps_mode = "w";
1584 } else {
1585 /* For -M and -MM, write deps on standard output
1586 and suppress the usual output. */
1587 deps_stream = stdout;
1588 inhibit_output = 1;
1590 break;
1592 case 'd':
1594 char *p = argv[i] + 2;
1595 char c;
1596 while ((c = *p++)) {
1597 /* Arg to -d specifies what parts of macros to dump */
1598 switch (c) {
1599 case 'M':
1600 dump_macros = dump_only;
1601 no_output = 1;
1602 break;
1603 case 'N':
1604 dump_macros = dump_names;
1605 break;
1606 case 'D':
1607 dump_macros = dump_definitions;
1608 break;
1609 case 'I':
1610 dump_includes = 1;
1611 break;
1615 break;
1617 case 'g':
1618 if (argv[i][2] == '3')
1619 debug_output = 1;
1620 break;
1622 case '-':
1623 if (strcmp (argv[i], "--help") != 0)
1624 return i;
1625 print_help ();
1626 exit (0);
1627 break;
1629 case 'v':
1630 fprintf (stderr, "GNU CPP version %s", version_string);
1631 #ifdef TARGET_VERSION
1632 TARGET_VERSION;
1633 #endif
1634 fprintf (stderr, "\n");
1635 verbose = 1;
1636 break;
1638 case 'H':
1639 print_include_names = 1;
1640 break;
1642 case 'D':
1643 if (argv[i][2] != 0)
1644 pend_defs[i] = argv[i] + 2;
1645 else if (i + 1 == argc)
1646 fatal ("Macro name missing after -D option");
1647 else
1648 i++, pend_defs[i] = argv[i];
1649 break;
1651 case 'A':
1653 char *p;
1655 if (argv[i][2] != 0)
1656 p = argv[i] + 2;
1657 else if (i + 1 == argc)
1658 fatal ("Assertion missing after -A option");
1659 else
1660 p = argv[++i];
1662 if (!strcmp (p, "-")) {
1663 /* -A- eliminates all predefined macros and assertions.
1664 Let's include also any that were specified earlier
1665 on the command line. That way we can get rid of any
1666 that were passed automatically in from GCC. */
1667 int j;
1668 inhibit_predefs = 1;
1669 for (j = 0; j < i; j++)
1670 pend_defs[j] = pend_assertions[j] = 0;
1671 } else {
1672 pend_assertions[i] = p;
1673 pend_assertion_options[i] = "-A";
1676 break;
1678 case 'U': /* JF #undef something */
1679 if (argv[i][2] != 0)
1680 pend_undefs[i] = argv[i] + 2;
1681 else if (i + 1 == argc)
1682 fatal ("Macro name missing after -U option");
1683 else
1684 pend_undefs[i] = argv[i+1], i++;
1685 break;
1687 case 'C':
1688 put_out_comments = 1;
1689 break;
1691 case 'E': /* -E comes from cc -E; ignore it. */
1692 break;
1694 case 'P':
1695 no_line_directives = 1;
1696 break;
1698 case '$': /* Don't include $ in identifiers. */
1699 is_idchar['$'] = is_idstart['$'] = 0;
1700 break;
1702 case 'I': /* Add directory to path for includes. */
1704 struct file_name_list *dirtmp;
1706 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1707 ignore_srcdir = 1;
1708 /* Don't use any preceding -I directories for #include <...>. */
1709 first_bracket_include = 0;
1711 else {
1712 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1713 argv[i][2] ? argv[i] + 2 : argv[++i]);
1714 append_include_chain (dirtmp, dirtmp);
1717 break;
1719 case 'n':
1720 if (!strcmp (argv[i], "-nostdinc"))
1721 /* -nostdinc causes no default include directories.
1722 You must specify all include-file directories with -I. */
1723 no_standard_includes = 1;
1724 else if (!strcmp (argv[i], "-nostdinc++"))
1725 /* -nostdinc++ causes no default C++-specific include directories. */
1726 no_standard_cplusplus_includes = 1;
1727 else if (!strcmp (argv[i], "-noprecomp"))
1728 no_precomp = 1;
1729 break;
1731 case 'r':
1732 if (!strcmp (argv[i], "-remap"))
1733 remap = 1;
1734 break;
1736 case 'u':
1737 /* Sun compiler passes undocumented switch "-undef".
1738 Let's assume it means to inhibit the predefined symbols. */
1739 inhibit_predefs = 1;
1740 break;
1742 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1743 if (in_fname == NULL) {
1744 in_fname = "";
1745 break;
1746 } else if (out_fname == NULL) {
1747 out_fname = "";
1748 break;
1749 } /* else fall through into error */
1751 default:
1752 fatal ("Invalid option `%s'", argv[i]);
1757 /* Add dirs from CPATH after dirs from -I. */
1758 /* There seems to be confusion about what CPATH should do,
1759 so for the moment it is not documented. */
1760 /* Some people say that CPATH should replace the standard include dirs,
1761 but that seems pointless: it comes before them, so it overrides them
1762 anyway. */
1763 GET_ENV_PATH_LIST (cp, "CPATH");
1764 if (cp && ! no_standard_includes)
1765 path_include (cp);
1767 /* Initialize output buffer */
1769 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1770 outbuf.bufp = outbuf.buf;
1771 outbuf.length = OUTBUF_SIZE;
1773 /* Do partial setup of input buffer for the sake of generating
1774 early #line directives (when -g is in effect). */
1776 fp = &instack[++indepth];
1777 if (in_fname == NULL)
1778 in_fname = "";
1779 fp->nominal_fname = fp->fname = in_fname;
1780 fp->nominal_fname_len = strlen (in_fname);
1781 fp->lineno = 0;
1783 /* In C++, wchar_t is a distinct basic type, and we can expect
1784 __wchar_t to be defined by cc1plus. */
1785 if (cplusplus)
1786 wchar_type = "__wchar_t";
1788 /* Install __LINE__, etc. Must follow initialize_char_syntax
1789 and option processing. */
1790 initialize_builtins (fp, &outbuf);
1792 /* Do standard #defines and assertions
1793 that identify system and machine type. */
1795 if (!inhibit_predefs) {
1796 char *p = (char *) alloca (strlen (predefs) + 1);
1798 #ifdef VMS
1799 struct dsc$descriptor_s lcl_name;
1800 struct item_list {
1801 unsigned short length; /* input length */
1802 unsigned short code; /* item code */
1803 unsigned long dptr; /* data ptr */
1804 unsigned long lptr; /* output length ptr */
1807 unsigned long syi_length;
1808 char syi_data[16];
1810 struct item_list items[] = {
1811 { 16, SYI$_VERSION, 0, 0 },
1812 { 0, 0, 0, 0 }
1815 items[0].dptr = (unsigned long)syi_data;
1816 items[0].lptr = (unsigned long)(&syi_length);
1818 if (SYS$GETSYIW (0, 0, 0, items, NULL, NULL, NULL, NULL) == SS$_NORMAL)
1820 unsigned long vms_version_value;
1821 char *vers;
1823 vers = syi_data;
1824 vms_version_value = 0;
1826 if (*vers == 'V')
1827 vers++;
1828 if (ISDIGIT (*vers))
1830 vms_version_value = (*vers - '0') * 10000000;
1832 vers++;
1833 if (*vers == '.')
1835 vers++;
1836 if (ISDIGIT (*vers))
1838 vms_version_value += (*vers - '0') * 100000;
1842 if (vms_version_value > 0)
1844 char versbuf[32];
1846 sprintf (versbuf, "__VMS_VER=%08ld", vms_version_value);
1847 if (debug_output)
1848 output_line_directive (fp, &outbuf, 0, same_file);
1849 make_definition (versbuf);
1852 #endif
1854 strcpy (p, predefs);
1855 while (*p) {
1856 char *q;
1857 while (*p == ' ' || *p == '\t')
1858 p++;
1859 /* Handle -D options. */
1860 if (p[0] == '-' && p[1] == 'D') {
1861 q = &p[2];
1862 while (*p && *p != ' ' && *p != '\t')
1863 p++;
1864 if (*p != 0)
1865 *p++= 0;
1866 if (debug_output)
1867 output_line_directive (fp, &outbuf, 0, same_file);
1868 make_definition (q);
1869 while (*p == ' ' || *p == '\t')
1870 p++;
1871 } else if (p[0] == '-' && p[1] == 'A') {
1872 /* Handle -A options (assertions). */
1873 char *assertion;
1874 char *past_name;
1875 char *value;
1876 char *past_value;
1877 char *termination;
1878 int save_char;
1880 assertion = &p[2];
1881 past_name = assertion;
1882 /* Locate end of name. */
1883 while (*past_name && *past_name != ' '
1884 && *past_name != '\t' && *past_name != '(')
1885 past_name++;
1886 /* Locate `(' at start of value. */
1887 value = past_name;
1888 while (*value && (*value == ' ' || *value == '\t'))
1889 value++;
1890 if (*value++ != '(')
1891 abort ();
1892 while (*value && (*value == ' ' || *value == '\t'))
1893 value++;
1894 past_value = value;
1895 /* Locate end of value. */
1896 while (*past_value && *past_value != ' '
1897 && *past_value != '\t' && *past_value != ')')
1898 past_value++;
1899 termination = past_value;
1900 while (*termination && (*termination == ' ' || *termination == '\t'))
1901 termination++;
1902 if (*termination++ != ')')
1903 abort ();
1904 if (*termination && *termination != ' ' && *termination != '\t')
1905 abort ();
1906 /* Temporarily null-terminate the value. */
1907 save_char = *termination;
1908 *termination = '\0';
1909 /* Install the assertion. */
1910 make_assertion ("-A", assertion);
1911 *termination = (char) save_char;
1912 p = termination;
1913 while (*p == ' ' || *p == '\t')
1914 p++;
1915 } else {
1916 abort ();
1921 /* Now handle the command line options. */
1923 /* Do -U's, -D's and -A's in the order they were seen. */
1924 for (i = 1; i < argc; i++) {
1925 if (pend_undefs[i]) {
1926 if (debug_output)
1927 output_line_directive (fp, &outbuf, 0, same_file);
1928 make_undef (pend_undefs[i], &outbuf);
1930 if (pend_defs[i]) {
1931 if (debug_output)
1932 output_line_directive (fp, &outbuf, 0, same_file);
1933 make_definition (pend_defs[i]);
1935 if (pend_assertions[i])
1936 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1939 done_initializing = 1;
1941 { /* Read the appropriate environment variable and if it exists
1942 replace include_defaults with the listed path. */
1943 char *epath = 0;
1944 switch ((objc << 1) + cplusplus)
1946 case 0:
1947 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
1948 break;
1949 case 1:
1950 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
1951 break;
1952 case 2:
1953 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
1954 break;
1955 case 3:
1956 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
1957 break;
1959 /* If the environment var for this language is set,
1960 add to the default list of include directories. */
1961 if (epath) {
1962 int num_dirs;
1963 char *startp, *endp;
1965 for (num_dirs = 1, startp = epath; *startp; startp++)
1966 if (*startp == PATH_SEPARATOR)
1967 num_dirs++;
1968 include_defaults
1969 = (struct default_include *) xmalloc ((num_dirs
1970 * sizeof (struct default_include))
1971 + sizeof (include_defaults_array));
1972 startp = endp = epath;
1973 num_dirs = 0;
1974 while (1) {
1975 char c = *endp++;
1976 if (c == PATH_SEPARATOR || !c) {
1977 endp[-1] = 0;
1978 include_defaults[num_dirs].fname
1979 = startp == endp ? "." : xstrdup (startp);
1980 endp[-1] = c;
1981 include_defaults[num_dirs].component = 0;
1982 include_defaults[num_dirs].cplusplus = cplusplus;
1983 include_defaults[num_dirs].cxx_aware = 1;
1984 num_dirs++;
1985 if (!c)
1986 break;
1987 startp = endp;
1990 /* Put the usual defaults back in at the end. */
1991 bcopy ((char *) include_defaults_array,
1992 (char *) &include_defaults[num_dirs],
1993 sizeof (include_defaults_array));
1997 append_include_chain (before_system, last_before_system);
1998 first_system_include = before_system;
2000 /* Unless -fnostdinc,
2001 tack on the standard include file dirs to the specified list */
2002 if (!no_standard_includes) {
2003 struct default_include *p = include_defaults;
2004 char *specd_prefix = include_prefix;
2005 char *default_prefix = xstrdup (GCC_INCLUDE_DIR);
2006 int default_len = 0;
2007 /* Remove the `include' from /usr/local/lib/gcc.../include. */
2008 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
2009 default_len = strlen (default_prefix) - 7;
2010 default_prefix[default_len] = 0;
2012 /* Search "translated" versions of GNU directories.
2013 These have /usr/local/lib/gcc... replaced by specd_prefix. */
2014 if (specd_prefix != 0 && default_len != 0)
2015 for (p = include_defaults; p->fname; p++) {
2016 /* Some standard dirs are only for C++. */
2017 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2018 /* Does this dir start with the prefix? */
2019 if (!strncmp (p->fname, default_prefix, default_len)) {
2020 /* Yes; change prefix and add to search list. */
2021 struct file_name_list *new
2022 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
2023 p->fname + default_len);
2024 if (new) {
2025 new->c_system_include_path = !p->cxx_aware;
2026 append_include_chain (new, new);
2027 if (first_system_include == 0)
2028 first_system_include = new;
2033 /* Search ordinary names for GNU include directories. */
2034 for (p = include_defaults; p->fname; p++) {
2035 /* Some standard dirs are only for C++. */
2036 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2037 struct file_name_list *new
2038 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
2039 if (new) {
2040 new->c_system_include_path = !p->cxx_aware;
2041 append_include_chain (new, new);
2042 if (first_system_include == 0)
2043 first_system_include = new;
2049 /* Tack the after_include chain at the end of the include chain. */
2050 append_include_chain (after_include, last_after_include);
2051 if (first_system_include == 0)
2052 first_system_include = after_include;
2054 /* With -v, print the list of dirs to search. */
2055 if (verbose) {
2056 struct file_name_list *p;
2057 fprintf (stderr, "#include \"...\" search starts here:\n");
2058 for (p = include; p; p = p->next) {
2059 if (p == first_bracket_include)
2060 fprintf (stderr, "#include <...> search starts here:\n");
2061 if (!p->fname[0])
2062 fprintf (stderr, " .\n");
2063 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
2064 fprintf (stderr, " %s\n", p->fname);
2065 else
2066 /* Omit trailing '/'. */
2067 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
2069 fprintf (stderr, "End of search list.\n");
2072 /* -MG doesn't select the form of output and must be specified with one of
2073 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2074 inhibit compilation. */
2075 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2076 fatal ("-MG must be specified with one of -M or -MM");
2078 /* Either of two environment variables can specify output of deps.
2079 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2080 where OUTPUT_FILE is the file to write deps info to
2081 and DEPS_TARGET is the target to mention in the deps. */
2083 if (print_deps == 0
2084 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2085 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2086 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2087 char *s;
2088 char *output_file;
2090 if (spec == 0) {
2091 spec = getenv ("SUNPRO_DEPENDENCIES");
2092 print_deps = 2;
2094 else
2095 print_deps = 1;
2097 s = spec;
2098 /* Find the space before the DEPS_TARGET, if there is one. */
2099 /* This should use index. (mrs) */
2100 while (*s != 0 && *s != ' ') s++;
2101 if (*s != 0) {
2102 deps_target = s + 1;
2103 output_file = xmalloc (s - spec + 1);
2104 bcopy (spec, output_file, s - spec);
2105 output_file[s - spec] = 0;
2107 else {
2108 deps_target = 0;
2109 output_file = spec;
2112 deps_file = output_file;
2113 deps_mode = "a";
2116 /* For -M, print the expected object file name
2117 as the target of this Make-rule. */
2118 if (print_deps) {
2119 deps_allocated_size = 200;
2120 deps_buffer = xmalloc (deps_allocated_size);
2121 deps_buffer[0] = 0;
2122 deps_size = 0;
2123 deps_column = 0;
2125 if (deps_target) {
2126 deps_output (deps_target, ':');
2127 } else if (*in_fname == 0) {
2128 deps_output ("-", ':');
2129 } else {
2130 char *p, *q;
2131 int len;
2133 q = base_name (in_fname);
2135 /* Copy remainder to mungable area. */
2136 p = (char *) alloca (strlen(q) + 8);
2137 strcpy (p, q);
2139 /* Output P, but remove known suffixes. */
2140 len = strlen (p);
2141 q = p + len;
2142 if (len >= 2
2143 && p[len - 2] == '.'
2144 && index("cCsSm", p[len - 1]))
2145 q = p + (len - 2);
2146 else if (len >= 3
2147 && p[len - 3] == '.'
2148 && p[len - 2] == 'c'
2149 && p[len - 1] == 'c')
2150 q = p + (len - 3);
2151 else if (len >= 4
2152 && p[len - 4] == '.'
2153 && p[len - 3] == 'c'
2154 && p[len - 2] == 'x'
2155 && p[len - 1] == 'x')
2156 q = p + (len - 4);
2157 else if (len >= 4
2158 && p[len - 4] == '.'
2159 && p[len - 3] == 'c'
2160 && p[len - 2] == 'p'
2161 && p[len - 1] == 'p')
2162 q = p + (len - 4);
2164 /* Supply our own suffix. */
2165 strcpy (q, OBJECT_SUFFIX);
2167 deps_output (p, ':');
2168 deps_output (in_fname, ' ');
2172 /* Scan the -imacros files before the main input.
2173 Much like #including them, but with no_output set
2174 so that only their macro definitions matter. */
2176 no_output++; no_record_file++;
2177 for (i = 1; i < argc; i++)
2178 if (pend_files[i]) {
2179 struct include_file *inc;
2180 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2181 if (fd < 0) {
2182 perror_with_name (pend_files[i]);
2183 return FATAL_EXIT_CODE;
2185 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2187 no_output--; no_record_file--;
2189 /* Copy the entire contents of the main input file into
2190 the stacked input buffer previously allocated for it. */
2192 /* JF check for stdin */
2193 if (in_fname == NULL || *in_fname == 0) {
2194 in_fname = "";
2195 f = 0;
2196 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2197 goto perror;
2199 if (fstat (f, &st) != 0)
2200 pfatal_with_name (in_fname);
2201 fp->nominal_fname = fp->fname = in_fname;
2202 fp->nominal_fname_len = strlen (in_fname);
2203 fp->lineno = 1;
2204 fp->system_header_p = 0;
2205 /* JF all this is mine about reading pipes and ttys */
2206 if (! S_ISREG (st.st_mode)) {
2207 /* Read input from a file that is not a normal disk file.
2208 We cannot preallocate a buffer with the correct size,
2209 so we must read in the file a piece at the time and make it bigger. */
2210 int size;
2211 int bsize;
2212 int cnt;
2214 if (S_ISDIR (st.st_mode))
2215 fatal ("Input file `%s' is a directory", in_fname);
2217 bsize = 2000;
2218 size = 0;
2219 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2220 for (;;) {
2221 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2222 if (cnt < 0) goto perror; /* error! */
2223 size += cnt;
2224 if (size != bsize) break; /* End of file */
2225 bsize *= 2;
2226 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2228 fp->length = size;
2229 } else {
2230 /* Read a file whose size we can determine in advance.
2231 For the sake of VMS, st.st_size is just an upper bound. */
2232 size_t s = (size_t) st.st_size;
2233 if (s != st.st_size || s + 2 < s)
2234 memory_full ();
2235 fp->buf = (U_CHAR *) xmalloc (s + 2);
2236 fp->length = safe_read (f, (char *) fp->buf, s);
2237 if (fp->length < 0) goto perror;
2239 fp->bufp = fp->buf;
2240 fp->if_stack = if_stack;
2242 /* Make sure data ends with a newline. And put a null after it. */
2244 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2245 /* Backslash-newline at end is not good enough. */
2246 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2247 fp->buf[fp->length++] = '\n';
2248 missing_newline = 1;
2250 fp->buf[fp->length] = '\0';
2252 /* Unless inhibited, convert trigraphs in the input. */
2254 if (!no_trigraphs)
2255 trigraph_pcp (fp);
2257 /* Now that we know the input file is valid, open the output. */
2259 if (!out_fname || !strcmp (out_fname, ""))
2260 out_fname = "stdout";
2261 else if (! freopen (out_fname, "w", stdout))
2262 pfatal_with_name (out_fname);
2264 output_line_directive (fp, &outbuf, 0, same_file);
2266 /* Scan the -include files before the main input. */
2268 no_record_file++;
2269 for (i = 1; i < argc; i++)
2270 if (pend_includes[i]) {
2271 struct include_file *inc;
2272 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2273 if (fd < 0) {
2274 perror_with_name (pend_includes[i]);
2275 return FATAL_EXIT_CODE;
2277 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2279 no_record_file--;
2281 /* Scan the input, processing macros and directives. */
2283 rescan (&outbuf, 0);
2285 if (missing_newline)
2286 fp->lineno--;
2288 if (pedantic && missing_newline)
2289 pedwarn ("file does not end in newline");
2291 /* Now we have processed the entire input
2292 Write whichever kind of output has been requested. */
2294 if (dump_macros == dump_only)
2295 dump_all_macros ();
2296 else if (! inhibit_output) {
2297 write_output ();
2300 if (print_deps) {
2301 /* Don't actually write the deps file if compilation has failed. */
2302 if (errors == 0) {
2303 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2304 pfatal_with_name (deps_file);
2305 fputs (deps_buffer, deps_stream);
2306 putc ('\n', deps_stream);
2307 if (deps_file) {
2308 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2309 fatal ("I/O error on output");
2314 if (pcp_outfile && pcp_outfile != stdout
2315 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2316 fatal ("I/O error on `-pcp' output");
2318 if (ferror (stdout) || fclose (stdout) != 0)
2319 fatal ("I/O error on output");
2321 if (errors)
2322 exit (FATAL_EXIT_CODE);
2323 exit (SUCCESS_EXIT_CODE);
2325 perror:
2326 pfatal_with_name (in_fname);
2327 return 0;
2330 /* Given a colon-separated list of file names PATH,
2331 add all the names to the search path for include files. */
2333 static void
2334 path_include (path)
2335 char *path;
2337 char *p;
2339 p = path;
2341 if (*p)
2342 while (1) {
2343 char *q = p;
2344 char c;
2345 struct file_name_list *dirtmp;
2347 /* Find the end of this name. */
2348 while ((c = *q++) != PATH_SEPARATOR && c)
2349 continue;
2351 q[-1] = 0;
2352 dirtmp = new_include_prefix (last_include, NULL_PTR,
2353 "", p == q ? "." : p);
2354 q[-1] = c;
2355 append_include_chain (dirtmp, dirtmp);
2357 /* Advance past this name. */
2358 p = q;
2359 if (! c)
2360 break;
2364 /* Return the address of the first character in S that equals C.
2365 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2366 Return 0 if there is no such character. Assume that C itself is not '\0'.
2367 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2368 but unfortunately memchr isn't autoconfigured yet. */
2370 static U_CHAR *
2371 index0 (s, c, n)
2372 U_CHAR *s;
2373 int c;
2374 size_t n;
2376 char *p = (char *) s;
2377 for (;;) {
2378 char *q = index (p, c);
2379 if (q)
2380 return (U_CHAR *) q;
2381 else {
2382 size_t l = strlen (p);
2383 if (l == n)
2384 return 0;
2385 l++;
2386 p += l;
2387 n -= l;
2392 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2393 before main CCCP processing. Name `pcp' is also in honor of the
2394 drugs the trigraph designers must have been on.
2396 Using an extra pass through the buffer takes a little extra time,
2397 but is infinitely less hairy than trying to handle trigraphs inside
2398 strings, etc. everywhere, and also makes sure that trigraphs are
2399 only translated in the top level of processing. */
2401 static void
2402 trigraph_pcp (buf)
2403 FILE_BUF *buf;
2405 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2406 int len;
2408 fptr = bptr = sptr = buf->buf;
2409 lptr = fptr + buf->length;
2410 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2411 if (*++sptr != '?')
2412 continue;
2413 switch (*++sptr) {
2414 case '=':
2415 c = '#';
2416 break;
2417 case '(':
2418 c = '[';
2419 break;
2420 case '/':
2421 c = '\\';
2422 break;
2423 case ')':
2424 c = ']';
2425 break;
2426 case '\'':
2427 c = '^';
2428 break;
2429 case '<':
2430 c = '{';
2431 break;
2432 case '!':
2433 c = '|';
2434 break;
2435 case '>':
2436 c = '}';
2437 break;
2438 case '-':
2439 c = '~';
2440 break;
2441 case '?':
2442 sptr--;
2443 continue;
2444 default:
2445 continue;
2447 len = sptr - fptr - 2;
2449 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2450 C, this will be memmove (). */
2451 if (bptr != fptr && len > 0)
2452 bcopy ((char *) fptr, (char *) bptr, len);
2454 bptr += len;
2455 *bptr++ = c;
2456 fptr = ++sptr;
2458 len = buf->length - (fptr - buf->buf);
2459 if (bptr != fptr && len > 0)
2460 bcopy ((char *) fptr, (char *) bptr, len);
2461 buf->length -= fptr - bptr;
2462 buf->buf[buf->length] = '\0';
2463 if (warn_trigraphs && fptr != bptr)
2464 warning_with_line (0, "%lu trigraph(s) encountered",
2465 (unsigned long) (fptr - bptr) / 2);
2468 /* Move all backslash-newline pairs out of embarrassing places.
2469 Exchange all such pairs following BP
2470 with any potentially-embarrassing characters that follow them.
2471 Potentially-embarrassing characters are / and *
2472 (because a backslash-newline inside a comment delimiter
2473 would cause it not to be recognized). */
2475 static void
2476 newline_fix (bp)
2477 U_CHAR *bp;
2479 register U_CHAR *p = bp;
2481 /* First count the backslash-newline pairs here. */
2483 while (p[0] == '\\' && p[1] == '\n')
2484 p += 2;
2486 /* What follows the backslash-newlines is not embarrassing. */
2488 if (*p != '/' && *p != '*')
2489 return;
2491 /* Copy all potentially embarrassing characters
2492 that follow the backslash-newline pairs
2493 down to where the pairs originally started. */
2495 while (*p == '*' || *p == '/')
2496 *bp++ = *p++;
2498 /* Now write the same number of pairs after the embarrassing chars. */
2499 while (bp < p) {
2500 *bp++ = '\\';
2501 *bp++ = '\n';
2505 /* Like newline_fix but for use within a directive-name.
2506 Move any backslash-newlines up past any following symbol constituents. */
2508 static void
2509 name_newline_fix (bp)
2510 U_CHAR *bp;
2512 register U_CHAR *p = bp;
2514 /* First count the backslash-newline pairs here. */
2515 while (p[0] == '\\' && p[1] == '\n')
2516 p += 2;
2518 /* What follows the backslash-newlines is not embarrassing. */
2520 if (!is_idchar[*p])
2521 return;
2523 /* Copy all potentially embarrassing characters
2524 that follow the backslash-newline pairs
2525 down to where the pairs originally started. */
2527 while (is_idchar[*p])
2528 *bp++ = *p++;
2530 /* Now write the same number of pairs after the embarrassing chars. */
2531 while (bp < p) {
2532 *bp++ = '\\';
2533 *bp++ = '\n';
2537 /* Look for lint commands in comments.
2539 When we come in here, ibp points into a comment. Limit is as one expects.
2540 scan within the comment -- it should start, after lwsp, with a lint command.
2541 If so that command is returned as a (constant) string.
2543 Upon return, any arg will be pointed to with argstart and will be
2544 arglen long. Note that we don't parse that arg since it will just
2545 be printed out again. */
2547 static char *
2548 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2549 register U_CHAR *ibp;
2550 register U_CHAR *limit;
2551 U_CHAR **argstart; /* point to command arg */
2552 int *arglen, *cmdlen; /* how long they are */
2554 HOST_WIDE_INT linsize;
2555 register U_CHAR *numptr; /* temp for arg parsing */
2557 *arglen = 0;
2559 SKIP_WHITE_SPACE (ibp);
2561 if (ibp >= limit) return NULL;
2563 linsize = limit - ibp;
2565 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2566 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2567 *cmdlen = 10;
2568 return "NOTREACHED";
2570 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2571 *cmdlen = 8;
2572 return "ARGSUSED";
2574 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2575 *cmdlen = 11;
2576 return "LINTLIBRARY";
2578 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2579 *cmdlen = 7;
2580 ibp += 7; linsize -= 7;
2581 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2583 /* OK, read a number */
2584 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2585 numptr++);
2586 *arglen = numptr - *argstart;
2587 return "VARARGS";
2589 return NULL;
2593 * The main loop of the program.
2595 * Read characters from the input stack, transferring them to the
2596 * output buffer OP.
2598 * Macros are expanded and push levels on the input stack.
2599 * At the end of such a level it is popped off and we keep reading.
2600 * At the end of any other kind of level, we return.
2601 * #-directives are handled, except within macros.
2603 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2604 * and insert them when appropriate. This is set while scanning macro
2605 * arguments before substitution. It is zero when scanning for final output.
2606 * There are three types of Newline markers:
2607 * * Newline - follows a macro name that was not expanded
2608 * because it appeared inside an expansion of the same macro.
2609 * This marker prevents future expansion of that identifier.
2610 * When the input is rescanned into the final output, these are deleted.
2611 * These are also deleted by ## concatenation.
2612 * * Newline Space (or Newline and any other whitespace character)
2613 * stands for a place that tokens must be separated or whitespace
2614 * is otherwise desirable, but where the ANSI standard specifies there
2615 * is no whitespace. This marker turns into a Space (or whichever other
2616 * whitespace char appears in the marker) in the final output,
2617 * but it turns into nothing in an argument that is stringified with #.
2618 * Such stringified arguments are the only place where the ANSI standard
2619 * specifies with precision that whitespace may not appear.
2621 * During this function, IP->bufp is kept cached in IBP for speed of access.
2622 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2623 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2624 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2625 * explicitly, and before RECACHE, since RECACHE uses OBP.
2628 static void
2629 rescan (op, output_marks)
2630 FILE_BUF *op;
2631 int output_marks;
2633 /* Character being scanned in main loop. */
2634 register U_CHAR c;
2636 /* Length of pending accumulated identifier. */
2637 register int ident_length = 0;
2639 /* Hash code of pending accumulated identifier. */
2640 register int hash = 0;
2642 /* Current input level (&instack[indepth]). */
2643 FILE_BUF *ip;
2645 /* Pointer for scanning input. */
2646 register U_CHAR *ibp;
2648 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2649 register U_CHAR *limit;
2651 /* Pointer for storing output. */
2652 register U_CHAR *obp;
2654 /* REDO_CHAR is nonzero if we are processing an identifier
2655 after backing up over the terminating character.
2656 Sometimes we process an identifier without backing up over
2657 the terminating character, if the terminating character
2658 is not special. Backing up is done so that the terminating character
2659 will be dispatched on again once the identifier is dealt with. */
2660 int redo_char = 0;
2662 /* 1 if within an identifier inside of which a concatenation
2663 marker (Newline -) has been seen. */
2664 int concatenated = 0;
2666 /* While scanning a comment or a string constant,
2667 this records the line it started on, for error messages. */
2668 int start_line;
2670 /* Record position of last `real' newline. */
2671 U_CHAR *beg_of_line;
2673 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2675 #define POPMACRO \
2676 do { ip->macro->type = T_MACRO; \
2677 if (ip->free_ptr) free (ip->free_ptr); \
2678 --indepth; } while (0)
2680 /* Reload `rescan's local variables that describe the current
2681 level of the input stack. */
2683 #define RECACHE \
2684 do { ip = &instack[indepth]; \
2685 ibp = ip->bufp; \
2686 limit = ip->buf + ip->length; \
2687 op->bufp = obp; \
2688 check_expand (op, limit - ibp); \
2689 beg_of_line = 0; \
2690 obp = op->bufp; } while (0)
2692 if (no_output && instack[indepth].fname != 0)
2693 skip_if_group (&instack[indepth], 1, NULL);
2695 obp = op->bufp;
2696 RECACHE;
2698 beg_of_line = ibp;
2700 /* Our caller must always put a null after the end of
2701 the input at each input stack level. */
2702 if (*limit != 0)
2703 abort ();
2705 while (1) {
2706 c = *ibp++;
2707 *obp++ = c;
2709 switch (c) {
2710 case '\\':
2711 if (*ibp == '\n' && !ip->macro) {
2712 /* At the top level, always merge lines ending with backslash-newline,
2713 even in middle of identifier. But do not merge lines in a macro,
2714 since backslash might be followed by a newline-space marker. */
2715 ++ibp;
2716 ++ip->lineno;
2717 --obp; /* remove backslash from obuf */
2718 break;
2720 /* If ANSI, backslash is just another character outside a string. */
2721 if (!traditional)
2722 goto randomchar;
2723 /* Otherwise, backslash suppresses specialness of following char,
2724 so copy it here to prevent the switch from seeing it.
2725 But first get any pending identifier processed. */
2726 if (ident_length > 0)
2727 goto specialchar;
2728 if (ibp < limit)
2729 *obp++ = *ibp++;
2730 break;
2732 case '%':
2733 if (ident_length || ip->macro || traditional)
2734 goto randomchar;
2735 while (*ibp == '\\' && ibp[1] == '\n') {
2736 ibp += 2;
2737 ++ip->lineno;
2739 if (*ibp != ':')
2740 break;
2741 /* Treat this %: digraph as if it were #. */
2742 /* Fall through. */
2744 case '#':
2745 if (assertions_flag) {
2746 if (ident_length)
2747 goto specialchar;
2748 /* Copy #foo (bar lose) without macro expansion. */
2749 obp[-1] = '#'; /* In case it was '%'. */
2750 SKIP_WHITE_SPACE (ibp);
2751 while (is_idchar[*ibp])
2752 *obp++ = *ibp++;
2753 SKIP_WHITE_SPACE (ibp);
2754 if (*ibp == '(') {
2755 ip->bufp = ibp;
2756 skip_paren_group (ip);
2757 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2758 obp += ip->bufp - ibp;
2759 ibp = ip->bufp;
2761 break;
2764 /* If this is expanding a macro definition, don't recognize
2765 preprocessing directives. */
2766 if (ip->macro != 0)
2767 goto randomchar;
2768 /* If this is expand_into_temp_buffer,
2769 don't recognize them either. Warn about them
2770 only after an actual newline at this level,
2771 not at the beginning of the input level. */
2772 if (! ip->fname) {
2773 if (ip->buf != beg_of_line)
2774 warning ("preprocessing directive not recognized within macro arg");
2775 goto randomchar;
2777 if (ident_length)
2778 goto specialchar;
2781 /* # keyword: a # must be first nonblank char on the line */
2782 if (beg_of_line == 0)
2783 goto randomchar;
2785 U_CHAR *bp;
2787 /* Scan from start of line, skipping whitespace, comments
2788 and backslash-newlines, and see if we reach this #.
2789 If not, this # is not special. */
2790 bp = beg_of_line;
2791 /* If -traditional, require # to be at beginning of line. */
2792 if (!traditional) {
2793 while (1) {
2794 if (is_hor_space[*bp])
2795 bp++;
2796 else if (*bp == '\\' && bp[1] == '\n')
2797 bp += 2;
2798 else if (*bp == '/' && bp[1] == '*') {
2799 bp += 2;
2800 while (1)
2802 if (*bp == '*')
2804 if (bp[1] == '/')
2806 bp += 2;
2807 break;
2810 else
2812 #ifdef MULTIBYTE_CHARS
2813 int length;
2814 length = local_mblen (bp, limit - bp);
2815 if (length > 1)
2816 bp += (length - 1);
2817 #endif
2819 bp++;
2822 /* There is no point in trying to deal with C++ // comments here,
2823 because if there is one, then this # must be part of the
2824 comment and we would never reach here. */
2825 else break;
2827 if (c == '%') {
2828 if (bp[0] != '%')
2829 break;
2830 while (bp[1] == '\\' && bp[2] == '\n')
2831 bp += 2;
2832 if (bp + 1 != ibp)
2833 break;
2834 /* %: appears at start of line; skip past the ':' too. */
2835 bp++;
2836 ibp++;
2839 if (bp + 1 != ibp)
2840 goto randomchar;
2843 /* This # can start a directive. */
2845 --obp; /* Don't copy the '#' */
2847 ip->bufp = ibp;
2848 op->bufp = obp;
2849 if (! handle_directive (ip, op)) {
2850 #ifdef USE_C_ALLOCA
2851 alloca (0);
2852 #endif
2853 /* Not a known directive: treat it as ordinary text.
2854 IP, OP, IBP, etc. have not been changed. */
2855 if (no_output && instack[indepth].fname) {
2856 /* If not generating expanded output,
2857 what we do with ordinary text is skip it.
2858 Discard everything until next # directive. */
2859 skip_if_group (&instack[indepth], 1, 0);
2860 RECACHE;
2861 beg_of_line = ibp;
2862 break;
2864 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2865 /* Don't expand an identifier that could be a macro directive.
2866 (Section 3.8.3 of the ANSI C standard) */
2867 SKIP_WHITE_SPACE (ibp);
2868 if (is_idstart[*ibp])
2870 *obp++ = *ibp++;
2871 while (is_idchar[*ibp])
2872 *obp++ = *ibp++;
2874 goto randomchar;
2876 #ifdef USE_C_ALLOCA
2877 alloca (0);
2878 #endif
2879 /* A # directive has been successfully processed. */
2880 /* If not generating expanded output, ignore everything until
2881 next # directive. */
2882 if (no_output && instack[indepth].fname)
2883 skip_if_group (&instack[indepth], 1, 0);
2884 obp = op->bufp;
2885 RECACHE;
2886 beg_of_line = ibp;
2887 break;
2889 case '\"': /* skip quoted string */
2890 case '\'':
2891 /* A single quoted string is treated like a double -- some
2892 programs (e.g., troff) are perverse this way */
2894 /* Handle any pending identifier;
2895 but the L in L'...' or L"..." is not an identifier. */
2896 if (ident_length) {
2897 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2898 goto specialchar;
2899 ident_length = hash = 0;
2902 start_line = ip->lineno;
2904 /* Skip ahead to a matching quote. */
2906 while (1) {
2907 if (ibp >= limit) {
2908 if (ip->macro != 0) {
2909 /* try harder: this string crosses a macro expansion boundary.
2910 This can happen naturally if -traditional.
2911 Otherwise, only -D can make a macro with an unmatched quote. */
2912 POPMACRO;
2913 RECACHE;
2914 continue;
2916 if (!traditional) {
2917 error_with_line (line_for_error (start_line),
2918 "unterminated string or character constant");
2919 if (multiline_string_line) {
2920 error_with_line (multiline_string_line,
2921 "possible real start of unterminated constant");
2922 multiline_string_line = 0;
2925 break;
2927 *obp++ = *ibp;
2928 switch (*ibp++) {
2929 case '\n':
2930 ++ip->lineno;
2931 ++op->lineno;
2932 /* Traditionally, end of line ends a string constant with no error.
2933 So exit the loop and record the new line. */
2934 if (traditional) {
2935 beg_of_line = ibp;
2936 goto while2end;
2938 if (c == '\'') {
2939 error_with_line (line_for_error (start_line),
2940 "unterminated character constant");
2941 goto while2end;
2943 if (multiline_string_line == 0) {
2944 if (pedantic)
2945 pedwarn_with_line (line_for_error (start_line),
2946 "string constant runs past end of line");
2947 multiline_string_line = ip->lineno - 1;
2949 break;
2951 case '\\':
2952 if (*ibp == '\n') {
2953 /* Backslash newline is replaced by nothing at all, but
2954 keep the line counts correct. But if we are reading
2955 from a macro, keep the backslash newline, since backslash
2956 newlines have already been processed. */
2957 if (ip->macro)
2958 *obp++ = '\n';
2959 else
2960 --obp;
2961 ++ibp;
2962 ++ip->lineno;
2963 } else {
2964 /* ANSI stupidly requires that in \\ the second \
2965 is *not* prevented from combining with a newline. */
2966 if (!ip->macro) {
2967 while (*ibp == '\\' && ibp[1] == '\n') {
2968 ibp += 2;
2969 ++ip->lineno;
2972 *obp++ = *ibp++;
2974 break;
2976 case '\"':
2977 case '\'':
2978 if (ibp[-1] == c)
2979 goto while2end;
2980 break;
2981 #ifdef MULTIBYTE_CHARS
2982 default:
2984 int length;
2985 --ibp;
2986 length = local_mblen (ibp, limit - ibp);
2987 if (length > 0)
2989 --obp;
2990 bcopy (ibp, obp, length);
2991 obp += length;
2992 ibp += length;
2994 else
2995 ++ibp;
2997 break;
2998 #endif
3001 while2end:
3002 break;
3004 case '/':
3005 if (ip->macro != 0)
3006 goto randomchar;
3007 if (*ibp == '\\' && ibp[1] == '\n')
3008 newline_fix (ibp);
3009 if (*ibp != '*'
3010 && !(cplusplus_comments && *ibp == '/'))
3011 goto randomchar;
3012 if (ident_length)
3013 goto specialchar;
3015 if (*ibp == '/') {
3016 /* C++ style comment... */
3017 start_line = ip->lineno;
3019 /* Comments are equivalent to spaces. */
3020 if (! put_out_comments)
3021 obp[-1] = ' ';
3024 U_CHAR *before_bp = ibp;
3026 while (++ibp < limit) {
3027 if (*ibp == '\n')
3029 if (put_out_comments) {
3030 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3031 obp += ibp - before_bp;
3033 break;
3035 if (*ibp == '\\')
3037 if (ibp + 1 < limit && ibp[1] == '\n')
3039 if (warn_comments)
3040 warning ("multiline `//' comment");
3041 ++ip->lineno;
3042 /* Copy the newline into the output buffer, in order to
3043 avoid the pain of a #line every time a multiline comment
3044 is seen. */
3045 if (!put_out_comments)
3046 *obp++ = '\n';
3047 ++op->lineno;
3048 ++ibp;
3051 else
3053 #ifdef MULTIBYTE_CHARS
3054 int length;
3055 length = local_mblen (ibp, limit - ibp);
3056 if (length > 1)
3057 ibp += (length - 1);
3058 #endif
3061 break;
3065 /* Ordinary C comment. Skip it, optionally copying it to output. */
3067 start_line = ip->lineno;
3069 ++ibp; /* Skip the star. */
3071 /* If this cpp is for lint, we peek inside the comments: */
3072 if (for_lint) {
3073 U_CHAR *argbp;
3074 int cmdlen, arglen;
3075 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
3077 if (lintcmd != NULL) {
3078 op->bufp = obp;
3079 check_expand (op, cmdlen + arglen + 14);
3080 obp = op->bufp;
3081 /* I believe it is always safe to emit this newline: */
3082 obp[-1] = '\n';
3083 bcopy ("#pragma lint ", (char *) obp, 13);
3084 obp += 13;
3085 bcopy (lintcmd, (char *) obp, cmdlen);
3086 obp += cmdlen;
3088 if (arglen != 0) {
3089 *(obp++) = ' ';
3090 bcopy (argbp, (char *) obp, arglen);
3091 obp += arglen;
3094 /* OK, now bring us back to the state we were in before we entered
3095 this branch. We need #line because the #pragma's newline always
3096 messes up the line count. */
3097 op->bufp = obp;
3098 output_line_directive (ip, op, 0, same_file);
3099 check_expand (op, limit - ibp + 2);
3100 obp = op->bufp;
3101 *(obp++) = '/';
3105 /* Comments are equivalent to spaces.
3106 Note that we already output the slash; we might not want it.
3107 For -traditional, a comment is equivalent to nothing. */
3108 if (! put_out_comments) {
3109 if (traditional)
3110 obp--;
3111 else
3112 obp[-1] = ' ';
3114 else
3115 *obp++ = '*';
3118 U_CHAR *before_bp = ibp;
3120 for (;;) {
3121 switch (*ibp++) {
3122 case '*':
3123 if (ibp[-2] == '/' && warn_comments)
3124 warning ("`/*' within comment");
3125 if (*ibp == '\\' && ibp[1] == '\n')
3126 newline_fix (ibp);
3127 if (*ibp == '/')
3128 goto comment_end;
3129 break;
3131 case '\n':
3132 ++ip->lineno;
3133 /* Copy the newline into the output buffer, in order to
3134 avoid the pain of a #line every time a multiline comment
3135 is seen. */
3136 if (!put_out_comments)
3137 *obp++ = '\n';
3138 ++op->lineno;
3139 break;
3141 case 0:
3142 if (limit < ibp) {
3143 error_with_line (line_for_error (start_line),
3144 "unterminated comment");
3145 goto limit_reached;
3147 break;
3148 #ifdef MULTIBYTE_CHARS
3149 default:
3151 int length;
3152 length = local_mblen (ibp, limit - ibp);
3153 if (length > 1)
3154 ibp += (length - 1);
3156 break;
3157 #endif
3160 comment_end:
3162 ibp++;
3163 if (put_out_comments) {
3164 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3165 obp += ibp - before_bp;
3168 break;
3170 case '$':
3171 if (! is_idchar['$'])
3172 goto randomchar;
3173 if (pedantic)
3174 pedwarn ("`$' in identifier");
3175 goto letter;
3177 case '0': case '1': case '2': case '3': case '4':
3178 case '5': case '6': case '7': case '8': case '9':
3179 /* If digit is not part of identifier, it starts a number,
3180 which means that following letters are not an identifier.
3181 "0x5" does not refer to an identifier "x5".
3182 So copy all alphanumerics that follow without accumulating
3183 as an identifier. Periods also, for sake of "3.e7". */
3185 if (ident_length == 0) {
3186 for (;;) {
3187 if (!ip->macro) {
3188 while (ibp[0] == '\\' && ibp[1] == '\n') {
3189 ++ip->lineno;
3190 ibp += 2;
3193 c = *ibp++;
3194 if (!is_idchar[c] && c != '.') {
3195 --ibp;
3196 break;
3198 *obp++ = c;
3199 /* A sign can be part of a preprocessing number
3200 if it follows an `e' or `p'. */
3201 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3202 if (!ip->macro) {
3203 while (ibp[0] == '\\' && ibp[1] == '\n') {
3204 ++ip->lineno;
3205 ibp += 2;
3208 if (*ibp == '+' || *ibp == '-') {
3209 *obp++ = *ibp++;
3210 /* But traditional C does not let the token go past the sign,
3211 and C89 does not allow `p'. */
3212 if (traditional || (c89 && (c == 'p' || c == 'P')))
3213 break;
3217 break;
3219 /* fall through */
3221 case '_':
3222 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3223 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3224 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3225 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3226 case 'y': case 'z':
3227 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3228 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3229 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3230 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3231 case 'Y': case 'Z':
3232 letter:
3233 ident_length++;
3234 /* Compute step of hash function, to avoid a proc call on every token */
3235 hash = HASHSTEP (hash, c);
3236 break;
3238 case '\n':
3239 if (ip->fname == 0 && *ibp == '-') {
3240 /* Newline - inhibits expansion of preceding token.
3241 If expanding a macro arg, we keep the newline -.
3242 In final output, it is deleted.
3243 We recognize Newline - in macro bodies and macro args. */
3244 if (! concatenated) {
3245 ident_length = 0;
3246 hash = 0;
3248 ibp++;
3249 if (!output_marks) {
3250 obp--;
3251 } else {
3252 /* If expanding a macro arg, keep the newline -. */
3253 *obp++ = '-';
3255 break;
3258 /* If reprocessing a macro expansion, newline is a special marker. */
3259 else if (ip->macro != 0) {
3260 /* Newline White is a "funny space" to separate tokens that are
3261 supposed to be separate but without space between.
3262 Here White means any whitespace character.
3263 Newline - marks a recursive macro use that is not
3264 supposed to be expandable. */
3266 if (is_space[*ibp]) {
3267 /* Newline Space does not prevent expansion of preceding token
3268 so expand the preceding token and then come back. */
3269 if (ident_length > 0)
3270 goto specialchar;
3272 /* If generating final output, newline space makes a space. */
3273 if (!output_marks) {
3274 obp[-1] = *ibp++;
3275 /* And Newline Newline makes a newline, so count it. */
3276 if (obp[-1] == '\n')
3277 op->lineno++;
3278 } else {
3279 /* If expanding a macro arg, keep the newline space.
3280 If the arg gets stringified, newline space makes nothing. */
3281 *obp++ = *ibp++;
3283 } else abort (); /* Newline followed by something random? */
3284 break;
3287 /* If there is a pending identifier, handle it and come back here. */
3288 if (ident_length > 0)
3289 goto specialchar;
3291 beg_of_line = ibp;
3293 /* Update the line counts and output a #line if necessary. */
3294 ++ip->lineno;
3295 ++op->lineno;
3296 if (ip->lineno != op->lineno) {
3297 op->bufp = obp;
3298 output_line_directive (ip, op, 1, same_file);
3299 check_expand (op, limit - ibp);
3300 obp = op->bufp;
3302 break;
3304 /* Come here either after (1) a null character that is part of the input
3305 or (2) at the end of the input, because there is a null there. */
3306 case 0:
3307 if (ibp <= limit)
3308 /* Our input really contains a null character. */
3309 goto randomchar;
3311 limit_reached:
3312 /* At end of a macro-expansion level, pop it and read next level. */
3313 if (ip->macro != 0) {
3314 obp--;
3315 ibp--;
3316 /* If traditional, and we have an identifier that ends here,
3317 process it now, so we get the right error for recursion. */
3318 if (traditional && ident_length
3319 && ! is_idchar[*instack[indepth - 1].bufp]) {
3320 redo_char = 1;
3321 goto randomchar;
3323 POPMACRO;
3324 RECACHE;
3325 break;
3328 /* If we don't have a pending identifier,
3329 return at end of input. */
3330 if (ident_length == 0) {
3331 obp--;
3332 ibp--;
3333 op->bufp = obp;
3334 ip->bufp = ibp;
3335 goto ending;
3338 /* If we do have a pending identifier, just consider this null
3339 a special character and arrange to dispatch on it again.
3340 The second time, IDENT_LENGTH will be zero so we will return. */
3342 /* Fall through */
3344 specialchar:
3346 /* Handle the case of a character such as /, ', " or null
3347 seen following an identifier. Back over it so that
3348 after the identifier is processed the special char
3349 will be dispatched on again. */
3351 ibp--;
3352 obp--;
3353 redo_char = 1;
3355 default:
3357 randomchar:
3359 if (ident_length > 0) {
3360 register HASHNODE *hp;
3362 /* We have just seen an identifier end. If it's a macro, expand it.
3364 IDENT_LENGTH is the length of the identifier
3365 and HASH is its hash code.
3367 The identifier has already been copied to the output,
3368 so if it is a macro we must remove it.
3370 If REDO_CHAR is 0, the char that terminated the identifier
3371 has been skipped in the output and the input.
3372 OBP-IDENT_LENGTH-1 points to the identifier.
3373 If the identifier is a macro, we must back over the terminator.
3375 If REDO_CHAR is 1, the terminating char has already been
3376 backed over. OBP-IDENT_LENGTH points to the identifier. */
3378 if (!pcp_outfile || pcp_inside_if) {
3379 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3380 hp = hp->next) {
3382 if (hp->length == ident_length) {
3383 int obufp_before_macroname;
3384 int op_lineno_before_macroname;
3385 register int i = ident_length;
3386 register U_CHAR *p = hp->name;
3387 register U_CHAR *q = obp - i;
3388 int disabled;
3390 if (! redo_char)
3391 q--;
3393 do { /* All this to avoid a strncmp () */
3394 if (*p++ != *q++)
3395 goto hashcollision;
3396 } while (--i);
3398 /* We found a use of a macro name.
3399 see if the context shows it is a macro call. */
3401 /* Back up over terminating character if not already done. */
3402 if (! redo_char) {
3403 ibp--;
3404 obp--;
3407 /* Save this as a displacement from the beginning of the output
3408 buffer. We can not save this as a position in the output
3409 buffer, because it may get realloc'ed by RECACHE. */
3410 obufp_before_macroname = (obp - op->buf) - ident_length;
3411 op_lineno_before_macroname = op->lineno;
3413 if (hp->type == T_PCSTRING) {
3414 pcstring_used (hp); /* Mark the definition of this key
3415 as needed, ensuring that it
3416 will be output. */
3417 break; /* Exit loop, since the key cannot have a
3418 definition any longer. */
3421 /* Record whether the macro is disabled. */
3422 disabled = hp->type == T_DISABLED;
3424 /* This looks like a macro ref, but if the macro was disabled,
3425 just copy its name and put in a marker if requested. */
3427 if (disabled) {
3428 #if 0
3429 /* This error check caught useful cases such as
3430 #define foo(x,y) bar (x (y,0), y)
3431 foo (foo, baz) */
3432 if (traditional)
3433 error ("recursive use of macro `%s'", hp->name);
3434 #endif
3436 if (output_marks) {
3437 check_expand (op, limit - ibp + 2);
3438 *obp++ = '\n';
3439 *obp++ = '-';
3441 break;
3444 /* If macro wants an arglist, verify that a '(' follows.
3445 first skip all whitespace, copying it to the output
3446 after the macro name. Then, if there is no '(',
3447 decide this is not a macro call and leave things that way. */
3448 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3449 && hp->value.defn->nargs >= 0)
3451 U_CHAR *old_ibp = ibp;
3452 U_CHAR *old_obp = obp;
3453 int old_iln = ip->lineno;
3454 int old_oln = op->lineno;
3456 while (1) {
3457 /* Scan forward over whitespace, copying it to the output. */
3458 if (ibp == limit && ip->macro != 0) {
3459 POPMACRO;
3460 RECACHE;
3461 old_ibp = ibp;
3462 old_obp = obp;
3463 old_iln = ip->lineno;
3464 old_oln = op->lineno;
3466 else if (is_space[*ibp]) {
3467 *obp++ = *ibp++;
3468 if (ibp[-1] == '\n') {
3469 if (ip->macro == 0) {
3470 /* Newline in a file. Count it. */
3471 ++ip->lineno;
3472 ++op->lineno;
3473 } else if (!output_marks) {
3474 /* A newline mark, and we don't want marks
3475 in the output. If it is newline-hyphen,
3476 discard it entirely. Otherwise, it is
3477 newline-whitechar, so keep the whitechar. */
3478 obp--;
3479 if (*ibp == '-')
3480 ibp++;
3481 else {
3482 if (*ibp == '\n')
3483 ++op->lineno;
3484 *obp++ = *ibp++;
3486 } else {
3487 /* A newline mark; copy both chars to the output. */
3488 *obp++ = *ibp++;
3492 else if (ip->macro)
3493 break;
3494 else if (*ibp == '/') {
3495 /* If a comment, copy it unchanged or discard it. */
3496 if (ibp[1] == '\\' && ibp[2] == '\n')
3497 newline_fix (ibp + 1);
3498 if (ibp[1] == '*') {
3499 if (put_out_comments) {
3500 *obp++ = '/';
3501 *obp++ = '*';
3502 } else if (! traditional) {
3503 *obp++ = ' ';
3505 for (ibp += 2; ibp < limit; ibp++) {
3506 /* We need not worry about newline-marks,
3507 since they are never found in comments. */
3508 if (ibp[0] == '*') {
3509 if (ibp[1] == '\\' && ibp[2] == '\n')
3510 newline_fix (ibp + 1);
3511 if (ibp[1] == '/') {
3512 ibp += 2;
3513 if (put_out_comments) {
3514 *obp++ = '*';
3515 *obp++ = '/';
3517 break;
3520 else if (*ibp == '\n') {
3521 /* Newline in a file. Count it. */
3522 ++ip->lineno;
3523 ++op->lineno;
3525 else
3527 #ifdef MULTIBYTE_CHARS
3528 int length;
3529 length = local_mblen (ibp, limit - ibp);
3530 if (length > 1)
3532 if (put_out_comments)
3534 bcopy (ibp, obp, length - 1);
3535 obp += length - 1;
3537 ibp += (length - 1);
3539 #endif
3541 if (put_out_comments)
3542 *obp++ = *ibp;
3544 } else if (ibp[1] == '/' && cplusplus_comments) {
3545 if (put_out_comments) {
3546 *obp++ = '/';
3547 *obp++ = '/';
3548 } else if (! traditional) {
3549 *obp++ = ' ';
3551 for (ibp += 2; ; ibp++)
3553 if (*ibp == '\n')
3554 break;
3555 if (*ibp == '\\' && ibp[1] == '\n')
3557 if (put_out_comments)
3558 *obp++ = *ibp++;
3560 else
3562 #ifdef MULTIBYTE_CHARS
3563 int length;
3564 length = local_mblen (ibp, limit - ibp);
3565 if (length > 1)
3567 if (put_out_comments)
3569 bcopy (ibp, obp, length - 1);
3570 obp += length - 1;
3572 ibp += (length - 1);
3574 #endif
3576 if (put_out_comments)
3577 *obp++ = *ibp;
3579 } else
3580 break;
3582 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3583 ibp += 2;
3584 ++ip->lineno;
3586 else break;
3588 if (*ibp != '(') {
3589 /* It isn't a macro call.
3590 Put back the space that we just skipped. */
3591 ibp = old_ibp;
3592 obp = old_obp;
3593 ip->lineno = old_iln;
3594 op->lineno = old_oln;
3595 /* Exit the for loop. */
3596 break;
3600 /* This is now known to be a macro call.
3601 Discard the macro name from the output,
3602 along with any following whitespace just copied,
3603 but preserve newlines if not outputting marks since this
3604 is more likely to do the right thing with line numbers. */
3605 obp = op->buf + obufp_before_macroname;
3606 if (output_marks)
3607 op->lineno = op_lineno_before_macroname;
3608 else {
3609 int newlines = op->lineno - op_lineno_before_macroname;
3610 while (0 < newlines--)
3611 *obp++ = '\n';
3614 /* Prevent accidental token-pasting with a character
3615 before the macro call. */
3616 if (!traditional && obp != op->buf) {
3617 switch (obp[-1]) {
3618 case '!': case '%': case '&': case '*':
3619 case '+': case '-': case '.': case '/':
3620 case ':': case '<': case '=': case '>':
3621 case '^': case '|':
3622 /* If we are expanding a macro arg, make a newline marker
3623 to separate the tokens. If we are making real output,
3624 a plain space will do. */
3625 if (output_marks)
3626 *obp++ = '\n';
3627 *obp++ = ' ';
3631 /* Expand the macro, reading arguments as needed,
3632 and push the expansion on the input stack. */
3633 ip->bufp = ibp;
3634 op->bufp = obp;
3635 macroexpand (hp, op);
3637 /* Reexamine input stack, since macroexpand has pushed
3638 a new level on it. */
3639 obp = op->bufp;
3640 RECACHE;
3641 break;
3643 hashcollision:
3645 } /* End hash-table-search loop */
3647 ident_length = hash = 0; /* Stop collecting identifier */
3648 redo_char = 0;
3649 concatenated = 0;
3650 } /* End if (ident_length > 0) */
3651 } /* End switch */
3652 } /* End per-char loop */
3654 /* Come here to return -- but first give an error message
3655 if there was an unterminated successful conditional. */
3656 ending:
3657 if (if_stack != ip->if_stack)
3659 char *str;
3661 switch (if_stack->type)
3663 case T_IF:
3664 str = "if";
3665 break;
3666 case T_IFDEF:
3667 str = "ifdef";
3668 break;
3669 case T_IFNDEF:
3670 str = "ifndef";
3671 break;
3672 case T_ELSE:
3673 str = "else";
3674 break;
3675 case T_ELIF:
3676 str = "elif";
3677 break;
3678 default:
3679 abort ();
3682 error_with_line (line_for_error (if_stack->lineno),
3683 "unterminated `#%s' conditional", str);
3685 if_stack = ip->if_stack;
3689 * Rescan a string into a temporary buffer and return the result
3690 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3692 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3693 * and insert such markers when appropriate. See `rescan' for details.
3694 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3695 * before substitution; it is 0 for other uses.
3697 static FILE_BUF
3698 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3699 U_CHAR *buf, *limit;
3700 int output_marks, assertions;
3702 register FILE_BUF *ip;
3703 FILE_BUF obuf;
3704 int length = limit - buf;
3705 U_CHAR *buf1;
3706 int odepth = indepth;
3707 int save_assertions_flag = assertions_flag;
3709 assertions_flag = assertions;
3711 if (length < 0)
3712 abort ();
3714 /* Set up the input on the input stack. */
3716 buf1 = (U_CHAR *) alloca (length + 1);
3718 register U_CHAR *p1 = buf;
3719 register U_CHAR *p2 = buf1;
3721 while (p1 != limit)
3722 *p2++ = *p1++;
3724 buf1[length] = 0;
3726 /* Set up to receive the output. */
3728 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3729 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3730 obuf.nominal_fname = 0;
3731 obuf.inc = 0;
3732 obuf.dir = 0;
3733 obuf.fname = 0;
3734 obuf.macro = 0;
3735 obuf.if_stack = 0;
3736 obuf.free_ptr = 0;
3737 obuf.system_header_p = 0;
3739 CHECK_DEPTH ({return obuf;});
3741 ++indepth;
3743 ip = &instack[indepth];
3744 ip->fname = 0;
3745 ip->nominal_fname = 0;
3746 ip->nominal_fname_len = 0;
3747 ip->inc = 0;
3748 ip->system_header_p = 0;
3749 ip->macro = 0;
3750 ip->free_ptr = 0;
3751 ip->length = length;
3752 ip->buf = ip->bufp = buf1;
3753 ip->if_stack = if_stack;
3755 ip->lineno = obuf.lineno = 1;
3757 /* Scan the input, create the output. */
3758 rescan (&obuf, output_marks);
3760 /* Pop input stack to original state. */
3761 --indepth;
3763 if (indepth != odepth)
3764 abort ();
3766 /* Record the output. */
3767 obuf.length = obuf.bufp - obuf.buf;
3769 assertions_flag = save_assertions_flag;
3770 return obuf;
3774 * Process a # directive. Expects IP->bufp to point after the '#', as in
3775 * `#define foo bar'. Passes to the directive handler
3776 * (do_define, do_include, etc.): the addresses of the 1st and
3777 * last chars of the directive (starting immediately after the #
3778 * keyword), plus op and the keyword table pointer. If the directive
3779 * contains comments it is copied into a temporary buffer sans comments
3780 * and the temporary buffer is passed to the directive handler instead.
3781 * Likewise for backslash-newlines.
3783 * Returns nonzero if this was a known # directive.
3784 * Otherwise, returns zero, without advancing the input pointer.
3787 static int
3788 handle_directive (ip, op)
3789 FILE_BUF *ip, *op;
3791 register U_CHAR *bp, *cp;
3792 register struct directive *kt;
3793 register int ident_length;
3794 U_CHAR *resume_p;
3796 /* Nonzero means we must copy the entire directive
3797 to get rid of comments or backslash-newlines. */
3798 int copy_directive = 0;
3800 U_CHAR *ident, *after_ident;
3802 bp = ip->bufp;
3804 /* Record where the directive started. do_xifdef needs this. */
3805 directive_start = bp - 1;
3807 ignore_escape_flag = 1;
3809 /* Skip whitespace and \-newline. */
3810 while (1) {
3811 if (is_hor_space[*bp]) {
3812 if (*bp != ' ' && *bp != '\t' && pedantic)
3813 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3814 bp++;
3815 } else if (*bp == '/') {
3816 if (bp[1] == '\\' && bp[2] == '\n')
3817 newline_fix (bp + 1);
3818 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3819 break;
3820 ip->bufp = bp + 2;
3821 skip_to_end_of_comment (ip, &ip->lineno, 0);
3822 bp = ip->bufp;
3823 } else if (*bp == '\\' && bp[1] == '\n') {
3824 bp += 2; ip->lineno++;
3825 } else break;
3828 /* Now find end of directive name.
3829 If we encounter a backslash-newline, exchange it with any following
3830 symbol-constituents so that we end up with a contiguous name. */
3832 cp = bp;
3833 while (1) {
3834 if (is_idchar[*cp])
3835 cp++;
3836 else {
3837 if (*cp == '\\' && cp[1] == '\n')
3838 name_newline_fix (cp);
3839 if (is_idchar[*cp])
3840 cp++;
3841 else break;
3844 ident_length = cp - bp;
3845 ident = bp;
3846 after_ident = cp;
3848 /* A line of just `#' becomes blank. */
3850 if (ident_length == 0 && *after_ident == '\n') {
3851 ip->bufp = after_ident;
3852 return 1;
3855 if (ident_length == 0 || !is_idstart[*ident]) {
3856 U_CHAR *p = ident;
3857 while (is_idchar[*p]) {
3858 if (*p < '0' || *p > '9')
3859 break;
3860 p++;
3862 /* Handle # followed by a line number. */
3863 if (p != ident && !is_idchar[*p]) {
3864 static struct directive line_directive_table[] = {
3865 { 4, do_line, "line", T_LINE},
3867 if (pedantic)
3868 pedwarn ("`#' followed by integer");
3869 after_ident = ident;
3870 kt = line_directive_table;
3871 ignore_escape_flag = 0;
3872 goto old_linenum;
3875 /* Avoid error for `###' and similar cases unless -pedantic. */
3876 if (p == ident) {
3877 while (*p == '#' || is_hor_space[*p]) p++;
3878 if (*p == '\n') {
3879 if (pedantic && !lang_asm)
3880 warning ("invalid preprocessing directive");
3881 return 0;
3885 if (!lang_asm)
3886 error ("invalid preprocessing directive name");
3888 return 0;
3892 * Decode the keyword and call the appropriate expansion
3893 * routine, after moving the input pointer up to the next line.
3895 for (kt = directive_table; kt->length > 0; kt++) {
3896 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3897 register U_CHAR *buf;
3898 register U_CHAR *limit;
3899 int unterminated;
3900 int junk;
3901 int *already_output;
3903 /* Nonzero means do not delete comments within the directive.
3904 #define needs this when -traditional. */
3905 int keep_comments;
3907 old_linenum:
3909 limit = ip->buf + ip->length;
3910 unterminated = 0;
3911 already_output = 0;
3912 keep_comments = traditional && kt->type == T_DEFINE;
3913 /* #import is defined only in Objective C, or when on the NeXT. */
3914 if (kt->type == T_IMPORT
3915 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3916 break;
3918 /* Find the end of this directive (first newline not backslashed
3919 and not in a string or comment).
3920 Set COPY_DIRECTIVE if the directive must be copied
3921 (it contains a backslash-newline or a comment). */
3923 buf = bp = after_ident;
3924 while (bp < limit) {
3925 register U_CHAR c = *bp++;
3926 switch (c) {
3927 case '\\':
3928 if (bp < limit) {
3929 if (*bp == '\n') {
3930 ip->lineno++;
3931 copy_directive = 1;
3932 bp++;
3933 } else if (traditional)
3934 bp++;
3936 break;
3938 case '"':
3939 /* "..." is special for #include. */
3940 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3941 while (bp < limit && *bp != '\n') {
3942 if (*bp == '"') {
3943 bp++;
3944 break;
3946 if (*bp == '\\' && bp[1] == '\n') {
3947 ip->lineno++;
3948 copy_directive = 1;
3949 bp++;
3951 bp++;
3953 break;
3955 /* Fall through. */
3956 case '\'':
3957 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3958 /* Don't bother calling the directive if we already got an error
3959 message due to unterminated string. Skip everything and pretend
3960 we called the directive. */
3961 if (unterminated) {
3962 if (traditional) {
3963 /* Traditional preprocessing permits unterminated strings. */
3964 ip->bufp = bp;
3965 goto endloop1;
3967 ip->bufp = bp;
3968 return 1;
3970 break;
3972 /* <...> is special for #include. */
3973 case '<':
3974 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3975 break;
3976 while (bp < limit && *bp != '>' && *bp != '\n') {
3977 if (*bp == '\\' && bp[1] == '\n') {
3978 ip->lineno++;
3979 copy_directive = 1;
3980 bp++;
3982 bp++;
3984 break;
3986 case '/':
3987 if (*bp == '\\' && bp[1] == '\n')
3988 newline_fix (bp);
3989 if (*bp == '*'
3990 || (cplusplus_comments && *bp == '/')) {
3991 U_CHAR *obp = bp - 1;
3992 ip->bufp = bp + 1;
3993 skip_to_end_of_comment (ip, &ip->lineno, 0);
3994 bp = ip->bufp;
3995 /* No need to copy the directive because of a comment at the end;
3996 just don't include the comment in the directive. */
3997 if (!put_out_comments) {
3998 U_CHAR *p;
3999 for (p = bp; *p == ' ' || *p == '\t'; p++)
4000 continue;
4001 if (*p == '\n') {
4002 bp = obp;
4003 goto endloop1;
4006 /* Don't remove the comments if -traditional. */
4007 if (! keep_comments)
4008 copy_directive++;
4010 break;
4012 case '\f':
4013 case '\r':
4014 case '\v':
4015 if (pedantic)
4016 pedwarn ("%s in preprocessing directive", char_name[c]);
4017 break;
4019 case '\n':
4020 --bp; /* Point to the newline */
4021 ip->bufp = bp;
4022 goto endloop1;
4025 ip->bufp = bp;
4027 endloop1:
4028 resume_p = ip->bufp;
4029 /* BP is the end of the directive.
4030 RESUME_P is the next interesting data after the directive.
4031 A comment may come between. */
4033 /* If a directive should be copied through, and -C was given,
4034 pass it through before removing comments. */
4035 if (!no_output && put_out_comments
4036 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
4037 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4038 : kt->type == T_PRAGMA)) {
4039 int len;
4041 /* Output directive name. */
4042 check_expand (op, kt->length + 2);
4043 /* Make sure # is at the start of a line */
4044 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
4045 op->lineno++;
4046 *op->bufp++ = '\n';
4048 *op->bufp++ = '#';
4049 bcopy (kt->name, op->bufp, kt->length);
4050 op->bufp += kt->length;
4052 /* Output arguments. */
4053 len = (bp - buf);
4054 check_expand (op, len);
4055 bcopy (buf, (char *) op->bufp, len);
4056 op->bufp += len;
4057 /* Take account of any (escaped) newlines just output. */
4058 while (--len >= 0)
4059 if (buf[len] == '\n')
4060 op->lineno++;
4062 already_output = &junk;
4063 } /* Don't we need a newline or #line? */
4065 if (copy_directive) {
4066 register U_CHAR *xp = buf;
4067 /* Need to copy entire directive into temp buffer before dispatching */
4069 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
4070 some slop */
4071 buf = cp;
4073 /* Copy to the new buffer, deleting comments
4074 and backslash-newlines (and whitespace surrounding the latter). */
4076 while (xp < bp) {
4077 register U_CHAR c = *xp++;
4078 *cp++ = c;
4080 switch (c) {
4081 case '\n':
4082 abort (); /* A bare newline should never part of the line. */
4083 break;
4085 /* <...> is special for #include. */
4086 case '<':
4087 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
4088 break;
4089 while (xp < bp && c != '>') {
4090 c = *xp++;
4091 if (c == '\\' && xp < bp && *xp == '\n')
4092 xp++;
4093 else
4094 *cp++ = c;
4096 break;
4098 case '\\':
4099 if (*xp == '\n') {
4100 xp++;
4101 cp--;
4102 if (cp != buf && is_hor_space[cp[-1]]) {
4103 while (cp - 1 != buf && is_hor_space[cp[-2]])
4104 cp--;
4105 SKIP_WHITE_SPACE (xp);
4106 } else if (is_hor_space[*xp]) {
4107 *cp++ = *xp++;
4108 SKIP_WHITE_SPACE (xp);
4110 } else if (traditional && xp < bp) {
4111 *cp++ = *xp++;
4113 break;
4115 case '\'':
4116 case '\"':
4118 register U_CHAR *bp1
4119 = skip_quoted_string (xp - 1, bp, ip->lineno,
4120 NULL_PTR, NULL_PTR, NULL_PTR);
4121 while (xp != bp1)
4122 *cp++ = *xp++;
4124 break;
4126 case '/':
4127 if (*xp == '*'
4128 || (cplusplus_comments && *xp == '/')) {
4129 ip->bufp = xp + 1;
4130 /* If we already copied the directive through,
4131 already_output != 0 prevents outputting comment now. */
4132 skip_to_end_of_comment (ip, already_output, 0);
4133 if (keep_comments)
4134 while (xp != ip->bufp)
4135 *cp++ = *xp++;
4136 /* Delete or replace the slash. */
4137 else if (traditional)
4138 cp--;
4139 else
4140 cp[-1] = ' ';
4141 xp = ip->bufp;
4146 /* Null-terminate the copy. */
4148 *cp = 0;
4149 } else
4150 cp = bp;
4152 ip->bufp = resume_p;
4154 /* Some directives should be written out for cc1 to process,
4155 just as if they were not defined. And sometimes we're copying
4156 directives through. */
4158 if (!no_output && already_output == 0
4159 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
4160 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4161 : kt->type == T_PRAGMA)) {
4162 int len;
4164 /* Output directive name. */
4165 check_expand (op, kt->length + 1);
4166 *op->bufp++ = '#';
4167 bcopy (kt->name, (char *) op->bufp, kt->length);
4168 op->bufp += kt->length;
4170 if (kt->type == T_DEFINE && dump_macros == dump_names) {
4171 /* Output `#define name' only. */
4172 U_CHAR *xp = buf;
4173 U_CHAR *yp;
4174 SKIP_WHITE_SPACE (xp);
4175 yp = xp;
4176 while (is_idchar[*xp]) xp++;
4177 len = (xp - yp);
4178 check_expand (op, len + 1);
4179 *op->bufp++ = ' ';
4180 bcopy (yp, (char *) op->bufp, len);
4181 } else {
4182 /* Output entire directive. */
4183 len = (cp - buf);
4184 check_expand (op, len);
4185 bcopy (buf, (char *) op->bufp, len);
4187 op->bufp += len;
4188 } /* Don't we need a newline or #line? */
4190 /* Call the appropriate directive handler. buf now points to
4191 either the appropriate place in the input buffer, or to
4192 the temp buffer if it was necessary to make one. cp
4193 points to the first char after the contents of the (possibly
4194 copied) directive, in either case. */
4195 (*kt->func) (buf, cp, op, kt);
4196 check_expand (op, ip->length - (ip->bufp - ip->buf));
4198 return 1;
4202 /* It is deliberate that we don't warn about undefined directives.
4203 That is the responsibility of cc1. */
4204 return 0;
4207 static struct tm *
4208 timestamp ()
4210 static struct tm *timebuf;
4211 if (!timebuf) {
4212 time_t t = time ((time_t *) 0);
4213 timebuf = localtime (&t);
4215 return timebuf;
4218 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4219 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4223 * expand things like __FILE__. Place the expansion into the output
4224 * buffer *without* rescanning.
4227 static void
4228 special_symbol (hp, op)
4229 HASHNODE *hp;
4230 FILE_BUF *op;
4232 char *buf;
4233 int i, len;
4234 int true_indepth;
4235 FILE_BUF *ip = NULL;
4236 struct tm *timebuf;
4238 int paren = 0; /* For special `defined' keyword */
4240 if (pcp_outfile && pcp_inside_if
4241 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4242 error ("Predefined macro `%s' used inside `#if' during precompilation",
4243 hp->name);
4245 for (i = indepth; i >= 0; i--)
4246 if (instack[i].fname != NULL) {
4247 ip = &instack[i];
4248 break;
4250 if (ip == NULL) {
4251 error ("cccp error: not in any file?!");
4252 return; /* the show must go on */
4255 switch (hp->type) {
4256 case T_FILE:
4257 case T_BASE_FILE:
4259 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4260 char *string = p->nominal_fname;
4262 if (string)
4264 size_t string_len = p->nominal_fname_len;
4265 buf = (char *) alloca (3 + 4 * string_len);
4266 quote_string (buf, string, string_len);
4268 else
4269 buf = "\"\"";
4271 break;
4274 case T_INCLUDE_LEVEL:
4275 true_indepth = 0;
4276 for (i = indepth; i >= 0; i--)
4277 if (instack[i].fname != NULL)
4278 true_indepth++;
4280 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4281 sprintf (buf, "%d", true_indepth - 1);
4282 break;
4284 case T_VERSION:
4285 buf = (char *) alloca (3 + strlen (version_string));
4286 sprintf (buf, "\"%s\"", version_string);
4287 break;
4289 #ifndef NO_BUILTIN_SIZE_TYPE
4290 case T_SIZE_TYPE:
4291 buf = SIZE_TYPE;
4292 break;
4293 #endif
4295 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4296 case T_PTRDIFF_TYPE:
4297 buf = PTRDIFF_TYPE;
4298 break;
4299 #endif
4301 case T_WCHAR_TYPE:
4302 buf = wchar_type;
4303 break;
4305 case T_USER_LABEL_PREFIX_TYPE:
4306 buf = user_label_prefix;
4307 break;
4309 case T_REGISTER_PREFIX_TYPE:
4310 buf = REGISTER_PREFIX;
4311 break;
4313 case T_IMMEDIATE_PREFIX_TYPE:
4314 buf = IMMEDIATE_PREFIX;
4315 break;
4317 case T_CONST:
4318 buf = hp->value.cpval;
4319 #ifdef STDC_0_IN_SYSTEM_HEADERS
4320 if (ip->system_header_p
4321 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4322 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4323 buf = "0";
4324 #endif
4325 if (pcp_inside_if && pcp_outfile)
4326 /* Output a precondition for this macro use */
4327 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4328 break;
4330 case T_SPECLINE:
4331 buf = (char *) alloca (10);
4332 sprintf (buf, "%d", ip->lineno);
4333 break;
4335 case T_DATE:
4336 case T_TIME:
4337 buf = (char *) alloca (20);
4338 timebuf = timestamp ();
4339 if (hp->type == T_DATE)
4340 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4341 timebuf->tm_mday, timebuf->tm_year + 1900);
4342 else
4343 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4344 timebuf->tm_sec);
4345 break;
4347 case T_SPEC_DEFINED:
4348 buf = " 0 "; /* Assume symbol is not defined */
4349 ip = &instack[indepth];
4350 SKIP_WHITE_SPACE (ip->bufp);
4351 if (*ip->bufp == '(') {
4352 paren++;
4353 ip->bufp++; /* Skip over the paren */
4354 SKIP_WHITE_SPACE (ip->bufp);
4357 if (!is_idstart[*ip->bufp])
4358 goto oops;
4359 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4360 goto oops;
4361 if ((hp = lookup (ip->bufp, -1, -1))) {
4362 if (pcp_outfile && pcp_inside_if
4363 && (hp->type == T_CONST
4364 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4365 /* Output a precondition for this macro use. */
4366 fprintf (pcp_outfile, "#define %s\n", hp->name);
4367 buf = " 1 ";
4369 else
4370 if (pcp_outfile && pcp_inside_if) {
4371 /* Output a precondition for this macro use */
4372 U_CHAR *cp = ip->bufp;
4373 fprintf (pcp_outfile, "#undef ");
4374 while (is_idchar[*cp]) /* Ick! */
4375 fputc (*cp++, pcp_outfile);
4376 putc ('\n', pcp_outfile);
4378 while (is_idchar[*ip->bufp])
4379 ++ip->bufp;
4380 SKIP_WHITE_SPACE (ip->bufp);
4381 if (paren) {
4382 if (*ip->bufp != ')')
4383 goto oops;
4384 ++ip->bufp;
4386 break;
4388 oops:
4390 error ("`defined' without an identifier");
4391 break;
4393 default:
4394 error ("cccp error: invalid special hash type"); /* time for gdb */
4395 abort ();
4397 len = strlen (buf);
4398 check_expand (op, len);
4399 bcopy (buf, (char *) op->bufp, len);
4400 op->bufp += len;
4402 return;
4406 /* Routines to handle #directives */
4408 /* Handle #include and #import.
4409 This function expects to see "fname" or <fname> on the input. */
4411 static int
4412 do_include (buf, limit, op, keyword)
4413 U_CHAR *buf, *limit;
4414 FILE_BUF *op;
4415 struct directive *keyword;
4417 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4418 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4419 static int import_warning = 0;
4420 char *fname; /* Dynamically allocated fname buffer */
4421 char *pcftry;
4422 char *pcfname;
4423 char *fbeg, *fend; /* Beginning and end of fname */
4424 U_CHAR *fin;
4426 struct file_name_list *search_start = include; /* Chain of dirs to search */
4427 struct file_name_list *dsp; /* First in chain, if #include "..." */
4428 struct file_name_list *searchptr = 0;
4429 size_t flen;
4431 int f = -3; /* file number */
4432 struct include_file *inc = 0;
4434 int retried = 0; /* Have already tried macro
4435 expanding the include line*/
4436 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4437 #ifdef VMS
4438 int vaxc_include = 0; /* 1 for token without punctuation */
4439 #endif
4440 int pcf = -1;
4441 char *pcfbuf;
4442 char *pcfbuflimit;
4443 int pcfnum;
4445 if (pedantic && !instack[indepth].system_header_p)
4447 if (importing)
4448 pedwarn ("ANSI C does not allow `#import'");
4449 if (skip_dirs)
4450 pedwarn ("ANSI C does not allow `#include_next'");
4453 if (importing && warn_import && !inhibit_warnings
4454 && !instack[indepth].system_header_p && !import_warning) {
4455 import_warning = 1;
4456 warning ("using `#import' is not recommended");
4457 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4458 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4459 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4460 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4461 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4462 fprintf (stderr, " ... <real contents of file> ...\n");
4463 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4464 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4465 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4466 fprintf (stderr, "when it is equipped with such a conditional.\n");
4469 get_filename:
4471 fin = buf;
4472 SKIP_WHITE_SPACE (fin);
4473 /* Discard trailing whitespace so we can easily see
4474 if we have parsed all the significant chars we were given. */
4475 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4476 fbeg = fend = (char *) alloca (limit - fin);
4478 switch (*fin++) {
4479 case '\"':
4481 FILE_BUF *fp;
4482 /* Copy the operand text, concatenating the strings. */
4484 for (;;) {
4485 for (;;) {
4486 if (fin == limit)
4487 goto invalid_include_file_name;
4488 *fend = *fin++;
4489 if (*fend == '"')
4490 break;
4491 fend++;
4493 if (fin == limit)
4494 break;
4495 /* If not at the end, there had better be another string. */
4496 /* Skip just horiz space, and don't go past limit. */
4497 while (fin != limit && is_hor_space[*fin]) fin++;
4498 if (fin != limit && *fin == '\"')
4499 fin++;
4500 else
4501 goto fail;
4505 /* We have "filename". Figure out directory this source
4506 file is coming from and put it on the front of the list. */
4508 /* If -I- was specified, don't search current dir, only spec'd ones. */
4509 if (ignore_srcdir) break;
4511 for (fp = &instack[indepth]; fp >= instack; fp--)
4513 int n;
4514 char *nam;
4516 if ((nam = fp->nominal_fname) != NULL) {
4517 /* Found a named file. Figure out dir of the file,
4518 and put it in front of the search list. */
4519 dsp = ((struct file_name_list *)
4520 alloca (sizeof (struct file_name_list)
4521 + fp->nominal_fname_len));
4522 strcpy (dsp->fname, nam);
4523 simplify_filename (dsp->fname);
4524 nam = base_name (dsp->fname);
4525 *nam = 0;
4526 #ifdef VMS
4527 /* for hack_vms_include_specification(), a local
4528 dir specification must start with "./" on VMS. */
4529 if (nam == dsp->fname)
4531 *nam++ = '.';
4532 *nam++ = '/';
4533 *nam = 0;
4535 #endif
4536 /* But for efficiency's sake, do not insert the dir
4537 if it matches the search list's first dir. */
4538 dsp->next = search_start;
4539 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4540 search_start = dsp;
4541 n = nam - dsp->fname;
4542 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4543 max_include_len = n + INCLUDE_LEN_FUDGE;
4545 dsp[0].got_name_map = 0;
4546 break;
4549 break;
4552 case '<':
4553 while (fin != limit && *fin != '>')
4554 *fend++ = *fin++;
4555 if (*fin == '>' && fin + 1 == limit) {
4556 angle_brackets = 1;
4557 /* If -I-, start with the first -I dir after the -I-. */
4558 search_start = first_bracket_include;
4559 break;
4561 goto fail;
4563 default:
4564 #ifdef VMS
4566 * Support '#include xyz' like VAX-C to allow for easy use of all the
4567 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4568 * code from case '<' is repeated here) and generates a warning.
4569 * (Note: macro expansion of `xyz' takes precedence.)
4571 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4572 the pre-decrement outside of the macro. */
4573 if (retried && (--fin, ISALPHA(*(U_CHAR *) (fin)))) {
4574 while (fin != limit && (!ISSPACE(*fin)))
4575 *fend++ = *fin++;
4576 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4577 vaxc_include = 1;
4578 if (fin == limit) {
4579 angle_brackets = 1;
4580 /* If -I-, start with the first -I dir after the -I-. */
4581 search_start = first_bracket_include;
4582 break;
4585 #endif
4587 fail:
4588 if (! retried) {
4589 /* Expand buffer and then remove any newline markers.
4590 We can't just tell expand_to_temp_buffer to omit the markers,
4591 since it would put extra spaces in include file names. */
4592 FILE_BUF trybuf;
4593 U_CHAR *src;
4594 int errors_before_expansion = errors;
4595 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4596 if (errors != errors_before_expansion) {
4597 free (trybuf.buf);
4598 goto invalid_include_file_name;
4600 src = trybuf.buf;
4601 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4602 limit = buf;
4603 while (src != trybuf.bufp) {
4604 switch ((*limit++ = *src++)) {
4605 case '\n':
4606 limit--;
4607 src++;
4608 break;
4610 case '\'':
4611 case '\"':
4613 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4614 NULL_PTR, NULL_PTR, NULL_PTR);
4615 while (src != src1)
4616 *limit++ = *src++;
4618 break;
4621 *limit = 0;
4622 free (trybuf.buf);
4623 retried = 1;
4624 goto get_filename;
4627 invalid_include_file_name:
4628 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4629 return 0;
4632 /* For #include_next, skip in the search path
4633 past the dir in which the containing file was found. */
4634 if (skip_dirs) {
4635 FILE_BUF *fp;
4636 for (fp = &instack[indepth]; fp >= instack; fp--)
4637 if (fp->fname != NULL) {
4638 /* fp->dir is null if the containing file was specified
4639 with an absolute file name. In that case, don't skip anything. */
4640 if (fp->dir)
4641 search_start = fp->dir->next;
4642 break;
4646 *fend = 0;
4647 flen = simplify_filename (fbeg);
4649 if (flen == 0)
4651 error ("empty file name in `#%s'", keyword->name);
4652 return 0;
4655 /* Allocate this permanently, because it gets stored in the definitions
4656 of macros. */
4657 fname = xmalloc (max_include_len + flen + 1);
4658 /* + 1 above for terminating null. */
4660 system_include_depth += angle_brackets;
4662 /* If specified file name is absolute, just open it. */
4664 if (absolute_filename (fbeg)) {
4665 strcpy (fname, fbeg);
4666 f = open_include_file (fname, NULL_PTR, importing, &inc);
4667 } else {
4669 struct bypass_dir {
4670 struct bypass_dir *next;
4671 char *fname;
4672 struct file_name_list *searchptr;
4673 } **bypass_slot = 0;
4675 /* Search directory path, trying to open the file.
4676 Copy each filename tried into FNAME. */
4678 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4680 if (searchptr == first_bracket_include) {
4681 /* Go to bypass directory if we know we've seen this file before. */
4682 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4683 struct bypass_dir *p;
4684 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4685 INCLUDE_HASHSIZE)];
4686 for (p = *bypass_slot; p; p = p->next)
4687 if (!strcmp (fbeg, p->fname)) {
4688 searchptr = p->searchptr;
4689 bypass_slot = 0;
4690 break;
4694 #ifdef VMS
4695 /* Change this 1/2 Unix 1/2 VMS file specification into a
4696 full VMS file specification */
4697 if (searchptr->fname[0])
4699 strcpy (fname, searchptr->fname);
4700 if (fname[strlen (fname) - 1] == ':')
4702 char *slashp;
4703 slashp = strchr (fbeg, '/');
4705 /* start at root-dir of logical device if no path given. */
4706 if (slashp == 0)
4707 strcat (fname, "[000000]");
4709 strcat (fname, fbeg);
4711 /* Fix up the filename */
4712 hack_vms_include_specification (fname, vaxc_include);
4714 else
4716 /* This is a normal VMS filespec, so use it unchanged. */
4717 strcpy (fname, fbeg);
4718 /* if it's '#include filename', add the missing .h */
4719 if (vaxc_include && index(fname,'.')==NULL)
4720 strcat (fname, ".h");
4722 #else
4723 strcpy (fname, searchptr->fname);
4724 strcat (fname, fbeg);
4725 #endif /* VMS */
4726 f = open_include_file (fname, searchptr, importing, &inc);
4727 if (f != -1) {
4728 if (bypass_slot && searchptr != first_bracket_include) {
4729 /* This is the first time we found this include file,
4730 and we found it after first_bracket_include.
4731 Record its location so that we can bypass to here next time. */
4732 struct bypass_dir *p
4733 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4734 p->next = *bypass_slot;
4735 p->fname = fname + strlen (searchptr->fname);
4736 p->searchptr = searchptr;
4737 *bypass_slot = p;
4739 break;
4741 #ifdef VMS
4742 /* Our VMS hacks can produce invalid filespecs, so don't worry
4743 about errors other than EACCES. */
4744 if (errno == EACCES)
4745 break;
4746 #else
4747 if (errno != ENOENT && errno != ENOTDIR)
4748 break;
4749 #endif
4754 if (f < 0) {
4756 if (f == -2) {
4757 /* The file was already included. */
4759 /* If generating dependencies and -MG was specified, we assume missing
4760 files are leaf files, living in the same directory as the source file
4761 or other similar place; these missing files may be generated from
4762 other files and may not exist yet (eg: y.tab.h). */
4763 } else if (print_deps_missing_files
4764 && (system_include_depth != 0) < print_deps)
4766 /* If it was requested as a system header file,
4767 then assume it belongs in the first place to look for such. */
4768 if (angle_brackets)
4770 if (search_start) {
4771 char *p = (char *) alloca (strlen (search_start->fname)
4772 + strlen (fbeg) + 1);
4773 strcpy (p, search_start->fname);
4774 strcat (p, fbeg);
4775 deps_output (p, ' ');
4778 else
4780 /* Otherwise, omit the directory, as if the file existed
4781 in the directory with the source. */
4782 deps_output (fbeg, ' ');
4785 /* If -M was specified, and this header file won't be added to the
4786 dependency list, then don't count this as an error, because we can
4787 still produce correct output. Otherwise, we can't produce correct
4788 output, because there may be dependencies we need inside the missing
4789 file, and we don't know what directory this missing file exists in. */
4790 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4791 warning ("No include path in which to find %s", fbeg);
4792 else if (f != -3)
4793 error_from_errno (fbeg);
4794 else
4795 error ("No include path in which to find %s", fbeg);
4797 } else {
4799 /* Actually process the file. */
4801 pcftry = (char *) alloca (strlen (fname) + 30);
4802 pcfbuf = 0;
4803 pcfnum = 0;
4805 if (!no_precomp)
4807 do {
4808 sprintf (pcftry, "%s%d", fname, pcfnum++);
4810 pcf = open (pcftry, O_RDONLY, 0666);
4811 if (pcf != -1)
4813 struct stat s;
4815 if (fstat (pcf, &s) != 0)
4816 pfatal_with_name (pcftry);
4817 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4818 || inc->st.st_dev != s.st_dev)
4820 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4821 /* Don't need it any more. */
4822 close (pcf);
4824 else
4826 /* Don't need it at all. */
4827 close (pcf);
4828 break;
4831 } while (pcf != -1 && !pcfbuf);
4834 /* Actually process the file */
4835 if (pcfbuf) {
4836 pcfname = xmalloc (strlen (pcftry) + 1);
4837 strcpy (pcfname, pcftry);
4838 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) fname, op);
4840 else
4841 finclude (f, inc, op, is_system_include (fname), searchptr);
4844 system_include_depth -= angle_brackets;
4846 return 0;
4849 /* Return nonzero if the given FILENAME is an absolute pathname which
4850 designates a file within one of the known "system" include file
4851 directories. We assume here that if the given FILENAME looks like
4852 it is the name of a file which resides either directly in a "system"
4853 include file directory, or within any subdirectory thereof, then the
4854 given file must be a "system" include file. This function tells us
4855 if we should suppress pedantic errors/warnings for the given FILENAME.
4857 The value is 2 if the file is a C-language system header file
4858 for which C++ should (on most systems) assume `extern "C"'. */
4860 static int
4861 is_system_include (filename)
4862 register char *filename;
4864 struct file_name_list *searchptr;
4866 for (searchptr = first_system_include; searchptr;
4867 searchptr = searchptr->next)
4868 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4869 return searchptr->c_system_include_path + 1;
4870 return 0;
4873 /* Yield the non-directory suffix of a file name. */
4875 static char *
4876 base_name (fname)
4877 char *fname;
4879 char *s = fname;
4880 char *p;
4881 #if defined (__MSDOS__) || defined (_WIN32)
4882 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4883 #endif
4884 #ifdef VMS
4885 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4886 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4887 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4888 if (s != fname)
4889 return s;
4890 #endif
4891 if ((p = rindex (s, '/'))) s = p + 1;
4892 #ifdef DIR_SEPARATOR
4893 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4894 #endif
4895 return s;
4898 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4900 static int
4901 absolute_filename (filename)
4902 char *filename;
4904 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN__))
4905 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4906 #endif
4907 #if defined (__CYGWIN__)
4908 /* At present, any path that begins with a drive spec is absolute. */
4909 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4910 #endif
4911 #ifdef VMS
4912 if (index (filename, ':') != 0) return 1;
4913 #endif
4914 if (filename[0] == '/') return 1;
4915 #ifdef DIR_SEPARATOR
4916 if (filename[0] == DIR_SEPARATOR) return 1;
4917 #endif
4918 return 0;
4921 /* Remove unnecessary characters from FILENAME in place,
4922 to avoid unnecessary filename aliasing.
4923 Return the length of the resulting string.
4925 Do only the simplifications allowed by Posix.
4926 It is OK to miss simplifications on non-Posix hosts,
4927 since this merely leads to suboptimal results. */
4929 static size_t
4930 simplify_filename (filename)
4931 char *filename;
4933 register char *from = filename;
4934 register char *to = filename;
4935 char *to0;
4937 /* Remove redundant initial /s. */
4938 if (*from == '/') {
4939 *to++ = '/';
4940 if (*++from == '/') {
4941 if (*++from == '/') {
4942 /* 3 or more initial /s are equivalent to 1 /. */
4943 while (*++from == '/')
4944 continue;
4945 } else {
4946 /* On some hosts // differs from /; Posix allows this. */
4947 static int slashslash_vs_slash;
4948 if (slashslash_vs_slash == 0) {
4949 struct stat s1, s2;
4950 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4951 && INO_T_EQ (s1.st_ino, s2.st_ino)
4952 && s1.st_dev == s2.st_dev)
4953 ? 1 : -1);
4955 if (slashslash_vs_slash < 0)
4956 *to++ = '/';
4960 to0 = to;
4962 for (;;) {
4963 #ifndef VMS
4964 if (from[0] == '.' && from[1] == '/')
4965 from += 2;
4966 else
4967 #endif
4969 /* Copy this component and trailing /, if any. */
4970 while ((*to++ = *from++) != '/') {
4971 if (!to[-1]) {
4972 /* Trim . component at end of nonempty name. */
4973 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4975 /* Trim unnecessary trailing /s. */
4976 while (to0 < --to && to[-1] == '/')
4977 continue;
4979 *to = 0;
4980 return to - filename;
4985 /* Skip /s after a /. */
4986 while (*from == '/')
4987 from++;
4991 /* The file_name_map structure holds a mapping of file names for a
4992 particular directory. This mapping is read from the file named
4993 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4994 map filenames on a file system with severe filename restrictions,
4995 such as DOS. The format of the file name map file is just a series
4996 of lines with two tokens on each line. The first token is the name
4997 to map, and the second token is the actual name to use. */
4999 struct file_name_map
5001 struct file_name_map *map_next;
5002 char *map_from;
5003 char *map_to;
5006 #define FILE_NAME_MAP_FILE "header.gcc"
5008 /* Read a space delimited string of unlimited length from a stdio
5009 file. */
5011 static char *
5012 read_filename_string (ch, f)
5013 int ch;
5014 FILE *f;
5016 char *alloc, *set;
5017 int len;
5019 len = 20;
5020 set = alloc = xmalloc (len + 1);
5021 if (! is_space[ch])
5023 *set++ = ch;
5024 while ((ch = getc (f)) != EOF && ! is_space[ch])
5026 if (set - alloc == len)
5028 len *= 2;
5029 alloc = xrealloc (alloc, len + 1);
5030 set = alloc + len / 2;
5032 *set++ = ch;
5035 *set = '\0';
5036 ungetc (ch, f);
5037 return alloc;
5040 /* Read the file name map file for DIRNAME.
5041 If DIRNAME is empty, read the map file for the working directory;
5042 otherwise DIRNAME must end in '/'. */
5044 static struct file_name_map *
5045 read_name_map (dirname)
5046 char *dirname;
5048 /* This structure holds a linked list of file name maps, one per
5049 directory. */
5050 struct file_name_map_list
5052 struct file_name_map_list *map_list_next;
5053 char *map_list_name;
5054 struct file_name_map *map_list_map;
5056 static struct file_name_map_list *map_list;
5057 register struct file_name_map_list *map_list_ptr;
5058 char *name;
5059 FILE *f;
5060 size_t dirlen;
5062 for (map_list_ptr = map_list; map_list_ptr;
5063 map_list_ptr = map_list_ptr->map_list_next)
5064 if (! strcmp (map_list_ptr->map_list_name, dirname))
5065 return map_list_ptr->map_list_map;
5067 map_list_ptr = ((struct file_name_map_list *)
5068 xmalloc (sizeof (struct file_name_map_list)));
5069 map_list_ptr->map_list_name = xstrdup (dirname);
5070 map_list_ptr->map_list_map = NULL;
5072 dirlen = strlen (dirname);
5073 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
5074 strcpy (name, dirname);
5075 strcat (name, FILE_NAME_MAP_FILE);
5076 f = fopen (name, "r");
5077 if (!f)
5078 map_list_ptr->map_list_map = NULL;
5079 else
5081 int ch;
5083 while ((ch = getc (f)) != EOF)
5085 char *from, *to;
5086 struct file_name_map *ptr;
5087 size_t tolen;
5089 if (is_space[ch])
5090 continue;
5091 from = read_filename_string (ch, f);
5092 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5094 to = read_filename_string (ch, f);
5096 simplify_filename (from);
5097 tolen = simplify_filename (to);
5099 ptr = ((struct file_name_map *)
5100 xmalloc (sizeof (struct file_name_map)));
5101 ptr->map_from = from;
5103 /* Make the real filename absolute. */
5104 if (absolute_filename (to))
5105 ptr->map_to = to;
5106 else
5108 ptr->map_to = xmalloc (dirlen + tolen + 1);
5109 strcpy (ptr->map_to, dirname);
5110 strcat (ptr->map_to, to);
5111 free (to);
5114 ptr->map_next = map_list_ptr->map_list_map;
5115 map_list_ptr->map_list_map = ptr;
5117 while ((ch = getc (f)) != '\n')
5118 if (ch == EOF)
5119 break;
5121 fclose (f);
5124 map_list_ptr->map_list_next = map_list;
5125 map_list = map_list_ptr;
5127 return map_list_ptr->map_list_map;
5130 /* Try to open include file FILENAME. SEARCHPTR is the directory
5131 being tried from the include file search path.
5132 IMPORTING is "" if we are importing, null otherwise.
5133 Return -2 if found, either a matching name or a matching inode.
5134 Otherwise, open the file and return a file descriptor if successful
5135 or -1 if unsuccessful.
5136 Unless unsuccessful, put a descriptor of the included file into *PINC.
5137 This function maps filenames on file systems based on information read by
5138 read_name_map. */
5140 static int
5141 open_include_file (filename, searchptr, importing, pinc)
5142 char *filename;
5143 struct file_name_list *searchptr;
5144 U_CHAR *importing;
5145 struct include_file **pinc;
5147 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
5148 int fd = -2;
5150 /* Look up FNAME in include_hashtab. */
5151 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
5152 strlen (fname),
5153 INCLUDE_HASHSIZE)];
5154 struct include_file *inc, *head = *phead;
5155 for (inc = head; inc; inc = inc->next)
5156 if (!strcmp (fname, inc->fname))
5157 break;
5159 if (!inc
5160 || ! inc->control_macro
5161 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
5163 fd = open (fname, O_RDONLY, 0);
5165 if (fd < 0)
5167 #ifdef VMS
5168 /* if #include <dir/file> fails, try again with hacked spec. */
5169 if (!hack_vms_include_specification (fname, 0))
5170 return fd;
5171 fd = open (fname, O_RDONLY, 0);
5172 if (fd < 0)
5173 #endif
5174 return fd;
5177 if (!inc) {
5178 /* FNAME was not in include_hashtab; insert a new entry. */
5179 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
5180 inc->next = head;
5181 inc->fname = fname;
5182 inc->control_macro = 0;
5183 inc->deps_output = 0;
5184 if (fstat (fd, &inc->st) != 0)
5185 pfatal_with_name (fname);
5186 *phead = inc;
5188 /* Look for another file with the same inode and device. */
5189 if (lookup_ino_include (inc)
5190 && inc->control_macro
5191 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
5192 close (fd);
5193 fd = -2;
5197 /* For -M, add this file to the dependencies. */
5198 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
5199 inc->deps_output = 1;
5200 deps_output (fname, ' ');
5203 /* Handle -H option. */
5204 if (print_include_names)
5205 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5208 if (importing)
5209 inc->control_macro = importing;
5211 *pinc = inc;
5212 return fd;
5215 /* Return the remapped name of the include file FILENAME.
5216 SEARCHPTR is the directory being tried from the include file path. */
5218 static char *
5219 remap_include_file (filename, searchptr)
5220 char *filename;
5221 struct file_name_list *searchptr;
5223 register struct file_name_map *map;
5224 register char *from;
5226 if (searchptr)
5228 if (! searchptr->got_name_map)
5230 searchptr->name_map = read_name_map (searchptr->fname);
5231 searchptr->got_name_map = 1;
5234 /* Check the mapping for the directory we are using. */
5235 from = filename + strlen (searchptr->fname);
5236 for (map = searchptr->name_map; map; map = map->map_next)
5237 if (! strcmp (map->map_from, from))
5238 return map->map_to;
5241 from = base_name (filename);
5243 if (from != filename || !searchptr)
5245 /* Try to find a mapping file for the particular directory we are
5246 looking in. Thus #include <sys/types.h> will look up sys/types.h
5247 in /usr/include/header.gcc and look up types.h in
5248 /usr/include/sys/header.gcc. */
5250 char *dir = (char *) alloca (from - filename + 1);
5251 bcopy (filename, dir, from - filename);
5252 dir[from - filename] = '\0';
5254 for (map = read_name_map (dir); map; map = map->map_next)
5255 if (! strcmp (map->map_from, from))
5256 return map->map_to;
5259 return filename;
5262 /* Insert INC into the include file table, hashed by device and inode number.
5263 If a file with different name but same dev+ino was already in the table,
5264 return 1 and set INC's control macro to the already-known macro. */
5266 static int
5267 lookup_ino_include (inc)
5268 struct include_file *inc;
5270 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5271 % INCLUDE_HASHSIZE);
5272 struct include_file *i = include_ino_hashtab[hash];
5273 inc->next_ino = i;
5274 include_ino_hashtab[hash] = inc;
5276 for (; i; i = i->next_ino)
5277 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5278 && inc->st.st_dev == i->st.st_dev) {
5279 inc->control_macro = i->control_macro;
5280 return 1;
5283 return 0;
5286 /* Process file descriptor F, which corresponds to include file INC,
5287 with output to OP.
5288 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5289 "system" include directories (as decided by the `is_system_include'
5290 function above).
5291 DIRPTR is the link in the dir path through which this file was found,
5292 or 0 if the file name was absolute. */
5294 static void
5295 finclude (f, inc, op, system_header_p, dirptr)
5296 int f;
5297 struct include_file *inc;
5298 FILE_BUF *op;
5299 int system_header_p;
5300 struct file_name_list *dirptr;
5302 char *fname = inc->fname;
5303 int i;
5304 FILE_BUF *fp; /* For input stack frame */
5305 int missing_newline = 0;
5307 CHECK_DEPTH (return;);
5309 fp = &instack[indepth + 1];
5310 bzero ((char *) fp, sizeof (FILE_BUF));
5311 fp->nominal_fname = fp->fname = fname;
5312 fp->nominal_fname_len = strlen (fname);
5313 fp->inc = inc;
5314 fp->length = 0;
5315 fp->lineno = 1;
5316 fp->if_stack = if_stack;
5317 fp->system_header_p = system_header_p;
5318 fp->dir = dirptr;
5320 if (S_ISREG (inc->st.st_mode)) {
5321 size_t s = (size_t) inc->st.st_size;
5322 if (s != inc->st.st_size || s + 2 < s)
5323 memory_full ();
5324 fp->buf = (U_CHAR *) xmalloc (s + 2);
5325 fp->bufp = fp->buf;
5327 /* Read the file contents, knowing that s is an upper bound
5328 on the number of bytes we can read. */
5329 fp->length = safe_read (f, (char *) fp->buf, s);
5330 if (fp->length < 0) goto nope;
5332 else if (S_ISDIR (inc->st.st_mode)) {
5333 error ("directory `%s' specified in #include", fname);
5334 close (f);
5335 return;
5336 } else {
5337 /* Cannot count its file size before reading.
5338 First read the entire file into heap and
5339 copy them into buffer on stack. */
5341 int bsize = 2000;
5342 int st_size = 0;
5344 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5346 for (;;) {
5347 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5348 if (i < 0)
5349 goto nope; /* error! */
5350 st_size += i;
5351 if (st_size != bsize)
5352 break; /* End of file */
5353 bsize *= 2;
5354 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5356 fp->bufp = fp->buf;
5357 fp->length = st_size;
5360 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5361 /* Backslash-newline at end is not good enough. */
5362 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5363 fp->buf[fp->length++] = '\n';
5364 missing_newline = 1;
5366 fp->buf[fp->length] = '\0';
5368 /* Close descriptor now, so nesting does not use lots of descriptors. */
5369 close (f);
5371 /* Must do this before calling trigraph_pcp, so that the correct file name
5372 will be printed in warning messages. */
5374 indepth++;
5375 input_file_stack_tick++;
5377 if (!no_trigraphs)
5378 trigraph_pcp (fp);
5380 output_line_directive (fp, op, 0, enter_file);
5381 rescan (op, 0);
5383 if (missing_newline)
5384 fp->lineno--;
5386 if (pedantic && missing_newline)
5387 pedwarn ("file does not end in newline");
5389 indepth--;
5390 input_file_stack_tick++;
5391 output_line_directive (&instack[indepth], op, 0, leave_file);
5392 free (fp->buf);
5393 return;
5395 nope:
5397 perror_with_name (fname);
5398 close (f);
5399 free (fp->buf);
5402 /* Record that inclusion of the include file INC
5403 should be controlled by the macro named MACRO_NAME.
5404 This means that trying to include the file again
5405 will do something if that macro is defined. */
5407 static void
5408 record_control_macro (inc, macro_name)
5409 struct include_file *inc;
5410 U_CHAR *macro_name;
5412 if (!inc->control_macro || inc->control_macro[0])
5413 inc->control_macro = macro_name;
5416 /* Load the specified precompiled header into core, and verify its
5417 preconditions. PCF indicates the file descriptor to read, which must
5418 be a regular file. *ST is its file status.
5419 FNAME indicates the file name of the original header.
5420 *LIMIT will be set to an address one past the end of the file.
5421 If the preconditions of the file are not satisfied, the buffer is
5422 freed and we return 0. If the preconditions are satisfied, return
5423 the address of the buffer following the preconditions. The buffer, in
5424 this case, should never be freed because various pieces of it will
5425 be referred to until all precompiled strings are output at the end of
5426 the run. */
5428 static char *
5429 check_precompiled (pcf, st, fname, limit)
5430 int pcf;
5431 struct stat *st;
5432 char *fname ATTRIBUTE_UNUSED;
5433 char **limit;
5435 int length = 0;
5436 char *buf;
5437 char *cp;
5439 if (pcp_outfile)
5440 return 0;
5442 if (S_ISREG (st->st_mode))
5444 size_t s = (size_t) st->st_size;
5445 if (s != st->st_size || s + 2 < s)
5446 memory_full ();
5447 buf = xmalloc (s + 2);
5448 length = safe_read (pcf, buf, s);
5449 if (length < 0)
5450 goto nope;
5452 else
5453 abort ();
5455 if (length > 0 && buf[length-1] != '\n')
5456 buf[length++] = '\n';
5457 buf[length] = '\0';
5459 *limit = buf + length;
5461 /* File is in core. Check the preconditions. */
5462 if (!check_preconditions (buf))
5463 goto nope;
5464 for (cp = buf; *cp; cp++)
5466 #ifdef DEBUG_PCP
5467 fprintf (stderr, "Using preinclude %s\n", fname);
5468 #endif
5469 return cp + 1;
5471 nope:
5472 #ifdef DEBUG_PCP
5473 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5474 #endif
5475 free (buf);
5476 return 0;
5479 /* PREC (null terminated) points to the preconditions of a
5480 precompiled header. These are a series of #define and #undef
5481 lines which must match the current contents of the hash
5482 table. */
5484 static int
5485 check_preconditions (prec)
5486 char *prec;
5488 MACRODEF mdef;
5489 char *lineend;
5491 while (*prec) {
5492 lineend = index (prec, '\n');
5494 if (*prec++ != '#') {
5495 error ("Bad format encountered while reading precompiled file");
5496 return 0;
5498 if (!strncmp (prec, "define", 6)) {
5499 HASHNODE *hp;
5501 prec += 6;
5502 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5504 if (mdef.defn == 0)
5505 abort ();
5507 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5508 || (hp->type != T_MACRO && hp->type != T_CONST)
5509 || (hp->type == T_MACRO
5510 && !compare_defs (mdef.defn, hp->value.defn)
5511 && (mdef.defn->length != 2
5512 || mdef.defn->expansion[0] != '\n'
5513 || mdef.defn->expansion[1] != ' ')))
5514 return 0;
5515 } else if (!strncmp (prec, "undef", 5)) {
5516 char *name;
5517 int len;
5519 prec += 5;
5520 while (is_hor_space[(U_CHAR) *prec])
5521 prec++;
5522 name = prec;
5523 while (is_idchar[(U_CHAR) *prec])
5524 prec++;
5525 len = prec - name;
5527 if (lookup ((U_CHAR *) name, len, -1))
5528 return 0;
5529 } else {
5530 error ("Bad format encountered while reading precompiled file");
5531 return 0;
5533 prec = lineend + 1;
5535 /* They all passed successfully */
5536 return 1;
5539 /* Process the main body of a precompiled file. BUF points to the
5540 string section of the file, following the preconditions. LIMIT is one
5541 character past the end. NAME is the name of the file being read
5542 in. OP is the main output buffer. */
5544 static void
5545 pcfinclude (buf, name, op)
5546 U_CHAR *buf, *name;
5547 FILE_BUF *op;
5549 FILE_BUF tmpbuf;
5550 int nstrings;
5551 U_CHAR *cp = buf;
5553 /* First in the file comes 4 bytes indicating the number of strings, */
5554 /* in network byte order. (MSB first). */
5555 nstrings = *cp++;
5556 nstrings = (nstrings << 8) | *cp++;
5557 nstrings = (nstrings << 8) | *cp++;
5558 nstrings = (nstrings << 8) | *cp++;
5560 /* Looping over each string... */
5561 while (nstrings--) {
5562 U_CHAR *string_start;
5563 U_CHAR *endofthiskey;
5564 STRINGDEF *str;
5565 int nkeys;
5567 /* Each string starts with a STRINGDEF structure (str), followed */
5568 /* by the text of the string (string_start) */
5570 /* First skip to a longword boundary */
5571 /* ??? Why a 4-byte boundary? On all machines? */
5572 /* NOTE: This works correctly even if size_t
5573 is narrower than a pointer.
5574 Do not try risky measures here to get another type to use!
5575 Do not include stddef.h--it will fail! */
5576 if ((size_t) cp & 3)
5577 cp += 4 - ((size_t) cp & 3);
5579 /* Now get the string. */
5580 str = (STRINGDEF *) (GENERIC_PTR) cp;
5581 string_start = cp += sizeof (STRINGDEF);
5583 for (; *cp; cp++) /* skip the string */
5586 /* We need to macro expand the string here to ensure that the
5587 proper definition environment is in place. If it were only
5588 expanded when we find out it is needed, macros necessary for
5589 its proper expansion might have had their definitions changed. */
5590 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5591 /* Lineno is already set in the precompiled file */
5592 str->contents = tmpbuf.buf;
5593 str->len = tmpbuf.length;
5594 str->writeflag = 0;
5595 str->filename = name;
5596 str->output_mark = outbuf.bufp - outbuf.buf;
5598 str->chain = 0;
5599 *stringlist_tailp = str;
5600 stringlist_tailp = &str->chain;
5602 /* Next comes a fourbyte number indicating the number of keys
5603 for this string. */
5604 nkeys = *cp++;
5605 nkeys = (nkeys << 8) | *cp++;
5606 nkeys = (nkeys << 8) | *cp++;
5607 nkeys = (nkeys << 8) | *cp++;
5609 /* If this number is -1, then the string is mandatory. */
5610 if (nkeys == -1)
5611 str->writeflag = 1;
5612 else
5613 /* Otherwise, for each key, */
5614 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5615 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5616 HASHNODE *hp;
5618 /* It starts with a KEYDEF structure */
5619 cp += sizeof (KEYDEF);
5621 /* Find the end of the key. At the end of this for loop we
5622 advance CP to the start of the next key using this variable. */
5623 endofthiskey = cp + strlen ((char *) cp);
5624 kp->str = str;
5626 /* Expand the key, and enter it into the hash table. */
5627 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5628 tmpbuf.bufp = tmpbuf.buf;
5630 while (is_hor_space[*tmpbuf.bufp])
5631 tmpbuf.bufp++;
5632 if (!is_idstart[*tmpbuf.bufp]
5633 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5634 str->writeflag = 1;
5635 continue;
5638 hp = lookup (tmpbuf.bufp, -1, -1);
5639 if (hp == NULL) {
5640 kp->chain = 0;
5641 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5643 else if (hp->type == T_PCSTRING) {
5644 kp->chain = hp->value.keydef;
5645 hp->value.keydef = kp;
5647 else
5648 str->writeflag = 1;
5651 /* This output_line_directive serves to switch us back to the current
5652 input file in case some of these strings get output (which will
5653 result in line directives for the header file being output). */
5654 output_line_directive (&instack[indepth], op, 0, enter_file);
5657 /* Called from rescan when it hits a key for strings. Mark them all
5658 used and clean up. */
5660 static void
5661 pcstring_used (hp)
5662 HASHNODE *hp;
5664 KEYDEF *kp;
5666 for (kp = hp->value.keydef; kp; kp = kp->chain)
5667 kp->str->writeflag = 1;
5668 delete_macro (hp);
5671 /* Write the output, interspersing precompiled strings in their
5672 appropriate places. */
5674 static void
5675 write_output ()
5677 STRINGDEF *next_string;
5678 U_CHAR *cur_buf_loc;
5679 int line_directive_len = 80;
5680 char *line_directive = xmalloc (line_directive_len);
5681 int len;
5683 /* In each run through the loop, either cur_buf_loc ==
5684 next_string_loc, in which case we print a series of strings, or
5685 it is less than next_string_loc, in which case we write some of
5686 the buffer. */
5687 cur_buf_loc = outbuf.buf;
5688 next_string = stringlist;
5690 while (cur_buf_loc < outbuf.bufp || next_string) {
5691 if (next_string
5692 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5693 if (next_string->writeflag) {
5694 len = 4 * strlen ((char *) next_string->filename) + 32;
5695 while (len > line_directive_len)
5696 line_directive = xrealloc (line_directive,
5697 line_directive_len *= 2);
5698 sprintf (line_directive, "\n# %d ", next_string->lineno);
5699 strcpy (quote_string (line_directive + strlen (line_directive),
5700 (char *) next_string->filename,
5701 strlen ((char *) next_string->filename)),
5702 "\n");
5703 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5704 safe_write (fileno (stdout),
5705 (char *) next_string->contents, next_string->len);
5707 next_string = next_string->chain;
5709 else {
5710 len = (next_string
5711 ? (next_string->output_mark
5712 - (cur_buf_loc - outbuf.buf))
5713 : outbuf.bufp - cur_buf_loc);
5715 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5716 cur_buf_loc += len;
5719 free (line_directive);
5722 /* Pass a directive through to the output file.
5723 BUF points to the contents of the directive, as a contiguous string.
5724 LIMIT points to the first character past the end of the directive.
5725 KEYWORD is the keyword-table entry for the directive. */
5727 static void
5728 pass_thru_directive (buf, limit, op, keyword)
5729 U_CHAR *buf, *limit;
5730 FILE_BUF *op;
5731 struct directive *keyword;
5733 register unsigned keyword_length = keyword->length;
5735 check_expand (op, 1 + keyword_length + (limit - buf));
5736 *op->bufp++ = '#';
5737 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5738 op->bufp += keyword_length;
5739 if (limit != buf && buf[0] != ' ')
5740 *op->bufp++ = ' ';
5741 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5742 op->bufp += (limit - buf);
5743 #if 0
5744 *op->bufp++ = '\n';
5745 /* Count the line we have just made in the output,
5746 to get in sync properly. */
5747 op->lineno++;
5748 #endif
5751 /* The arglist structure is built by do_define to tell
5752 collect_definition where the argument names begin. That
5753 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5754 would contain pointers to the strings x, y, and z.
5755 Collect_definition would then build a DEFINITION node,
5756 with reflist nodes pointing to the places x, y, and z had
5757 appeared. So the arglist is just convenience data passed
5758 between these two routines. It is not kept around after
5759 the current #define has been processed and entered into the
5760 hash table. */
5762 struct arglist {
5763 struct arglist *next;
5764 U_CHAR *name;
5765 int length;
5766 int argno;
5767 char rest_args;
5770 /* Create a DEFINITION node from a #define directive. Arguments are
5771 as for do_define. */
5773 static MACRODEF
5774 create_definition (buf, limit, op)
5775 U_CHAR *buf, *limit;
5776 FILE_BUF *op;
5778 U_CHAR *bp; /* temp ptr into input buffer */
5779 U_CHAR *symname; /* remember where symbol name starts */
5780 int sym_length; /* and how long it is */
5781 int line = instack[indepth].lineno;
5782 char *file = instack[indepth].nominal_fname;
5783 size_t file_len = instack[indepth].nominal_fname_len;
5784 int rest_args = 0;
5786 DEFINITION *defn;
5787 int arglengths = 0; /* Accumulate lengths of arg names
5788 plus number of args. */
5789 MACRODEF mdef;
5791 bp = buf;
5793 while (is_hor_space[*bp])
5794 bp++;
5796 symname = bp; /* remember where it starts */
5797 sym_length = check_macro_name (bp, "macro");
5798 bp += sym_length;
5800 /* Lossage will occur if identifiers or control keywords are broken
5801 across lines using backslash. This is not the right place to take
5802 care of that. */
5804 if (*bp == '(') {
5805 struct arglist *arg_ptrs = NULL;
5806 int argno = 0;
5808 bp++; /* skip '(' */
5809 SKIP_WHITE_SPACE (bp);
5811 /* Loop over macro argument names. */
5812 while (*bp != ')') {
5813 struct arglist *temp;
5815 temp = (struct arglist *) alloca (sizeof (struct arglist));
5816 temp->name = bp;
5817 temp->next = arg_ptrs;
5818 temp->argno = argno++;
5819 temp->rest_args = 0;
5820 arg_ptrs = temp;
5822 if (rest_args)
5823 pedwarn ("another parameter follows `%s'",
5824 rest_extension);
5826 if (!is_idstart[*bp])
5828 if (c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5829 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
5831 /* This is the ISO C 9x way to write macros with variable
5832 number of arguments. */
5833 rest_args = 1;
5834 temp->rest_args = 1;
5836 else
5837 pedwarn ("invalid character in macro parameter name");
5840 /* Find the end of the arg name. */
5841 while (is_idchar[*bp]) {
5842 bp++;
5843 /* do we have a "special" rest-args extension here? */
5844 if (limit - bp > (long) REST_EXTENSION_LENGTH
5845 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5846 if (pedantic && !instack[indepth].system_header_p)
5847 pedwarn ("ANSI C does not allow macro with variable arguments");
5848 rest_args = 1;
5849 temp->rest_args = 1;
5850 break;
5853 if (bp == temp->name && rest_args == 1)
5855 /* This is the ISO C 9x style. */
5856 temp->name = va_args_name;
5857 temp->length = VA_ARGS_NAME_LENGTH;
5859 else
5860 temp->length = bp - temp->name;
5861 if (rest_args == 1)
5862 bp += REST_EXTENSION_LENGTH;
5863 arglengths += temp->length + 2;
5864 SKIP_WHITE_SPACE (bp);
5865 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5866 error ("badly punctuated parameter list in `#define'");
5867 goto nope;
5869 if (*bp == ',') {
5870 bp++;
5871 SKIP_WHITE_SPACE (bp);
5872 /* A comma at this point can only be followed by an identifier. */
5873 if (!is_idstart[*bp]
5874 && !(c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5875 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)) {
5876 error ("badly punctuated parameter list in `#define'");
5877 goto nope;
5880 if (bp >= limit) {
5881 error ("unterminated parameter list in `#define'");
5882 goto nope;
5885 struct arglist *otemp;
5887 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5888 if (temp->length == otemp->length
5889 && bcmp (temp->name, otemp->name, temp->length) == 0)
5891 error ("duplicate argument name `%.*s' in `#define'",
5892 temp->length, temp->name);
5893 goto nope;
5895 if (rest_args == 0 && temp->length == VA_ARGS_NAME_LENGTH
5896 && bcmp (temp->name, va_args_name, VA_ARGS_NAME_LENGTH) == 0)
5898 error ("\
5899 reserved name `%s' used as argument name in `#define'", va_args_name);
5900 goto nope;
5905 ++bp; /* skip paren */
5906 SKIP_WHITE_SPACE (bp);
5907 /* now everything from bp before limit is the definition. */
5908 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5909 defn->rest_args = rest_args;
5911 /* Now set defn->args.argnames to the result of concatenating
5912 the argument names in reverse order
5913 with comma-space between them. */
5914 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5916 struct arglist *temp;
5917 int i = 0;
5918 for (temp = arg_ptrs; temp; temp = temp->next) {
5919 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5920 i += temp->length;
5921 if (temp->next != 0) {
5922 defn->args.argnames[i++] = ',';
5923 defn->args.argnames[i++] = ' ';
5926 defn->args.argnames[i] = 0;
5928 } else {
5929 /* Simple expansion or empty definition. */
5931 if (bp < limit)
5933 if (is_hor_space[*bp]) {
5934 bp++;
5935 SKIP_WHITE_SPACE (bp);
5936 } else if (sym_length) {
5937 switch (*bp) {
5938 case '!': case '"': case '#': case '%': case '&': case '\'':
5939 case ')': case '*': case '+': case ',': case '-': case '.':
5940 case '/': case ':': case ';': case '<': case '=': case '>':
5941 case '?': case '[': case '\\': case ']': case '^': case '{':
5942 case '|': case '}': case '~':
5943 warning ("missing white space after `#define %.*s'",
5944 sym_length, symname);
5945 break;
5947 default:
5948 pedwarn ("missing white space after `#define %.*s'",
5949 sym_length, symname);
5950 break;
5954 /* Now everything from bp before limit is the definition. */
5955 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5956 defn->args.argnames = (U_CHAR *) "";
5959 defn->line = line;
5960 defn->file = file;
5961 defn->file_len = file_len;
5963 /* OP is null if this is a predefinition */
5964 defn->predefined = !op;
5965 mdef.defn = defn;
5966 mdef.symnam = symname;
5967 mdef.symlen = sym_length;
5969 return mdef;
5971 nope:
5972 mdef.defn = 0;
5973 return mdef;
5976 /* Process a #define directive.
5977 BUF points to the contents of the #define directive, as a contiguous string.
5978 LIMIT points to the first character past the end of the definition.
5979 KEYWORD is the keyword-table entry for #define. */
5981 static int
5982 do_define (buf, limit, op, keyword)
5983 U_CHAR *buf, *limit;
5984 FILE_BUF *op;
5985 struct directive *keyword;
5987 int hashcode;
5988 MACRODEF mdef;
5990 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5991 if (pcp_outfile && op)
5992 pass_thru_directive (buf, limit, op, keyword);
5994 mdef = create_definition (buf, limit, op);
5995 if (mdef.defn == 0)
5996 goto nope;
5998 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
6001 HASHNODE *hp;
6002 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
6003 int ok = 0;
6004 /* Redefining a precompiled key is ok. */
6005 if (hp->type == T_PCSTRING)
6006 ok = 1;
6007 /* Redefining a macro is ok if the definitions are the same. */
6008 else if (hp->type == T_MACRO)
6009 ok = ! compare_defs (mdef.defn, hp->value.defn);
6010 /* Redefining a constant is ok with -D. */
6011 else if (hp->type == T_CONST)
6012 ok = ! done_initializing;
6013 /* Print the warning if it's not ok. */
6014 if (!ok) {
6015 /* If we are passing through #define and #undef directives, do
6016 that for this re-definition now. */
6017 if (debug_output && op)
6018 pass_thru_directive (buf, limit, op, keyword);
6020 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
6021 if (hp->type == T_MACRO)
6022 pedwarn_with_file_and_line (hp->value.defn->file,
6023 hp->value.defn->file_len,
6024 hp->value.defn->line,
6025 "this is the location of the previous definition");
6027 /* Replace the old definition. */
6028 hp->type = T_MACRO;
6029 hp->value.defn = mdef.defn;
6030 } else {
6031 /* If we are passing through #define and #undef directives, do
6032 that for this new definition now. */
6033 if (debug_output && op)
6034 pass_thru_directive (buf, limit, op, keyword);
6035 install (mdef.symnam, mdef.symlen, T_MACRO,
6036 (char *) mdef.defn, hashcode);
6040 return 0;
6042 nope:
6044 return 1;
6047 /* Check a purported macro name SYMNAME, and yield its length.
6048 USAGE is the kind of name this is intended for. */
6050 static int
6051 check_macro_name (symname, usage)
6052 U_CHAR *symname;
6053 char *usage;
6055 U_CHAR *p;
6056 int sym_length;
6058 for (p = symname; is_idchar[*p]; p++)
6060 sym_length = p - symname;
6061 if (sym_length == 0
6062 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
6063 error ("invalid %s name", usage);
6064 else if (!is_idstart[*symname]
6065 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
6066 error ("invalid %s name `%.*s'", usage, sym_length, symname);
6067 return sym_length;
6070 /* Return zero if two DEFINITIONs are isomorphic. */
6072 static int
6073 compare_defs (d1, d2)
6074 DEFINITION *d1, *d2;
6076 register struct reflist *a1, *a2;
6077 register U_CHAR *p1 = d1->expansion;
6078 register U_CHAR *p2 = d2->expansion;
6079 int first = 1;
6081 if (d1->nargs != d2->nargs)
6082 return 1;
6083 if (pedantic
6084 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
6085 return 1;
6086 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
6087 a1 = a1->next, a2 = a2->next) {
6088 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
6089 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
6090 || a1->argno != a2->argno
6091 || a1->stringify != a2->stringify
6092 || a1->raw_before != a2->raw_before
6093 || a1->raw_after != a2->raw_after)
6094 return 1;
6095 first = 0;
6096 p1 += a1->nchars;
6097 p2 += a2->nchars;
6099 if (a1 != a2)
6100 return 1;
6101 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
6102 p2, d2->length - (p2 - d2->expansion), 1))
6103 return 1;
6104 return 0;
6107 /* Return 1 if two parts of two macro definitions are effectively different.
6108 One of the parts starts at BEG1 and has LEN1 chars;
6109 the other has LEN2 chars at BEG2.
6110 Any sequence of whitespace matches any other sequence of whitespace.
6111 FIRST means these parts are the first of a macro definition;
6112 so ignore leading whitespace entirely.
6113 LAST means these parts are the last of a macro definition;
6114 so ignore trailing whitespace entirely. */
6116 static int
6117 comp_def_part (first, beg1, len1, beg2, len2, last)
6118 int first;
6119 U_CHAR *beg1, *beg2;
6120 int len1, len2;
6121 int last;
6123 register U_CHAR *end1 = beg1 + len1;
6124 register U_CHAR *end2 = beg2 + len2;
6125 if (first) {
6126 while (beg1 != end1 && is_space[*beg1]) beg1++;
6127 while (beg2 != end2 && is_space[*beg2]) beg2++;
6129 if (last) {
6130 while (beg1 != end1 && is_space[end1[-1]]) end1--;
6131 while (beg2 != end2 && is_space[end2[-1]]) end2--;
6133 while (beg1 != end1 && beg2 != end2) {
6134 if (is_space[*beg1] && is_space[*beg2]) {
6135 while (beg1 != end1 && is_space[*beg1]) beg1++;
6136 while (beg2 != end2 && is_space[*beg2]) beg2++;
6137 } else if (*beg1 == *beg2) {
6138 beg1++; beg2++;
6139 } else break;
6141 return (beg1 != end1) || (beg2 != end2);
6144 /* Read a replacement list for a macro with parameters.
6145 Build the DEFINITION structure.
6146 Reads characters of text starting at BUF until END.
6147 ARGLIST specifies the formal parameters to look for
6148 in the text of the definition; NARGS is the number of args
6149 in that list, or -1 for a macro name that wants no argument list.
6150 MACRONAME is the macro name itself (so we can avoid recursive expansion)
6151 and NAMELEN is its length in characters.
6153 Note that comments, backslash-newlines, and leading white space
6154 have already been deleted from the argument. */
6156 /* If there is no trailing whitespace, a Newline Space is added at the end
6157 to prevent concatenation that would be contrary to the standard. */
6159 static DEFINITION *
6160 collect_expansion (buf, end, nargs, arglist)
6161 U_CHAR *buf, *end;
6162 int nargs;
6163 struct arglist *arglist;
6165 DEFINITION *defn;
6166 register U_CHAR *p, *limit, *lastp, *exp_p;
6167 struct reflist *endpat = NULL;
6168 /* Pointer to first nonspace after last ## seen. */
6169 U_CHAR *concat = 0;
6170 /* Pointer to first nonspace after last single-# seen. */
6171 U_CHAR *stringify = 0;
6172 /* How those tokens were spelled. */
6173 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
6174 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
6175 int maxsize;
6176 int expected_delimiter = '\0';
6178 /* Scan thru the replacement list, ignoring comments and quoted
6179 strings, picking up on the macro calls. It does a linear search
6180 thru the arg list on every potential symbol. Profiling might say
6181 that something smarter should happen. */
6183 if (end < buf)
6184 abort ();
6186 /* Find the beginning of the trailing whitespace. */
6187 limit = end;
6188 p = buf;
6189 while (p < limit && is_space[limit[-1]]) limit--;
6191 /* Allocate space for the text in the macro definition.
6192 Each input char may or may not need 1 byte,
6193 so this is an upper bound.
6194 The extra 3 are for invented trailing newline-marker and final null. */
6195 maxsize = (sizeof (DEFINITION)
6196 + (limit - p) + 3);
6197 defn = (DEFINITION *) xcalloc (1, maxsize);
6199 defn->nargs = nargs;
6200 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6201 lastp = exp_p;
6203 if (p[0] == '#'
6204 ? p[1] == '#'
6205 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6206 error ("`##' at start of macro definition");
6207 p += p[0] == '#' ? 2 : 4;
6210 /* Process the main body of the definition. */
6211 while (p < limit) {
6212 int skipped_arg = 0;
6213 register U_CHAR c = *p++;
6215 *exp_p++ = c;
6217 if (!traditional) {
6218 switch (c) {
6219 case '\'':
6220 case '\"':
6221 if (expected_delimiter != '\0') {
6222 if (c == expected_delimiter)
6223 expected_delimiter = '\0';
6224 } else
6225 expected_delimiter = c;
6226 break;
6228 case '\\':
6229 if (p < limit && expected_delimiter) {
6230 /* In a string, backslash goes through
6231 and makes next char ordinary. */
6232 *exp_p++ = *p++;
6234 break;
6236 case '%':
6237 if (!expected_delimiter && *p == ':') {
6238 /* %: is not a digraph if preceded by an odd number of '<'s. */
6239 U_CHAR *p0 = p - 1;
6240 while (buf < p0 && p0[-1] == '<')
6241 p0--;
6242 if ((p - p0) & 1) {
6243 /* Treat %:%: as ## and %: as #. */
6244 if (p[1] == '%' && p[2] == ':') {
6245 p += 2;
6246 goto sharp_sharp_token;
6248 if (nargs >= 0) {
6249 p++;
6250 goto sharp_token;
6254 break;
6256 case '#':
6257 /* # is ordinary inside a string. */
6258 if (expected_delimiter)
6259 break;
6260 if (*p == '#') {
6261 sharp_sharp_token:
6262 /* ##: concatenate preceding and following tokens. */
6263 /* Take out the first #, discard preceding whitespace. */
6264 exp_p--;
6265 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6266 --exp_p;
6267 /* Skip the second #. */
6268 p++;
6269 concat_sharp_token_type = c;
6270 if (is_hor_space[*p]) {
6271 concat_sharp_token_type = c + 1;
6272 p++;
6273 SKIP_WHITE_SPACE (p);
6275 concat = p;
6276 if (p == limit)
6277 error ("`##' at end of macro definition");
6278 } else if (nargs >= 0) {
6279 /* Single #: stringify following argument ref.
6280 Don't leave the # in the expansion. */
6281 sharp_token:
6282 exp_p--;
6283 stringify_sharp_token_type = c;
6284 if (is_hor_space[*p]) {
6285 stringify_sharp_token_type = c + 1;
6286 p++;
6287 SKIP_WHITE_SPACE (p);
6289 if (! is_idstart[*p] || nargs == 0
6290 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6291 error ("`#' operator is not followed by a macro argument name");
6292 else
6293 stringify = p;
6295 break;
6297 } else {
6298 /* In -traditional mode, recognize arguments inside strings and
6299 character constants, and ignore special properties of #.
6300 Arguments inside strings are considered "stringified", but no
6301 extra quote marks are supplied. */
6302 switch (c) {
6303 case '\'':
6304 case '\"':
6305 if (expected_delimiter != '\0') {
6306 if (c == expected_delimiter)
6307 expected_delimiter = '\0';
6308 } else
6309 expected_delimiter = c;
6310 break;
6312 case '\\':
6313 /* Backslash quotes delimiters and itself, but not macro args. */
6314 if (expected_delimiter != 0 && p < limit
6315 && (*p == expected_delimiter || *p == '\\')) {
6316 *exp_p++ = *p++;
6317 continue;
6319 break;
6321 case '/':
6322 if (expected_delimiter != '\0') /* No comments inside strings. */
6323 break;
6324 if (*p == '*') {
6325 /* If we find a comment that wasn't removed by handle_directive,
6326 this must be -traditional. So replace the comment with
6327 nothing at all. */
6328 exp_p--;
6329 while (++p < limit) {
6330 if (p[0] == '*' && p[1] == '/') {
6331 p += 2;
6332 break;
6335 #if 0
6336 /* Mark this as a concatenation-point, as if it had been ##. */
6337 concat = p;
6338 #endif
6340 break;
6344 #ifdef MULTIBYTE_CHARS
6345 /* Handle multibyte characters inside string and character literals. */
6346 if (expected_delimiter != '\0')
6348 int length;
6349 --p;
6350 length = local_mblen (p, limit - p);
6351 if (length > 1)
6353 --exp_p;
6354 bcopy (p, exp_p, length);
6355 p += length;
6356 exp_p += length;
6357 continue;
6359 ++p;
6361 #endif
6363 /* Handle the start of a symbol. */
6364 if (is_idchar[c] && nargs > 0) {
6365 U_CHAR *id_beg = p - 1;
6366 int id_len;
6368 --exp_p;
6369 while (p != limit && is_idchar[*p]) p++;
6370 id_len = p - id_beg;
6372 if (is_idstart[c]
6373 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6374 register struct arglist *arg;
6376 for (arg = arglist; arg != NULL; arg = arg->next) {
6377 struct reflist *tpat;
6379 if (arg->name[0] == c
6380 && arg->length == id_len
6381 && bcmp (arg->name, id_beg, id_len) == 0) {
6382 enum sharp_token_type tpat_stringify;
6383 if (expected_delimiter) {
6384 if (warn_stringify) {
6385 if (traditional) {
6386 warning ("macro argument `%.*s' is stringified.",
6387 id_len, arg->name);
6388 } else {
6389 warning ("macro arg `%.*s' would be stringified with -traditional.",
6390 id_len, arg->name);
6393 /* If ANSI, don't actually substitute inside a string. */
6394 if (!traditional)
6395 break;
6396 tpat_stringify = SHARP_TOKEN;
6397 } else {
6398 tpat_stringify
6399 = (stringify == id_beg
6400 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6402 /* make a pat node for this arg and append it to the end of
6403 the pat list */
6404 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6405 tpat->next = NULL;
6406 tpat->raw_before
6407 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6408 tpat->raw_after = NO_SHARP_TOKEN;
6409 tpat->rest_args = arg->rest_args;
6410 tpat->stringify = tpat_stringify;
6412 if (endpat == NULL)
6413 defn->pattern = tpat;
6414 else
6415 endpat->next = tpat;
6416 endpat = tpat;
6418 tpat->argno = arg->argno;
6419 tpat->nchars = exp_p - lastp;
6421 register U_CHAR *p1 = p;
6422 SKIP_WHITE_SPACE (p1);
6423 if (p1[0]=='#'
6424 ? p1[1]=='#'
6425 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6426 tpat->raw_after = p1[0] + (p != p1);
6428 lastp = exp_p; /* place to start copying from next time */
6429 skipped_arg = 1;
6430 break;
6435 /* If this was not a macro arg, copy it into the expansion. */
6436 if (! skipped_arg) {
6437 register U_CHAR *lim1 = p;
6438 p = id_beg;
6439 while (p != lim1)
6440 *exp_p++ = *p++;
6441 if (stringify == id_beg)
6442 error ("`#' operator should be followed by a macro argument name");
6447 if (!traditional && expected_delimiter == 0) {
6448 /* If ANSI, put in a newline-space marker to prevent token pasting.
6449 But not if "inside a string" (which in ANSI mode happens only for
6450 -D option). */
6451 *exp_p++ = '\n';
6452 *exp_p++ = ' ';
6455 *exp_p = '\0';
6457 defn->length = exp_p - defn->expansion;
6459 /* Crash now if we overrun the allocated size. */
6460 if (defn->length + 1 > maxsize)
6461 abort ();
6463 #if 0
6464 /* This isn't worth the time it takes. */
6465 /* give back excess storage */
6466 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6467 #endif
6469 return defn;
6472 static int
6473 do_assert (buf, limit, op, keyword)
6474 U_CHAR *buf, *limit;
6475 FILE_BUF *op ATTRIBUTE_UNUSED;
6476 struct directive *keyword ATTRIBUTE_UNUSED;
6478 U_CHAR *bp; /* temp ptr into input buffer */
6479 U_CHAR *symname; /* remember where symbol name starts */
6480 int sym_length; /* and how long it is */
6481 struct arglist *tokens = NULL;
6483 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6484 pedwarn ("ANSI C does not allow `#assert'");
6486 bp = buf;
6488 while (is_hor_space[*bp])
6489 bp++;
6491 symname = bp; /* remember where it starts */
6492 sym_length = check_macro_name (bp, "assertion");
6493 bp += sym_length;
6494 /* #define doesn't do this, but we should. */
6495 SKIP_WHITE_SPACE (bp);
6497 /* Lossage will occur if identifiers or control tokens are broken
6498 across lines using backslash. This is not the right place to take
6499 care of that. */
6501 if (*bp != '(') {
6502 error ("missing token-sequence in `#assert'");
6503 return 1;
6507 int error_flag = 0;
6509 bp++; /* skip '(' */
6510 SKIP_WHITE_SPACE (bp);
6512 tokens = read_token_list (&bp, limit, &error_flag);
6513 if (error_flag)
6514 return 1;
6515 if (tokens == 0) {
6516 error ("empty token-sequence in `#assert'");
6517 return 1;
6520 ++bp; /* skip paren */
6521 SKIP_WHITE_SPACE (bp);
6524 /* If this name isn't already an assertion name, make it one.
6525 Error if it was already in use in some other way. */
6528 ASSERTION_HASHNODE *hp;
6529 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6530 struct tokenlist_list *value
6531 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6533 hp = assertion_lookup (symname, sym_length, hashcode);
6534 if (hp == NULL) {
6535 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6536 error ("`defined' redefined as assertion");
6537 hp = assertion_install (symname, sym_length, hashcode);
6540 /* Add the spec'd token-sequence to the list of such. */
6541 value->tokens = tokens;
6542 value->next = hp->value;
6543 hp->value = value;
6546 return 0;
6549 static int
6550 do_unassert (buf, limit, op, keyword)
6551 U_CHAR *buf, *limit;
6552 FILE_BUF *op ATTRIBUTE_UNUSED;
6553 struct directive *keyword ATTRIBUTE_UNUSED;
6555 U_CHAR *bp; /* temp ptr into input buffer */
6556 U_CHAR *symname; /* remember where symbol name starts */
6557 int sym_length; /* and how long it is */
6559 struct arglist *tokens = NULL;
6560 int tokens_specified = 0;
6562 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6563 pedwarn ("ANSI C does not allow `#unassert'");
6565 bp = buf;
6567 while (is_hor_space[*bp])
6568 bp++;
6570 symname = bp; /* remember where it starts */
6571 sym_length = check_macro_name (bp, "assertion");
6572 bp += sym_length;
6573 /* #define doesn't do this, but we should. */
6574 SKIP_WHITE_SPACE (bp);
6576 /* Lossage will occur if identifiers or control tokens are broken
6577 across lines using backslash. This is not the right place to take
6578 care of that. */
6580 if (*bp == '(') {
6581 int error_flag = 0;
6583 bp++; /* skip '(' */
6584 SKIP_WHITE_SPACE (bp);
6586 tokens = read_token_list (&bp, limit, &error_flag);
6587 if (error_flag)
6588 return 1;
6589 if (tokens == 0) {
6590 error ("empty token list in `#unassert'");
6591 return 1;
6594 tokens_specified = 1;
6596 ++bp; /* skip paren */
6597 SKIP_WHITE_SPACE (bp);
6601 ASSERTION_HASHNODE *hp;
6602 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6603 struct tokenlist_list *tail, *prev;
6605 hp = assertion_lookup (symname, sym_length, hashcode);
6606 if (hp == NULL)
6607 return 1;
6609 /* If no token list was specified, then eliminate this assertion
6610 entirely. */
6611 if (! tokens_specified) {
6612 struct tokenlist_list *next;
6613 for (tail = hp->value; tail; tail = next) {
6614 next = tail->next;
6615 free_token_list (tail->tokens);
6616 free (tail);
6618 delete_assertion (hp);
6619 } else {
6620 /* If a list of tokens was given, then delete any matching list. */
6622 tail = hp->value;
6623 prev = 0;
6624 while (tail) {
6625 struct tokenlist_list *next = tail->next;
6626 if (compare_token_lists (tail->tokens, tokens)) {
6627 if (prev)
6628 prev->next = next;
6629 else
6630 hp->value = tail->next;
6631 free_token_list (tail->tokens);
6632 free (tail);
6633 } else {
6634 prev = tail;
6636 tail = next;
6641 return 0;
6644 /* Test whether there is an assertion named NAME
6645 and optionally whether it has an asserted token list TOKENS.
6646 NAME is not null terminated; its length is SYM_LENGTH.
6647 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6650 check_assertion (name, sym_length, tokens_specified, tokens)
6651 U_CHAR *name;
6652 int sym_length;
6653 int tokens_specified;
6654 struct arglist *tokens;
6656 ASSERTION_HASHNODE *hp;
6657 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6659 if (pedantic && !instack[indepth].system_header_p)
6660 pedwarn ("ANSI C does not allow testing assertions");
6662 hp = assertion_lookup (name, sym_length, hashcode);
6663 if (hp == NULL)
6664 /* It is not an assertion; just return false. */
6665 return 0;
6667 /* If no token list was specified, then value is 1. */
6668 if (! tokens_specified)
6669 return 1;
6672 struct tokenlist_list *tail;
6674 tail = hp->value;
6676 /* If a list of tokens was given,
6677 then succeed if the assertion records a matching list. */
6679 while (tail) {
6680 if (compare_token_lists (tail->tokens, tokens))
6681 return 1;
6682 tail = tail->next;
6685 /* Fail if the assertion has no matching list. */
6686 return 0;
6690 /* Compare two lists of tokens for equality including order of tokens. */
6692 static int
6693 compare_token_lists (l1, l2)
6694 struct arglist *l1, *l2;
6696 while (l1 && l2) {
6697 if (l1->length != l2->length)
6698 return 0;
6699 if (bcmp (l1->name, l2->name, l1->length))
6700 return 0;
6701 l1 = l1->next;
6702 l2 = l2->next;
6705 /* Succeed if both lists end at the same time. */
6706 return l1 == l2;
6709 /* Read a space-separated list of tokens ending in a close parenthesis.
6710 Return a list of strings, in the order they were written.
6711 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6712 Parse the text starting at *BPP, and update *BPP.
6713 Don't parse beyond LIMIT. */
6715 static struct arglist *
6716 read_token_list (bpp, limit, error_flag)
6717 U_CHAR **bpp;
6718 U_CHAR *limit;
6719 int *error_flag;
6721 struct arglist *token_ptrs = 0;
6722 U_CHAR *bp = *bpp;
6723 int depth = 1;
6725 *error_flag = 0;
6727 /* Loop over the assertion value tokens. */
6728 while (depth > 0) {
6729 struct arglist *temp;
6730 int eofp = 0;
6731 U_CHAR *beg = bp;
6733 /* Find the end of the token. */
6734 if (*bp == '(') {
6735 bp++;
6736 depth++;
6737 } else if (*bp == ')') {
6738 depth--;
6739 if (depth == 0)
6740 break;
6741 bp++;
6742 } else if (*bp == '"' || *bp == '\'')
6743 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6744 else
6745 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6746 && *bp != '"' && *bp != '\'' && bp != limit)
6747 bp++;
6749 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6750 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6751 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6752 temp->name[bp - beg] = 0;
6753 temp->next = token_ptrs;
6754 token_ptrs = temp;
6755 temp->length = bp - beg;
6757 SKIP_WHITE_SPACE (bp);
6759 if (bp >= limit) {
6760 error ("unterminated token sequence in `#assert' or `#unassert'");
6761 *error_flag = -1;
6762 return 0;
6765 *bpp = bp;
6767 /* We accumulated the names in reverse order.
6768 Now reverse them to get the proper order. */
6770 register struct arglist *prev = 0, *this, *next;
6771 for (this = token_ptrs; this; this = next) {
6772 next = this->next;
6773 this->next = prev;
6774 prev = this;
6776 return prev;
6780 static void
6781 free_token_list (tokens)
6782 struct arglist *tokens;
6784 while (tokens) {
6785 struct arglist *next = tokens->next;
6786 free (tokens->name);
6787 free (tokens);
6788 tokens = next;
6792 /* Install a name in the assertion hash table.
6794 If LEN is >= 0, it is the length of the name.
6795 Otherwise, compute the length by scanning the entire name.
6797 If HASH is >= 0, it is the precomputed hash code.
6798 Otherwise, compute the hash code. */
6800 static ASSERTION_HASHNODE *
6801 assertion_install (name, len, hash)
6802 U_CHAR *name;
6803 int len;
6804 int hash;
6806 register ASSERTION_HASHNODE *hp;
6807 register int i, bucket;
6808 register U_CHAR *p, *q;
6810 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6811 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6812 bucket = hash;
6813 hp->bucket_hdr = &assertion_hashtab[bucket];
6814 hp->next = assertion_hashtab[bucket];
6815 assertion_hashtab[bucket] = hp;
6816 hp->prev = NULL;
6817 if (hp->next != NULL)
6818 hp->next->prev = hp;
6819 hp->length = len;
6820 hp->value = 0;
6821 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6822 p = hp->name;
6823 q = name;
6824 for (i = 0; i < len; i++)
6825 *p++ = *q++;
6826 hp->name[len] = 0;
6827 return hp;
6830 /* Find the most recent hash node for name "name" (ending with first
6831 non-identifier char) installed by install
6833 If LEN is >= 0, it is the length of the name.
6834 Otherwise, compute the length by scanning the entire name.
6836 If HASH is >= 0, it is the precomputed hash code.
6837 Otherwise, compute the hash code. */
6839 static ASSERTION_HASHNODE *
6840 assertion_lookup (name, len, hash)
6841 U_CHAR *name;
6842 int len;
6843 int hash;
6845 register ASSERTION_HASHNODE *bucket;
6847 bucket = assertion_hashtab[hash];
6848 while (bucket) {
6849 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6850 return bucket;
6851 bucket = bucket->next;
6853 return NULL;
6856 static void
6857 delete_assertion (hp)
6858 ASSERTION_HASHNODE *hp;
6861 if (hp->prev != NULL)
6862 hp->prev->next = hp->next;
6863 if (hp->next != NULL)
6864 hp->next->prev = hp->prev;
6866 /* Make sure that the bucket chain header that the deleted guy was
6867 on points to the right thing afterwards. */
6868 if (hp == *hp->bucket_hdr)
6869 *hp->bucket_hdr = hp->next;
6871 free (hp);
6875 * interpret #line directive. Remembers previously seen fnames
6876 * in its very own hash table.
6878 #define FNAME_HASHSIZE 37
6880 static int
6881 do_line (buf, limit, op, keyword)
6882 U_CHAR *buf, *limit;
6883 FILE_BUF *op;
6884 struct directive *keyword ATTRIBUTE_UNUSED;
6886 register U_CHAR *bp;
6887 FILE_BUF *ip = &instack[indepth];
6888 FILE_BUF tem;
6889 int new_lineno;
6890 enum file_change_code file_change = same_file;
6892 /* Expand any macros. */
6893 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6895 /* Point to macroexpanded line, which is null-terminated now. */
6896 bp = tem.buf;
6897 SKIP_WHITE_SPACE (bp);
6899 if (!ISDIGIT (*bp)) {
6900 error ("invalid format `#line' directive");
6901 return 0;
6904 /* The Newline at the end of this line remains to be processed.
6905 To put the next line at the specified line number,
6906 we must store a line number now that is one less. */
6907 new_lineno = atoi ((char *) bp) - 1;
6909 /* NEW_LINENO is one less than the actual line number here. */
6910 if (pedantic && new_lineno < 0)
6911 pedwarn ("line number out of range in `#line' directive");
6913 /* skip over the line number. */
6914 while (ISDIGIT (*bp))
6915 bp++;
6917 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6918 if (*bp && !is_space[*bp]) {
6919 error ("invalid format `#line' directive");
6920 return;
6922 #endif
6924 SKIP_WHITE_SPACE (bp);
6926 if (*bp == '\"') {
6927 static HASHNODE *fname_table[FNAME_HASHSIZE];
6928 HASHNODE *hp, **hash_bucket;
6929 U_CHAR *fname, *p;
6930 int fname_length;
6932 fname = ++bp;
6934 /* Turn the file name, which is a character string literal,
6935 into a null-terminated string. Do this in place. */
6936 p = bp;
6937 for (;;)
6938 switch ((*p++ = *bp++)) {
6939 case '\0':
6940 error ("invalid format `#line' directive");
6941 return 0;
6943 case '\\':
6944 if (! ignore_escape_flag)
6946 char *bpc = (char *) bp;
6947 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6948 bp = (U_CHAR *) bpc;
6949 if (c < 0)
6950 p--;
6951 else
6952 p[-1] = c;
6954 break;
6956 case '\"':
6957 *--p = 0;
6958 goto fname_done;
6960 fname_done:
6961 fname_length = p - fname;
6963 SKIP_WHITE_SPACE (bp);
6964 if (*bp) {
6965 if (pedantic)
6966 pedwarn ("garbage at end of `#line' directive");
6967 if (*bp == '1')
6968 file_change = enter_file;
6969 else if (*bp == '2')
6970 file_change = leave_file;
6971 else if (*bp == '3')
6972 ip->system_header_p = 1;
6973 else if (*bp == '4')
6974 ip->system_header_p = 2;
6975 else {
6976 error ("invalid format `#line' directive");
6977 return 0;
6980 bp++;
6981 SKIP_WHITE_SPACE (bp);
6982 if (*bp == '3') {
6983 ip->system_header_p = 1;
6984 bp++;
6985 SKIP_WHITE_SPACE (bp);
6987 if (*bp == '4') {
6988 ip->system_header_p = 2;
6989 bp++;
6990 SKIP_WHITE_SPACE (bp);
6992 if (*bp) {
6993 error ("invalid format `#line' directive");
6994 return 0;
6998 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6999 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
7000 if (hp->length == fname_length &&
7001 bcmp (hp->value.cpval, fname, fname_length) == 0) {
7002 ip->nominal_fname = hp->value.cpval;
7003 ip->nominal_fname_len = fname_length;
7004 break;
7006 if (hp == 0) {
7007 /* Didn't find it; cons up a new one. */
7008 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
7009 hp->next = *hash_bucket;
7010 *hash_bucket = hp;
7012 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
7013 ip->nominal_fname_len = hp->length = fname_length;
7014 bcopy (fname, hp->value.cpval, fname_length + 1);
7016 } else if (*bp) {
7017 error ("invalid format `#line' directive");
7018 return 0;
7021 ip->lineno = new_lineno;
7022 output_line_directive (ip, op, 0, file_change);
7023 check_expand (op, ip->length - (ip->bufp - ip->buf));
7024 return 0;
7027 /* Remove the definition of a symbol from the symbol table.
7028 according to un*x /lib/cpp, it is not an error to undef
7029 something that has no definitions, so it isn't one here either. */
7031 static int
7032 do_undef (buf, limit, op, keyword)
7033 U_CHAR *buf, *limit;
7034 FILE_BUF *op;
7035 struct directive *keyword;
7037 int sym_length;
7038 HASHNODE *hp;
7039 U_CHAR *orig_buf = buf;
7041 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
7042 if (pcp_outfile && op)
7043 pass_thru_directive (buf, limit, op, keyword);
7045 SKIP_WHITE_SPACE (buf);
7046 sym_length = check_macro_name (buf, "macro");
7048 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
7049 /* If we are generating additional info for debugging (with -g) we
7050 need to pass through all effective #undef directives. */
7051 if (debug_output && op)
7052 pass_thru_directive (orig_buf, limit, op, keyword);
7053 if (hp->type != T_MACRO)
7054 warning ("undefining `%s'", hp->name);
7055 delete_macro (hp);
7058 if (pedantic) {
7059 buf += sym_length;
7060 SKIP_WHITE_SPACE (buf);
7061 if (buf != limit)
7062 pedwarn ("garbage after `#undef' directive");
7064 return 0;
7067 /* Report an error detected by the program we are processing.
7068 Use the text of the line in the error message.
7069 (We use error because it prints the filename & line#.) */
7071 static int
7072 do_error (buf, limit, op, keyword)
7073 U_CHAR *buf, *limit;
7074 FILE_BUF *op ATTRIBUTE_UNUSED;
7075 struct directive *keyword ATTRIBUTE_UNUSED;
7077 int length = limit - buf;
7078 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7079 bcopy ((char *) buf, (char *) copy, length);
7080 copy[length] = 0;
7081 SKIP_WHITE_SPACE (copy);
7082 error ("#error %s", copy);
7083 return 0;
7086 /* Report a warning detected by the program we are processing.
7087 Use the text of the line in the warning message, then continue.
7088 (We use error because it prints the filename & line#.) */
7090 static int
7091 do_warning (buf, limit, op, keyword)
7092 U_CHAR *buf, *limit;
7093 FILE_BUF *op ATTRIBUTE_UNUSED;
7094 struct directive *keyword ATTRIBUTE_UNUSED;
7096 int length = limit - buf;
7097 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7098 bcopy ((char *) buf, (char *) copy, length);
7099 copy[length] = 0;
7100 SKIP_WHITE_SPACE (copy);
7102 if (pedantic && !instack[indepth].system_header_p)
7103 pedwarn ("ANSI C does not allow `#warning'");
7105 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
7106 if -pedantic-errors is given, #warning should cause an error. */
7107 pedwarn ("#warning %s", copy);
7108 return 0;
7111 /* Remember the name of the current file being read from so that we can
7112 avoid ever including it again. */
7114 static void
7115 do_once ()
7117 int i;
7119 for (i = indepth; i >= 0; i--)
7120 if (instack[i].inc) {
7121 record_control_macro (instack[i].inc, (U_CHAR *) "");
7122 break;
7126 /* Report program identification. */
7128 static int
7129 do_ident (buf, limit, op, keyword)
7130 U_CHAR *buf, *limit;
7131 FILE_BUF *op;
7132 struct directive *keyword ATTRIBUTE_UNUSED;
7134 FILE_BUF trybuf;
7135 int len;
7137 /* Allow #ident in system headers, since that's not user's fault. */
7138 if (pedantic && !instack[indepth].system_header_p)
7139 pedwarn ("ANSI C does not allow `#ident'");
7141 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
7142 buf = trybuf.buf;
7143 len = trybuf.bufp - buf;
7145 /* Output expanded directive. */
7146 check_expand (op, 7 + len);
7147 bcopy ("#ident ", (char *) op->bufp, 7);
7148 op->bufp += 7;
7149 bcopy ((char *) buf, (char *) op->bufp, len);
7150 op->bufp += len;
7152 free (buf);
7153 return 0;
7156 /* #pragma and its argument line have already been copied to the output file.
7157 Just check for some recognized pragmas that need validation here. */
7159 static int
7160 do_pragma (buf, limit, op, keyword)
7161 U_CHAR *buf, *limit ATTRIBUTE_UNUSED;
7162 FILE_BUF *op ATTRIBUTE_UNUSED;
7163 struct directive *keyword ATTRIBUTE_UNUSED;
7165 SKIP_WHITE_SPACE (buf);
7166 if (!strncmp ((char *) buf, "once", 4)) {
7167 /* Allow #pragma once in system headers, since that's not the user's
7168 fault. */
7169 if (!instack[indepth].system_header_p)
7170 warning ("`#pragma once' is obsolete");
7171 do_once ();
7174 if (!strncmp ((char *) buf, "implementation", 14)) {
7175 /* Be quiet about `#pragma implementation' for a file only if it hasn't
7176 been included yet. */
7178 int h;
7179 U_CHAR *p = buf + 14, *fname;
7180 SKIP_WHITE_SPACE (p);
7181 if (*p != '\"')
7182 return 0;
7184 fname = p + 1;
7185 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
7186 *p = '\0';
7188 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
7189 struct include_file *inc;
7190 for (inc = include_hashtab[h]; inc; inc = inc->next) {
7191 if (!strcmp (base_name (inc->fname), (char *) fname)) {
7192 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
7193 return 0;
7198 return 0;
7201 #if 0
7202 /* This was a fun hack, but #pragma seems to start to be useful.
7203 By failing to recognize it, we pass it through unchanged to cc1. */
7205 /* The behavior of the #pragma directive is implementation defined.
7206 this implementation defines it as follows. */
7208 static int
7209 do_pragma ()
7211 close (0);
7212 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7213 goto nope;
7214 close (1);
7215 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7216 goto nope;
7217 execl ("/usr/games/hack", "#pragma", 0);
7218 execl ("/usr/games/rogue", "#pragma", 0);
7219 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7220 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7221 nope:
7222 fatal ("You are in a maze of twisty compiler features, all different");
7224 #endif
7226 #ifdef SCCS_DIRECTIVE
7228 /* Just ignore #sccs, on systems where we define it at all. */
7230 static int
7231 do_sccs (buf, limit, op, keyword)
7232 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7233 FILE_BUF *op ATTRIBUTE_UNUSED;
7234 struct directive *keyword ATTRIBUTE_UNUSED;
7236 if (pedantic)
7237 pedwarn ("ANSI C does not allow `#sccs'");
7238 return 0;
7241 #endif /* defined (SCCS_DIRECTIVE) */
7243 /* Handle #if directive by
7244 1) inserting special `defined' keyword into the hash table
7245 that gets turned into 0 or 1 by special_symbol (thus,
7246 if the luser has a symbol called `defined' already, it won't
7247 work inside the #if directive)
7248 2) rescan the input into a temporary output buffer
7249 3) pass the output buffer to the yacc parser and collect a value
7250 4) clean up the mess left from steps 1 and 2.
7251 5) call conditional_skip to skip til the next #endif (etc.),
7252 or not, depending on the value from step 3. */
7254 static int
7255 do_if (buf, limit, op, keyword)
7256 U_CHAR *buf, *limit;
7257 FILE_BUF *op;
7258 struct directive *keyword ATTRIBUTE_UNUSED;
7260 HOST_WIDE_INT value;
7261 FILE_BUF *ip = &instack[indepth];
7263 value = eval_if_expression (buf, limit - buf);
7264 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7265 return 0;
7268 /* Handle a #elif directive by not changing if_stack either.
7269 see the comment above do_else. */
7271 static int
7272 do_elif (buf, limit, op, keyword)
7273 U_CHAR *buf, *limit;
7274 FILE_BUF *op;
7275 struct directive *keyword ATTRIBUTE_UNUSED;
7277 HOST_WIDE_INT value;
7278 FILE_BUF *ip = &instack[indepth];
7280 if (if_stack == instack[indepth].if_stack) {
7281 error ("`#elif' not within a conditional");
7282 return 0;
7283 } else {
7284 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7285 error ("`#elif' after `#else'");
7286 fprintf (stderr, " (matches line %d", if_stack->lineno);
7287 if (! (if_stack->fname_len == ip->nominal_fname_len
7288 && !bcmp (if_stack->fname, ip->nominal_fname,
7289 if_stack->fname_len))) {
7290 fprintf (stderr, ", file ");
7291 eprint_string (if_stack->fname, if_stack->fname_len);
7293 fprintf (stderr, ")\n");
7295 if_stack->type = T_ELIF;
7298 if (if_stack->if_succeeded)
7299 skip_if_group (ip, 0, op);
7300 else {
7301 value = eval_if_expression (buf, limit - buf);
7302 if (value == 0)
7303 skip_if_group (ip, 0, op);
7304 else {
7305 ++if_stack->if_succeeded; /* continue processing input */
7306 output_line_directive (ip, op, 1, same_file);
7309 return 0;
7312 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7313 result as a C expression and return the value as an int. */
7315 static HOST_WIDE_INT
7316 eval_if_expression (buf, length)
7317 U_CHAR *buf;
7318 int length;
7320 FILE_BUF temp_obuf;
7321 HASHNODE *save_defined;
7322 HOST_WIDE_INT value;
7324 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7325 NULL_PTR, -1);
7326 pcp_inside_if = 1;
7327 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7328 pcp_inside_if = 0;
7329 delete_macro (save_defined); /* clean up special symbol */
7331 temp_obuf.buf[temp_obuf.length] = '\n';
7332 value = parse_c_expression ((char *) temp_obuf.buf,
7333 warn_undef && !instack[indepth].system_header_p);
7335 free (temp_obuf.buf);
7337 return value;
7340 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7341 or don't skip to the #endif/#else/#elif depending on what directive
7342 is actually being processed. */
7344 static int
7345 do_xifdef (buf, limit, op, keyword)
7346 U_CHAR *buf, *limit;
7347 FILE_BUF *op;
7348 struct directive *keyword;
7350 int skip;
7351 FILE_BUF *ip = &instack[indepth];
7352 U_CHAR *end;
7353 int start_of_file = 0;
7354 U_CHAR *control_macro = 0;
7356 /* Detect a #ifndef at start of file (not counting comments). */
7357 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7358 U_CHAR *p = ip->buf;
7359 while (p != directive_start) {
7360 U_CHAR c = *p++;
7361 if (is_space[c])
7363 /* Make no special provision for backslash-newline here; this is
7364 slower if backslash-newlines are present, but it's correct,
7365 and it's not worth it to tune for the rare backslash-newline. */
7366 else if (c == '/'
7367 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7368 /* Skip this comment. */
7369 int junk = 0;
7370 U_CHAR *save_bufp = ip->bufp;
7371 ip->bufp = p + 1;
7372 p = skip_to_end_of_comment (ip, &junk, 1);
7373 ip->bufp = save_bufp;
7374 } else {
7375 goto fail;
7378 /* If we get here, this conditional is the beginning of the file. */
7379 start_of_file = 1;
7380 fail: ;
7383 /* Discard leading and trailing whitespace. */
7384 SKIP_WHITE_SPACE (buf);
7385 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7387 /* Find the end of the identifier at the beginning. */
7388 for (end = buf; is_idchar[*end]; end++);
7390 if (end == buf) {
7391 skip = (keyword->type == T_IFDEF);
7392 if (! traditional)
7393 pedwarn (end == limit ? "`#%s' with no argument"
7394 : "`#%s' argument starts with punctuation",
7395 keyword->name);
7396 } else {
7397 HASHNODE *hp;
7399 if (! traditional) {
7400 if (ISDIGIT (buf[0]))
7401 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7402 else if (end != limit)
7403 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7406 hp = lookup (buf, end-buf, -1);
7408 if (pcp_outfile) {
7409 /* Output a precondition for this macro. */
7410 if (hp
7411 && (hp->type == T_CONST
7412 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7413 fprintf (pcp_outfile, "#define %s\n", hp->name);
7414 else {
7415 U_CHAR *cp = buf;
7416 fprintf (pcp_outfile, "#undef ");
7417 while (is_idchar[*cp]) /* Ick! */
7418 fputc (*cp++, pcp_outfile);
7419 putc ('\n', pcp_outfile);
7423 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7424 if (start_of_file && !skip) {
7425 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7426 bcopy ((char *) buf, (char *) control_macro, end - buf);
7427 control_macro[end - buf] = 0;
7431 conditional_skip (ip, skip, T_IF, control_macro, op);
7432 return 0;
7435 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7436 If this is a #ifndef starting at the beginning of a file,
7437 CONTROL_MACRO is the macro name tested by the #ifndef.
7438 Otherwise, CONTROL_MACRO is 0. */
7440 static void
7441 conditional_skip (ip, skip, type, control_macro, op)
7442 FILE_BUF *ip;
7443 int skip;
7444 enum node_type type;
7445 U_CHAR *control_macro;
7446 FILE_BUF *op;
7448 IF_STACK_FRAME *temp;
7450 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7451 temp->fname = ip->nominal_fname;
7452 temp->fname_len = ip->nominal_fname_len;
7453 temp->lineno = ip->lineno;
7454 temp->next = if_stack;
7455 temp->control_macro = control_macro;
7456 if_stack = temp;
7458 if_stack->type = type;
7460 if (skip != 0) {
7461 skip_if_group (ip, 0, op);
7462 return;
7463 } else {
7464 ++if_stack->if_succeeded;
7465 output_line_directive (ip, &outbuf, 1, same_file);
7469 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7470 Leaves input ptr at the sharp sign found.
7471 If ANY is nonzero, return at next directive of any sort. */
7473 static void
7474 skip_if_group (ip, any, op)
7475 FILE_BUF *ip;
7476 int any;
7477 FILE_BUF *op;
7479 register U_CHAR *bp = ip->bufp, *cp;
7480 register U_CHAR *endb = ip->buf + ip->length;
7481 struct directive *kt;
7482 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7483 U_CHAR *beg_of_line = bp;
7484 register int ident_length;
7485 U_CHAR *ident, *after_ident;
7486 /* Save info about where the group starts. */
7487 U_CHAR *beg_of_group = bp;
7488 int beg_lineno = ip->lineno;
7489 int skipping_include_directive = 0;
7491 if (output_conditionals && op != 0) {
7492 char *ptr = "#failed\n";
7493 int len = strlen (ptr);
7495 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7497 *op->bufp++ = '\n';
7498 op->lineno++;
7500 check_expand (op, len);
7501 bcopy (ptr, (char *) op->bufp, len);
7502 op->bufp += len;
7503 op->lineno++;
7504 output_line_directive (ip, op, 1, 0);
7507 while (bp < endb) {
7508 switch (*bp++) {
7509 case '/': /* possible comment */
7510 if (*bp == '\\' && bp[1] == '\n')
7511 newline_fix (bp);
7512 if (*bp == '*'
7513 || (cplusplus_comments && *bp == '/')) {
7514 ip->bufp = ++bp;
7515 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7517 break;
7518 case '<':
7519 if (skipping_include_directive) {
7520 while (bp < endb && *bp != '>' && *bp != '\n') {
7521 if (*bp == '\\' && bp[1] == '\n') {
7522 ip->lineno++;
7523 bp++;
7525 bp++;
7528 break;
7529 case '\"':
7530 if (skipping_include_directive) {
7531 while (bp < endb && *bp != '\n') {
7532 if (*bp == '"') {
7533 bp++;
7534 break;
7536 if (*bp == '\\' && bp[1] == '\n') {
7537 ip->lineno++;
7538 bp++;
7540 bp++;
7542 break;
7544 /* Fall through. */
7545 case '\'':
7546 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7547 NULL_PTR, NULL_PTR);
7548 break;
7549 case '\\':
7550 /* Char after backslash loses its special meaning in some cases. */
7551 if (*bp == '\n') {
7552 ++ip->lineno;
7553 bp++;
7554 } else if (traditional && bp < endb)
7555 bp++;
7556 break;
7557 case '\n':
7558 ++ip->lineno;
7559 beg_of_line = bp;
7560 skipping_include_directive = 0;
7561 break;
7562 case '%':
7563 if (beg_of_line == 0 || traditional)
7564 break;
7565 ip->bufp = bp - 1;
7566 while (bp[0] == '\\' && bp[1] == '\n')
7567 bp += 2;
7568 if (*bp == ':')
7569 goto sharp_token;
7570 break;
7571 case '#':
7572 /* # keyword: a # must be first nonblank char on the line */
7573 if (beg_of_line == 0)
7574 break;
7575 ip->bufp = bp - 1;
7576 sharp_token:
7577 /* Scan from start of line, skipping whitespace, comments
7578 and backslash-newlines, and see if we reach this #.
7579 If not, this # is not special. */
7580 bp = beg_of_line;
7581 /* If -traditional, require # to be at beginning of line. */
7582 if (!traditional) {
7583 while (1) {
7584 if (is_hor_space[*bp])
7585 bp++;
7586 else if (*bp == '\\' && bp[1] == '\n')
7587 bp += 2;
7588 else if (*bp == '/' && bp[1] == '*') {
7589 bp += 2;
7590 while (1)
7592 if (*bp == '*')
7594 if (bp[1] == '/')
7596 bp += 2;
7597 break;
7600 else
7602 #ifdef MULTIBYTE_CHARS
7603 int length;
7604 length = local_mblen (bp, endb - bp);
7605 if (length > 1)
7606 bp += (length - 1);
7607 #endif
7609 bp++;
7612 /* There is no point in trying to deal with C++ // comments here,
7613 because if there is one, then this # must be part of the
7614 comment and we would never reach here. */
7615 else break;
7618 if (bp != ip->bufp) {
7619 bp = ip->bufp + 1; /* Reset bp to after the #. */
7620 break;
7623 bp = ip->bufp + 1; /* Point after the '#' */
7624 if (ip->bufp[0] == '%') {
7625 /* Skip past the ':' again. */
7626 while (*bp == '\\') {
7627 ip->lineno++;
7628 bp += 2;
7630 bp++;
7633 /* Skip whitespace and \-newline. */
7634 while (1) {
7635 if (is_hor_space[*bp])
7636 bp++;
7637 else if (*bp == '\\' && bp[1] == '\n')
7638 bp += 2;
7639 else if (*bp == '/') {
7640 if (bp[1] == '\\' && bp[2] == '\n')
7641 newline_fix (bp + 1);
7642 if (bp[1] == '*') {
7643 for (bp += 2; ; bp++) {
7644 if (*bp == '\n')
7645 ip->lineno++;
7646 else if (*bp == '*') {
7647 if (bp[-1] == '/' && warn_comments)
7648 warning ("`/*' within comment");
7649 if (bp[1] == '\\' && bp[2] == '\n')
7650 newline_fix (bp + 1);
7651 if (bp[1] == '/')
7652 break;
7654 else
7656 #ifdef MULTIBYTE_CHARS
7657 int length;
7658 length = local_mblen (bp, endb - bp);
7659 if (length > 1)
7660 bp += (length - 1);
7661 #endif
7664 bp += 2;
7665 } else if (bp[1] == '/' && cplusplus_comments) {
7666 for (bp += 2; ; bp++) {
7667 if (*bp == '\n')
7668 break;
7669 if (*bp == '\\' && bp[1] == '\n')
7671 if (warn_comments)
7672 warning ("multiline `//' comment");
7673 ip->lineno++;
7674 bp++;
7676 else
7678 #ifdef MULTIBYTE_CHARS
7679 int length;
7680 length = local_mblen (bp, endb - bp);
7681 if (length > 1)
7682 bp += (length - 1);
7683 #endif
7686 } else
7687 break;
7688 } else
7689 break;
7692 cp = bp;
7694 /* Now find end of directive name.
7695 If we encounter a backslash-newline, exchange it with any following
7696 symbol-constituents so that we end up with a contiguous name. */
7698 while (1) {
7699 if (is_idchar[*bp])
7700 bp++;
7701 else {
7702 if (*bp == '\\' && bp[1] == '\n')
7703 name_newline_fix (bp);
7704 if (is_idchar[*bp])
7705 bp++;
7706 else break;
7709 ident_length = bp - cp;
7710 ident = cp;
7711 after_ident = bp;
7713 /* A line of just `#' becomes blank. */
7715 if (ident_length == 0 && *after_ident == '\n') {
7716 continue;
7719 if (ident_length == 0 || !is_idstart[*ident]) {
7720 U_CHAR *p = ident;
7721 while (is_idchar[*p]) {
7722 if (*p < '0' || *p > '9')
7723 break;
7724 p++;
7726 /* Handle # followed by a line number. */
7727 if (p != ident && !is_idchar[*p]) {
7728 if (pedantic)
7729 pedwarn ("`#' followed by integer");
7730 continue;
7733 /* Avoid error for `###' and similar cases unless -pedantic. */
7734 if (p == ident) {
7735 while (*p == '#' || is_hor_space[*p]) p++;
7736 if (*p == '\n') {
7737 if (pedantic && !lang_asm)
7738 pedwarn ("invalid preprocessing directive");
7739 continue;
7743 if (!lang_asm && pedantic)
7744 pedwarn ("invalid preprocessing directive name");
7745 continue;
7748 for (kt = directive_table; kt->length >= 0; kt++) {
7749 IF_STACK_FRAME *temp;
7750 if (ident_length == kt->length
7751 && bcmp (cp, kt->name, kt->length) == 0) {
7752 /* If we are asked to return on next directive, do so now. */
7753 if (any)
7754 goto done;
7756 switch (kt->type) {
7757 case T_IF:
7758 case T_IFDEF:
7759 case T_IFNDEF:
7760 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7761 temp->next = if_stack;
7762 if_stack = temp;
7763 temp->lineno = ip->lineno;
7764 temp->fname = ip->nominal_fname;
7765 temp->fname_len = ip->nominal_fname_len;
7766 temp->type = kt->type;
7767 break;
7768 case T_ELSE:
7769 case T_ENDIF:
7770 if (pedantic && if_stack != save_if_stack)
7771 validate_else (bp, endb);
7772 case T_ELIF:
7773 if (if_stack == instack[indepth].if_stack) {
7774 error ("`#%s' not within a conditional", kt->name);
7775 break;
7777 else if (if_stack == save_if_stack)
7778 goto done; /* found what we came for */
7780 if (kt->type != T_ENDIF) {
7781 if (if_stack->type == T_ELSE)
7782 error ("`#else' or `#elif' after `#else'");
7783 if_stack->type = kt->type;
7784 break;
7787 temp = if_stack;
7788 if_stack = if_stack->next;
7789 free (temp);
7790 break;
7792 case T_INCLUDE:
7793 case T_INCLUDE_NEXT:
7794 case T_IMPORT:
7795 skipping_include_directive = 1;
7796 break;
7798 default:
7799 break;
7801 break;
7804 /* Don't let erroneous code go by. */
7805 if (kt->length < 0 && !lang_asm && pedantic)
7806 pedwarn ("invalid preprocessing directive name");
7810 ip->bufp = bp;
7811 /* after this returns, rescan will exit because ip->bufp
7812 now points to the end of the buffer.
7813 rescan is responsible for the error message also. */
7815 done:
7816 if (output_conditionals && op != 0) {
7817 char *ptr = "#endfailed\n";
7818 int len = strlen (ptr);
7820 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7822 *op->bufp++ = '\n';
7823 op->lineno++;
7825 check_expand (op, beg_of_line - beg_of_group);
7826 bcopy ((char *) beg_of_group, (char *) op->bufp,
7827 beg_of_line - beg_of_group);
7828 op->bufp += beg_of_line - beg_of_group;
7829 op->lineno += ip->lineno - beg_lineno;
7830 check_expand (op, len);
7831 bcopy (ptr, (char *) op->bufp, len);
7832 op->bufp += len;
7833 op->lineno++;
7837 /* Handle a #else directive. Do this by just continuing processing
7838 without changing if_stack ; this is so that the error message
7839 for missing #endif's etc. will point to the original #if. It
7840 is possible that something different would be better. */
7842 static int
7843 do_else (buf, limit, op, keyword)
7844 U_CHAR *buf, *limit;
7845 FILE_BUF *op;
7846 struct directive *keyword ATTRIBUTE_UNUSED;
7848 FILE_BUF *ip = &instack[indepth];
7850 if (pedantic) {
7851 SKIP_WHITE_SPACE (buf);
7852 if (buf != limit)
7853 pedwarn ("text following `#else' violates ANSI standard");
7856 if (if_stack == instack[indepth].if_stack) {
7857 error ("`#else' not within a conditional");
7858 return 0;
7859 } else {
7860 /* #ifndef can't have its special treatment for containing the whole file
7861 if it has a #else clause. */
7862 if_stack->control_macro = 0;
7864 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7865 error ("`#else' after `#else'");
7866 fprintf (stderr, " (matches line %d", if_stack->lineno);
7867 if (! (if_stack->fname_len == ip->nominal_fname_len
7868 && !bcmp (if_stack->fname, ip->nominal_fname,
7869 if_stack->fname_len))) {
7870 fprintf (stderr, ", file ");
7871 eprint_string (if_stack->fname, if_stack->fname_len);
7873 fprintf (stderr, ")\n");
7875 if_stack->type = T_ELSE;
7878 if (if_stack->if_succeeded)
7879 skip_if_group (ip, 0, op);
7880 else {
7881 ++if_stack->if_succeeded; /* continue processing input */
7882 output_line_directive (ip, op, 1, same_file);
7884 return 0;
7887 /* Unstack after #endif directive. */
7889 static int
7890 do_endif (buf, limit, op, keyword)
7891 U_CHAR *buf, *limit;
7892 FILE_BUF *op;
7893 struct directive *keyword ATTRIBUTE_UNUSED;
7895 if (pedantic) {
7896 SKIP_WHITE_SPACE (buf);
7897 if (buf != limit)
7898 pedwarn ("text following `#endif' violates ANSI standard");
7901 if (if_stack == instack[indepth].if_stack)
7902 error ("unbalanced `#endif'");
7903 else {
7904 IF_STACK_FRAME *temp = if_stack;
7905 if_stack = if_stack->next;
7906 if (temp->control_macro != 0) {
7907 /* This #endif matched a #ifndef at the start of the file.
7908 See if it is at the end of the file. */
7909 FILE_BUF *ip = &instack[indepth];
7910 U_CHAR *p = ip->bufp;
7911 U_CHAR *ep = ip->buf + ip->length;
7913 while (p != ep) {
7914 U_CHAR c = *p++;
7915 if (!is_space[c]) {
7916 if (c == '/'
7917 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7918 /* Skip this comment. */
7919 int junk = 0;
7920 U_CHAR *save_bufp = ip->bufp;
7921 ip->bufp = p + 1;
7922 p = skip_to_end_of_comment (ip, &junk, 1);
7923 ip->bufp = save_bufp;
7924 } else
7925 goto fail;
7928 /* If we get here, this #endif ends a #ifndef
7929 that contains all of the file (aside from whitespace).
7930 Arrange not to include the file again
7931 if the macro that was tested is defined.
7933 Do not do this for the top-level file in a -include or any
7934 file in a -imacros. */
7935 if (indepth != 0
7936 && ! (indepth == 1 && no_record_file)
7937 && ! (no_record_file && no_output))
7938 record_control_macro (ip->inc, temp->control_macro);
7939 fail: ;
7941 free (temp);
7942 output_line_directive (&instack[indepth], op, 1, same_file);
7944 return 0;
7947 /* When an #else or #endif is found while skipping failed conditional,
7948 if -pedantic was specified, this is called to warn about text after
7949 the directive name. P points to the first char after the directive
7950 name. */
7952 static void
7953 validate_else (p, limit)
7954 register U_CHAR *p;
7955 register U_CHAR *limit;
7957 /* Advance P over whitespace and comments. */
7958 while (1) {
7959 while (*p == '\\' && p[1] == '\n')
7960 p += 2;
7961 if (is_hor_space[*p])
7962 p++;
7963 else if (*p == '/') {
7964 while (p[1] == '\\' && p[2] == '\n')
7965 p += 2;
7966 if (p[1] == '*') {
7967 /* Don't bother warning about unterminated comments
7968 since that will happen later. Just be sure to exit. */
7969 for (p += 2; ; p++) {
7970 if (p == limit)
7971 return;
7972 if (*p == '*') {
7973 while (p[1] == '\\' && p[2] == '\n')
7974 p += 2;
7975 if (p[1] == '/') {
7976 p += 2;
7977 break;
7980 else
7982 #ifdef MULTIBYTE_CHARS
7983 int length;
7984 length = local_mblen (p, limit - p);
7985 if (length > 1)
7986 p += (length - 1);
7987 #endif
7991 else if (cplusplus_comments && p[1] == '/')
7992 return;
7993 else break;
7994 } else break;
7996 if (*p != '\n')
7997 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
8000 /* Skip a comment, assuming the input ptr immediately follows the
8001 initial slash-star. Bump *LINE_COUNTER for each newline.
8002 (The canonical line counter is &ip->lineno.)
8003 Don't use this routine (or the next one) if bumping the line
8004 counter is not sufficient to deal with newlines in the string.
8006 If NOWARN is nonzero, don't warn about slash-star inside a comment.
8007 This feature is useful when processing a comment that is going to
8008 be processed or was processed at another point in the preprocessor,
8009 to avoid a duplicate warning. Likewise for unterminated comment
8010 errors. */
8012 static U_CHAR *
8013 skip_to_end_of_comment (ip, line_counter, nowarn)
8014 register FILE_BUF *ip;
8015 int *line_counter; /* place to remember newlines, or NULL */
8016 int nowarn;
8018 register U_CHAR *limit = ip->buf + ip->length;
8019 register U_CHAR *bp = ip->bufp;
8020 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
8021 int start_line = line_counter ? *line_counter : 0;
8023 /* JF this line_counter stuff is a crock to make sure the
8024 comment is only put out once, no matter how many times
8025 the comment is skipped. It almost works */
8026 if (op) {
8027 *op->bufp++ = '/';
8028 *op->bufp++ = bp[-1];
8030 if (cplusplus_comments && bp[-1] == '/') {
8031 for (; bp < limit; bp++) {
8032 if (*bp == '\n')
8033 break;
8034 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
8036 if (!nowarn && warn_comments)
8037 warning ("multiline `//' comment");
8038 if (line_counter)
8039 ++*line_counter;
8040 if (op)
8042 ++op->lineno;
8043 *op->bufp++ = *bp;
8045 ++bp;
8047 else
8049 #ifdef MULTIBYTE_CHARS
8050 int length;
8051 length = local_mblen (bp, limit - bp);
8052 if (length > 1)
8054 if (op)
8056 bcopy (bp, op->bufp, length - 1);
8057 op->bufp += (length - 1);
8059 bp += (length - 1);
8061 #endif
8063 if (op)
8064 *op->bufp++ = *bp;
8066 ip->bufp = bp;
8067 return bp;
8069 while (bp < limit) {
8070 if (op)
8071 *op->bufp++ = *bp;
8072 switch (*bp++) {
8073 case '\n':
8074 /* If this is the end of the file, we have an unterminated comment.
8075 Don't swallow the newline. We are guaranteed that there will be a
8076 trailing newline and various pieces assume it's there. */
8077 if (bp == limit)
8079 --bp;
8080 --limit;
8081 break;
8083 if (line_counter != NULL)
8084 ++*line_counter;
8085 if (op)
8086 ++op->lineno;
8087 break;
8088 case '*':
8089 if (bp[-2] == '/' && !nowarn && warn_comments)
8090 warning ("`/*' within comment");
8091 if (*bp == '\\' && bp[1] == '\n')
8092 newline_fix (bp);
8093 if (*bp == '/') {
8094 if (op)
8095 *op->bufp++ = '/';
8096 ip->bufp = ++bp;
8097 return bp;
8099 break;
8100 #ifdef MULTIBYTE_CHARS
8101 default:
8103 int length;
8104 bp--;
8105 length = local_mblen (bp, limit - bp);
8106 if (length <= 0)
8107 length = 1;
8108 if (op)
8110 op->bufp--;
8111 bcopy (bp, op->bufp, length);
8112 op->bufp += length;
8114 bp += length;
8116 #endif
8120 if (!nowarn)
8121 error_with_line (line_for_error (start_line), "unterminated comment");
8122 ip->bufp = bp;
8123 return bp;
8126 /* Skip over a quoted string. BP points to the opening quote.
8127 Returns a pointer after the closing quote. Don't go past LIMIT.
8128 START_LINE is the line number of the starting point (but it need
8129 not be valid if the starting point is inside a macro expansion).
8131 The input stack state is not changed.
8133 If COUNT_NEWLINES is nonzero, it points to an int to increment
8134 for each newline passed.
8136 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
8137 if we pass a backslash-newline.
8139 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
8141 static U_CHAR *
8142 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
8143 register U_CHAR *bp;
8144 register U_CHAR *limit;
8145 int start_line;
8146 int *count_newlines;
8147 int *backslash_newlines_p;
8148 int *eofp;
8150 register U_CHAR c, match;
8152 match = *bp++;
8153 while (1) {
8154 if (bp >= limit) {
8155 error_with_line (line_for_error (start_line),
8156 "unterminated string or character constant");
8157 error_with_line (multiline_string_line,
8158 "possible real start of unterminated constant");
8159 multiline_string_line = 0;
8160 if (eofp)
8161 *eofp = 1;
8162 break;
8164 c = *bp++;
8165 if (c == '\\') {
8166 while (*bp == '\\' && bp[1] == '\n') {
8167 if (backslash_newlines_p)
8168 *backslash_newlines_p = 1;
8169 if (count_newlines)
8170 ++*count_newlines;
8171 bp += 2;
8173 if (*bp == '\n') {
8174 if (backslash_newlines_p)
8175 *backslash_newlines_p = 1;
8176 if (count_newlines)
8177 ++*count_newlines;
8179 bp++;
8180 } else if (c == '\n') {
8181 if (traditional) {
8182 /* Unterminated strings and character constants are 'valid'. */
8183 bp--; /* Don't consume the newline. */
8184 if (eofp)
8185 *eofp = 1;
8186 break;
8188 if (match == '\'') {
8189 error_with_line (line_for_error (start_line),
8190 "unterminated string or character constant");
8191 bp--;
8192 if (eofp)
8193 *eofp = 1;
8194 break;
8196 /* If not traditional, then allow newlines inside strings. */
8197 if (count_newlines)
8198 ++*count_newlines;
8199 if (multiline_string_line == 0) {
8200 if (pedantic)
8201 pedwarn_with_line (line_for_error (start_line),
8202 "string constant runs past end of line");
8203 multiline_string_line = start_line;
8205 } else if (c == match)
8206 break;
8207 #ifdef MULTIBYTE_CHARS
8209 int length;
8210 --bp;
8211 length = local_mblen (bp, limit - bp);
8212 if (length <= 0)
8213 length = 1;
8214 bp += length;
8216 #endif
8218 return bp;
8221 /* Place into DST a quoted string representing the string SRC.
8222 SRCLEN is the length of SRC; SRC may contain null bytes.
8223 Return the address of DST's terminating null. */
8225 static char *
8226 quote_string (dst, src, srclen)
8227 char *dst, *src;
8228 size_t srclen;
8230 U_CHAR c;
8231 char *srclim = src + srclen;
8233 *dst++ = '\"';
8234 while (src != srclim)
8235 switch ((c = *src++))
8237 default:
8238 if (ISPRINT (c))
8239 *dst++ = c;
8240 else
8242 sprintf (dst, "\\%03o", c);
8243 dst += 4;
8245 break;
8247 case '\"':
8248 case '\\':
8249 *dst++ = '\\';
8250 *dst++ = c;
8251 break;
8254 *dst++ = '\"';
8255 *dst = '\0';
8256 return dst;
8259 /* Skip across a group of balanced parens, starting from IP->bufp.
8260 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
8262 This does not handle newlines, because it's used for the arg of #if,
8263 where there aren't any newlines. Also, backslash-newline can't appear. */
8265 static U_CHAR *
8266 skip_paren_group (ip)
8267 register FILE_BUF *ip;
8269 U_CHAR *limit = ip->buf + ip->length;
8270 U_CHAR *p = ip->bufp;
8271 int depth = 0;
8272 int lines_dummy = 0;
8274 while (p != limit) {
8275 int c = *p++;
8276 switch (c) {
8277 case '(':
8278 depth++;
8279 break;
8281 case ')':
8282 depth--;
8283 if (depth == 0)
8284 return ip->bufp = p;
8285 break;
8287 case '/':
8288 if (*p == '*') {
8289 ip->bufp = p;
8290 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
8291 p = ip->bufp;
8294 case '"':
8295 case '\'':
8297 int eofp = 0;
8298 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
8299 if (eofp)
8300 return ip->bufp = p;
8302 break;
8306 ip->bufp = p;
8307 return p;
8310 /* Write out a #line directive, for instance, after an #include file.
8311 If CONDITIONAL is nonzero, we can omit the #line if it would
8312 appear to be a no-op, and we can output a few newlines instead
8313 if we want to increase the line number by a small amount.
8314 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
8316 static void
8317 output_line_directive (ip, op, conditional, file_change)
8318 FILE_BUF *ip, *op;
8319 int conditional;
8320 enum file_change_code file_change;
8322 int len;
8323 char *line_directive_buf, *line_end;
8325 if (no_line_directives
8326 || ip->fname == NULL
8327 || no_output) {
8328 op->lineno = ip->lineno;
8329 return;
8332 if (conditional) {
8333 if (ip->lineno == op->lineno)
8334 return;
8336 /* If the inherited line number is a little too small,
8337 output some newlines instead of a #line directive. */
8338 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8339 check_expand (op, 10);
8340 while (ip->lineno > op->lineno) {
8341 *op->bufp++ = '\n';
8342 op->lineno++;
8344 return;
8348 /* Output a positive line number if possible. */
8349 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8350 && *ip->bufp == '\n') {
8351 ip->lineno++;
8352 ip->bufp++;
8355 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8356 sprintf (line_directive_buf, "# %d ", ip->lineno);
8357 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8358 ip->nominal_fname, ip->nominal_fname_len);
8359 if (file_change != same_file) {
8360 *line_end++ = ' ';
8361 *line_end++ = file_change == enter_file ? '1' : '2';
8363 /* Tell cc1 if following text comes from a system header file. */
8364 if (ip->system_header_p) {
8365 *line_end++ = ' ';
8366 *line_end++ = '3';
8368 #ifndef NO_IMPLICIT_EXTERN_C
8369 /* Tell cc1plus if following text should be treated as C. */
8370 if (ip->system_header_p == 2 && cplusplus) {
8371 *line_end++ = ' ';
8372 *line_end++ = '4';
8374 #endif
8375 *line_end++ = '\n';
8376 len = line_end - line_directive_buf;
8377 check_expand (op, len + 1);
8378 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8379 *op->bufp++ = '\n';
8380 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8381 op->bufp += len;
8382 op->lineno = ip->lineno;
8385 /* This structure represents one parsed argument in a macro call.
8386 `raw' points to the argument text as written (`raw_length' is its length).
8387 `expanded' points to the argument's macro-expansion
8388 (its length is `expand_length').
8389 `stringified_length' is the length the argument would have
8390 if stringified.
8391 `use_count' is the number of times this macro arg is substituted
8392 into the macro. If the actual use count exceeds 10,
8393 the value stored is 10.
8394 `free1' and `free2', if nonzero, point to blocks to be freed
8395 when the macro argument data is no longer needed. */
8397 struct argdata {
8398 U_CHAR *raw, *expanded;
8399 int raw_length, expand_length;
8400 int stringified_length;
8401 U_CHAR *free1, *free2;
8402 char newlines;
8403 char use_count;
8406 /* Expand a macro call.
8407 HP points to the symbol that is the macro being called.
8408 Put the result of expansion onto the input stack
8409 so that subsequent input by our caller will use it.
8411 If macro wants arguments, caller has already verified that
8412 an argument list follows; arguments come from the input stack. */
8414 static void
8415 macroexpand (hp, op)
8416 HASHNODE *hp;
8417 FILE_BUF *op;
8419 int nargs;
8420 DEFINITION *defn = hp->value.defn;
8421 register U_CHAR *xbuf;
8422 int xbuf_len;
8423 int start_line = instack[indepth].lineno;
8424 int rest_args, rest_zero;
8426 CHECK_DEPTH (return;);
8428 /* it might not actually be a macro. */
8429 if (hp->type != T_MACRO) {
8430 special_symbol (hp, op);
8431 return;
8434 /* This macro is being used inside a #if, which means it must be */
8435 /* recorded as a precondition. */
8436 if (pcp_inside_if && pcp_outfile && defn->predefined)
8437 dump_single_macro (hp, pcp_outfile);
8439 nargs = defn->nargs;
8441 if (nargs >= 0) {
8442 register int i;
8443 struct argdata *args;
8444 char *parse_error = 0;
8446 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8448 for (i = 0; i < nargs; i++) {
8449 args[i].raw = (U_CHAR *) "";
8450 args[i].expanded = 0;
8451 args[i].raw_length = args[i].expand_length
8452 = args[i].stringified_length = 0;
8453 args[i].free1 = args[i].free2 = 0;
8454 args[i].use_count = 0;
8457 /* Parse all the macro args that are supplied. I counts them.
8458 The first NARGS args are stored in ARGS.
8459 The rest are discarded.
8460 If rest_args is set then we assume macarg absorbed the rest of the args.
8462 i = 0;
8463 rest_args = 0;
8464 do {
8465 /* Discard the open-parenthesis or comma before the next arg. */
8466 ++instack[indepth].bufp;
8467 if (rest_args)
8468 continue;
8469 if (i < nargs || (nargs == 0 && i == 0)) {
8470 /* If we are working on last arg which absorbs rest of args... */
8471 if (i == nargs - 1 && defn->rest_args)
8472 rest_args = 1;
8473 parse_error = macarg (&args[i], rest_args);
8475 else
8476 parse_error = macarg (NULL_PTR, 0);
8477 if (parse_error) {
8478 error_with_line (line_for_error (start_line), parse_error);
8479 break;
8481 i++;
8482 } while (*instack[indepth].bufp != ')');
8484 /* If we got one arg but it was just whitespace, call that 0 args. */
8485 if (i == 1) {
8486 register U_CHAR *bp = args[0].raw;
8487 register U_CHAR *lim = bp + args[0].raw_length;
8488 /* cpp.texi says for foo ( ) we provide one argument.
8489 However, if foo wants just 0 arguments, treat this as 0. */
8490 if (nargs == 0)
8491 while (bp != lim && is_space[*bp]) bp++;
8492 if (bp == lim)
8493 i = 0;
8496 /* Don't output an error message if we have already output one for
8497 a parse error above. */
8498 rest_zero = 0;
8499 if (nargs == 0 && i > 0) {
8500 if (! parse_error)
8501 error ("arguments given to macro `%s'", hp->name);
8502 } else if (i < nargs) {
8503 /* traditional C allows foo() if foo wants one argument. */
8504 if (nargs == 1 && i == 0 && traditional)
8506 /* the rest args token is allowed to absorb 0 tokens */
8507 else if (i == nargs - 1 && defn->rest_args)
8508 rest_zero = 1;
8509 else if (parse_error)
8511 else if (i == 0)
8512 error ("macro `%s' used without args", hp->name);
8513 else if (i == 1)
8514 error ("macro `%s' used with just one arg", hp->name);
8515 else
8516 error ("macro `%s' used with only %d args", hp->name, i);
8517 } else if (i > nargs) {
8518 if (! parse_error)
8519 error ("macro `%s' used with too many (%d) args", hp->name, i);
8522 /* Swallow the closeparen. */
8523 ++instack[indepth].bufp;
8525 /* If macro wants zero args, we parsed the arglist for checking only.
8526 Read directly from the macro definition. */
8527 if (nargs == 0) {
8528 xbuf = defn->expansion;
8529 xbuf_len = defn->length;
8530 } else {
8531 register U_CHAR *exp = defn->expansion;
8532 register int offset; /* offset in expansion,
8533 copied a piece at a time */
8534 register int totlen; /* total amount of exp buffer filled so far */
8536 register struct reflist *ap, *last_ap;
8538 /* Macro really takes args. Compute the expansion of this call. */
8540 /* Compute length in characters of the macro's expansion.
8541 Also count number of times each arg is used. */
8542 xbuf_len = defn->length;
8543 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8544 if (ap->stringify)
8545 xbuf_len += args[ap->argno].stringified_length;
8546 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8547 /* Add 4 for two newline-space markers to prevent
8548 token concatenation. */
8549 xbuf_len += args[ap->argno].raw_length + 4;
8550 else {
8551 /* We have an ordinary (expanded) occurrence of the arg.
8552 So compute its expansion, if we have not already. */
8553 if (args[ap->argno].expanded == 0) {
8554 FILE_BUF obuf;
8555 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8556 args[ap->argno].raw + args[ap->argno].raw_length,
8557 1, 0);
8559 args[ap->argno].expanded = obuf.buf;
8560 args[ap->argno].expand_length = obuf.length;
8561 args[ap->argno].free2 = obuf.buf;
8564 /* Add 4 for two newline-space markers to prevent
8565 token concatenation. */
8566 xbuf_len += args[ap->argno].expand_length + 4;
8568 if (args[ap->argno].use_count < 10)
8569 args[ap->argno].use_count++;
8572 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8574 /* Generate in XBUF the complete expansion
8575 with arguments substituted in.
8576 TOTLEN is the total size generated so far.
8577 OFFSET is the index in the definition
8578 of where we are copying from. */
8579 offset = totlen = 0;
8580 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8581 last_ap = ap, ap = ap->next) {
8582 register struct argdata *arg = &args[ap->argno];
8583 int count_before = totlen;
8585 /* Add chars to XBUF. */
8586 for (i = 0; i < ap->nchars; i++, offset++)
8587 xbuf[totlen++] = exp[offset];
8589 /* If followed by an empty rest arg with concatenation,
8590 delete the last run of nonwhite chars. */
8591 if (rest_zero && totlen > count_before
8592 && ((ap->rest_args && ap->raw_before != 0)
8593 || (last_ap != NULL && last_ap->rest_args
8594 && last_ap->raw_after != 0))) {
8595 /* Delete final whitespace. */
8596 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8597 totlen--;
8600 /* Delete the nonwhites before them. */
8601 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8602 totlen--;
8606 if (ap->stringify != 0) {
8607 int arglen = arg->raw_length;
8608 int escaped = 0;
8609 int in_string = 0;
8610 int c;
8611 i = 0;
8612 while (i < arglen
8613 && (c = arg->raw[i], is_space[c]))
8614 i++;
8615 while (i < arglen
8616 && (c = arg->raw[arglen - 1], is_space[c]))
8617 arglen--;
8618 if (!traditional)
8619 xbuf[totlen++] = '\"'; /* insert beginning quote */
8620 for (; i < arglen; i++) {
8621 c = arg->raw[i];
8623 if (! in_string) {
8624 /* Special markers Newline Space
8625 generate nothing for a stringified argument. */
8626 if (c == '\n' && arg->raw[i+1] != '\n') {
8627 i++;
8628 continue;
8631 /* Internal sequences of whitespace are replaced by one space
8632 except within an string or char token. */
8633 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8634 while (1) {
8635 /* Note that Newline Space does occur within whitespace
8636 sequences; consider it part of the sequence. */
8637 if (c == '\n' && is_space[arg->raw[i+1]])
8638 i += 2;
8639 else if (c != '\n' && is_space[c])
8640 i++;
8641 else break;
8642 c = arg->raw[i];
8644 i--;
8645 c = ' ';
8649 if (escaped)
8650 escaped = 0;
8651 else {
8652 if (c == '\\')
8653 escaped = 1;
8654 else if (in_string) {
8655 if (c == in_string)
8656 in_string = 0;
8657 else
8659 #ifdef MULTIBYTE_CHARS
8660 int length;
8661 length = local_mblen (arg->raw + i, arglen - i);
8662 if (length > 1)
8664 bcopy (arg->raw + i, xbuf + totlen, length);
8665 i += length - 1;
8666 totlen += length;
8667 continue;
8669 #endif
8671 } else if (c == '\"' || c == '\'')
8672 in_string = c;
8675 /* Escape these chars */
8676 if (c == '\"' || (in_string && c == '\\'))
8677 xbuf[totlen++] = '\\';
8678 /* We used to output e.g. \008 for control characters here,
8679 but this doesn't conform to the C Standard.
8680 Just output the characters as-is. */
8681 xbuf[totlen++] = c;
8683 if (!traditional)
8684 xbuf[totlen++] = '\"'; /* insert ending quote */
8685 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8686 U_CHAR *p1 = arg->raw;
8687 U_CHAR *l1 = p1 + arg->raw_length;
8688 if (ap->raw_before != 0) {
8689 while (p1 != l1 && is_space[*p1]) p1++;
8690 while (p1 != l1 && is_idchar[*p1])
8691 xbuf[totlen++] = *p1++;
8692 /* Delete any no-reexpansion marker that follows
8693 an identifier at the beginning of the argument
8694 if the argument is concatenated with what precedes it. */
8695 if (p1[0] == '\n' && p1[1] == '-')
8696 p1 += 2;
8697 } else if (!traditional) {
8698 /* Ordinary expanded use of the argument.
8699 Put in newline-space markers to prevent token pasting. */
8700 xbuf[totlen++] = '\n';
8701 xbuf[totlen++] = ' ';
8703 if (ap->raw_after != 0) {
8704 /* Arg is concatenated after: delete trailing whitespace,
8705 whitespace markers, and no-reexpansion markers. */
8706 while (p1 != l1) {
8707 if (is_space[l1[-1]]) l1--;
8708 else if (l1[-1] == '-') {
8709 U_CHAR *p2 = l1 - 1;
8710 /* If a `-' is preceded by an odd number of newlines then it
8711 and the last newline are a no-reexpansion marker. */
8712 while (p2 != p1 && p2[-1] == '\n') p2--;
8713 if ((l1 - 1 - p2) & 1) {
8714 l1 -= 2;
8716 else break;
8718 else break;
8722 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8723 totlen += l1 - p1;
8724 if (!traditional && ap->raw_after == 0) {
8725 /* Ordinary expanded use of the argument.
8726 Put in newline-space markers to prevent token pasting. */
8727 xbuf[totlen++] = '\n';
8728 xbuf[totlen++] = ' ';
8730 } else {
8731 /* Ordinary expanded use of the argument.
8732 Put in newline-space markers to prevent token pasting. */
8733 if (!traditional) {
8734 xbuf[totlen++] = '\n';
8735 xbuf[totlen++] = ' ';
8737 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8738 arg->expand_length);
8739 totlen += arg->expand_length;
8740 if (!traditional) {
8741 xbuf[totlen++] = '\n';
8742 xbuf[totlen++] = ' ';
8744 /* If a macro argument with newlines is used multiple times,
8745 then only expand the newlines once. This avoids creating output
8746 lines which don't correspond to any input line, which confuses
8747 gdb and gcov. */
8748 if (arg->use_count > 1 && arg->newlines > 0) {
8749 /* Don't bother doing change_newlines for subsequent
8750 uses of arg. */
8751 arg->use_count = 1;
8752 arg->expand_length
8753 = change_newlines (arg->expanded, arg->expand_length);
8757 if (totlen > xbuf_len)
8758 abort ();
8761 /* If there is anything left of the definition after handling
8762 the arg list, copy that in too. */
8764 for (i = offset; i < defn->length; i++) {
8765 /* if we've reached the end of the macro */
8766 if (exp[i] == ')')
8767 rest_zero = 0;
8768 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8769 && last_ap->raw_after != 0))
8770 xbuf[totlen++] = exp[i];
8773 xbuf[totlen] = 0;
8774 xbuf_len = totlen;
8776 for (i = 0; i < nargs; i++) {
8777 if (args[i].free1 != 0)
8778 free (args[i].free1);
8779 if (args[i].free2 != 0)
8780 free (args[i].free2);
8783 } else {
8784 xbuf = defn->expansion;
8785 xbuf_len = defn->length;
8788 /* Now put the expansion on the input stack
8789 so our caller will commence reading from it. */
8791 register FILE_BUF *ip2;
8793 ip2 = &instack[++indepth];
8795 ip2->fname = 0;
8796 ip2->nominal_fname = 0;
8797 ip2->nominal_fname_len = 0;
8798 ip2->inc = 0;
8799 /* This may not be exactly correct, but will give much better error
8800 messages for nested macro calls than using a line number of zero. */
8801 ip2->lineno = start_line;
8802 ip2->buf = xbuf;
8803 ip2->length = xbuf_len;
8804 ip2->bufp = xbuf;
8805 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8806 ip2->macro = hp;
8807 ip2->if_stack = if_stack;
8808 ip2->system_header_p = 0;
8810 /* Recursive macro use sometimes works traditionally.
8811 #define foo(x,y) bar (x (y,0), y)
8812 foo (foo, baz) */
8814 if (!traditional)
8815 hp->type = T_DISABLED;
8819 /* Parse a macro argument and store the info on it into *ARGPTR.
8820 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8821 Return nonzero to indicate a syntax error. */
8823 static char *
8824 macarg (argptr, rest_args)
8825 register struct argdata *argptr;
8826 int rest_args;
8828 FILE_BUF *ip = &instack[indepth];
8829 int paren = 0;
8830 int newlines = 0;
8831 int comments = 0;
8832 char *result = 0;
8834 /* Try to parse as much of the argument as exists at this
8835 input stack level. */
8836 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8837 &paren, &newlines, &comments, rest_args);
8839 /* If we find the end of the argument at this level,
8840 set up *ARGPTR to point at it in the input stack. */
8841 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8842 && bp != ip->buf + ip->length) {
8843 if (argptr != 0) {
8844 argptr->raw = ip->bufp;
8845 argptr->raw_length = bp - ip->bufp;
8846 argptr->newlines = newlines;
8848 ip->bufp = bp;
8849 } else {
8850 /* This input stack level ends before the macro argument does.
8851 We must pop levels and keep parsing.
8852 Therefore, we must allocate a temporary buffer and copy
8853 the macro argument into it. */
8854 int bufsize = bp - ip->bufp;
8855 int extra = newlines;
8856 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8857 int final_start = 0;
8859 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8860 ip->bufp = bp;
8861 ip->lineno += newlines;
8863 while (bp == ip->buf + ip->length) {
8864 if (instack[indepth].macro == 0) {
8865 result = "unterminated macro call";
8866 break;
8868 ip->macro->type = T_MACRO;
8869 if (ip->free_ptr)
8870 free (ip->free_ptr);
8871 ip = &instack[--indepth];
8872 newlines = 0;
8873 comments = 0;
8874 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8875 &newlines, &comments, rest_args);
8876 final_start = bufsize;
8877 bufsize += bp - ip->bufp;
8878 extra += newlines;
8879 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8880 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8881 bp - ip->bufp);
8882 ip->bufp = bp;
8883 ip->lineno += newlines;
8886 /* Now, if arg is actually wanted, record its raw form,
8887 discarding comments and duplicating newlines in whatever
8888 part of it did not come from a macro expansion.
8889 EXTRA space has been preallocated for duplicating the newlines.
8890 FINAL_START is the index of the start of that part. */
8891 if (argptr != 0) {
8892 argptr->raw = buffer;
8893 argptr->raw_length = bufsize;
8894 argptr->free1 = buffer;
8895 argptr->newlines = newlines;
8896 if ((newlines || comments) && ip->fname != 0)
8897 argptr->raw_length
8898 = final_start +
8899 discard_comments (argptr->raw + final_start,
8900 argptr->raw_length - final_start,
8901 newlines);
8902 argptr->raw[argptr->raw_length] = 0;
8903 if (argptr->raw_length > bufsize + extra)
8904 abort ();
8908 /* If we are not discarding this argument,
8909 macroexpand it and compute its length as stringified.
8910 All this info goes into *ARGPTR. */
8912 if (argptr != 0) {
8913 register U_CHAR *buf, *lim;
8914 register int totlen;
8916 buf = argptr->raw;
8917 lim = buf + argptr->raw_length;
8919 while (buf != lim && is_space[*buf])
8920 buf++;
8921 while (buf != lim && is_space[lim[-1]])
8922 lim--;
8923 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8924 while (buf != lim) {
8925 register U_CHAR c = *buf++;
8926 totlen++;
8927 /* Internal sequences of whitespace are replaced by one space
8928 in most cases, but not always. So count all the whitespace
8929 in case we need to keep it all. */
8930 #if 0
8931 if (is_space[c])
8932 SKIP_ALL_WHITE_SPACE (buf);
8933 else
8934 #endif
8935 if (c == '\"' || c == '\\') /* escape these chars */
8936 totlen++;
8938 argptr->stringified_length = totlen;
8940 return result;
8943 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8944 taken from the expansion of MACRO,
8945 counting parens in *DEPTHPTR,
8946 and return if reach LIMIT
8947 or before a `)' that would make *DEPTHPTR negative
8948 or before a comma when *DEPTHPTR is zero.
8949 Single and double quotes are matched and termination
8950 is inhibited within them. Comments also inhibit it.
8951 Value returned is pointer to stopping place.
8953 Increment *NEWLINES each time a newline is passed.
8954 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8955 Set *COMMENTS to 1 if a comment is seen. */
8957 static U_CHAR *
8958 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8959 U_CHAR *start;
8960 register U_CHAR *limit;
8961 struct hashnode *macro;
8962 int *depthptr, *newlines, *comments;
8963 int rest_args;
8965 register U_CHAR *bp = start;
8967 while (bp < limit) {
8968 switch (*bp) {
8969 case '(':
8970 (*depthptr)++;
8971 break;
8972 case ')':
8973 if (--(*depthptr) < 0)
8974 return bp;
8975 break;
8976 case '\\':
8977 /* Traditionally, backslash makes following char not special. */
8978 if (traditional && bp + 1 < limit && bp[1] != '\n')
8979 bp++;
8980 break;
8981 case '\n':
8982 ++*newlines;
8983 break;
8984 case '/':
8985 if (macro)
8986 break;
8987 if (bp[1] == '\\' && bp[2] == '\n')
8988 newline_fix (bp + 1);
8989 if (bp[1] == '*') {
8990 *comments = 1;
8991 for (bp += 2; bp < limit; bp++) {
8992 if (*bp == '\n')
8993 ++*newlines;
8994 else if (*bp == '*') {
8995 if (bp[-1] == '/' && warn_comments)
8996 warning ("`/*' within comment");
8997 if (bp[1] == '\\' && bp[2] == '\n')
8998 newline_fix (bp + 1);
8999 if (bp[1] == '/') {
9000 bp++;
9001 break;
9004 else
9006 #ifdef MULTIBYTE_CHARS
9007 int length;
9008 length = local_mblen (bp, limit - bp);
9009 if (length > 1)
9010 bp += (length - 1);
9011 #endif
9014 } else if (bp[1] == '/' && cplusplus_comments) {
9015 *comments = 1;
9016 for (bp += 2; bp < limit; bp++) {
9017 if (*bp == '\n') {
9018 ++*newlines;
9019 break;
9021 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
9023 ++*newlines;
9024 if (warn_comments)
9025 warning ("multiline `//' comment");
9026 ++bp;
9028 else
9030 #ifdef MULTIBYTE_CHARS
9031 int length;
9032 length = local_mblen (bp, limit - bp);
9033 if (length > 1)
9034 bp += (length - 1);
9035 #endif
9039 break;
9040 case '\'':
9041 case '\"':
9043 int quotec;
9044 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
9045 if (*bp == '\\') {
9046 bp++;
9047 if (*bp == '\n')
9048 ++*newlines;
9049 if (!macro) {
9050 while (*bp == '\\' && bp[1] == '\n') {
9051 bp += 2;
9052 ++*newlines;
9055 } else if (*bp == '\n') {
9056 ++*newlines;
9057 if (quotec == '\'')
9058 break;
9060 else
9062 #ifdef MULTIBYTE_CHARS
9063 int length;
9064 length = local_mblen (bp, limit - bp);
9065 if (length > 1)
9066 bp += (length - 1);
9067 #endif
9071 break;
9072 case ',':
9073 /* if we've returned to lowest level and we aren't absorbing all args */
9074 if ((*depthptr) == 0 && rest_args == 0)
9075 return bp;
9076 break;
9078 bp++;
9081 return bp;
9084 /* Discard comments and duplicate newlines
9085 in the string of length LENGTH at START,
9086 except inside of string constants.
9087 The string is copied into itself with its beginning staying fixed.
9089 NEWLINES is the number of newlines that must be duplicated.
9090 We assume that that much extra space is available past the end
9091 of the string. */
9093 static int
9094 discard_comments (start, length, newlines)
9095 U_CHAR *start;
9096 int length;
9097 int newlines;
9099 register U_CHAR *ibp;
9100 register U_CHAR *obp;
9101 register U_CHAR *limit;
9102 register int c;
9104 /* If we have newlines to duplicate, copy everything
9105 that many characters up. Then, in the second part,
9106 we will have room to insert the newlines
9107 while copying down.
9108 NEWLINES may actually be too large, because it counts
9109 newlines in string constants, and we don't duplicate those.
9110 But that does no harm. */
9111 if (newlines > 0) {
9112 ibp = start + length;
9113 obp = ibp + newlines;
9114 limit = start;
9115 while (limit != ibp)
9116 *--obp = *--ibp;
9119 ibp = start + newlines;
9120 limit = start + length + newlines;
9121 obp = start;
9123 while (ibp < limit) {
9124 *obp++ = c = *ibp++;
9125 switch (c) {
9126 case '\n':
9127 /* Duplicate the newline. */
9128 *obp++ = '\n';
9129 break;
9131 case '\\':
9132 if (*ibp == '\n') {
9133 obp--;
9134 ibp++;
9136 break;
9138 case '/':
9139 if (*ibp == '\\' && ibp[1] == '\n')
9140 newline_fix (ibp);
9141 /* Delete any comment. */
9142 if (cplusplus_comments && ibp[0] == '/') {
9143 /* Comments are equivalent to spaces. */
9144 obp[-1] = ' ';
9145 ibp++;
9146 while (ibp < limit)
9148 if (*ibp == '\n')
9149 break;
9150 if (*ibp == '\\' && ibp + 1 < limit && ibp[1] == '\n')
9151 ibp++;
9152 else
9154 #ifdef MULTIBYTE_CHARS
9155 int length = local_mblen (ibp, limit - ibp);
9156 if (length > 1)
9157 ibp += (length - 1);
9158 #endif
9160 ibp++;
9162 break;
9164 if (ibp[0] != '*' || ibp + 1 >= limit)
9165 break;
9166 /* Comments are equivalent to spaces.
9167 For -traditional, a comment is equivalent to nothing. */
9168 if (traditional)
9169 obp--;
9170 else
9171 obp[-1] = ' ';
9172 while (++ibp < limit) {
9173 if (ibp[0] == '*') {
9174 if (ibp[1] == '\\' && ibp[2] == '\n')
9175 newline_fix (ibp + 1);
9176 if (ibp[1] == '/') {
9177 ibp += 2;
9178 break;
9181 else
9183 #ifdef MULTIBYTE_CHARS
9184 int length = local_mblen (ibp, limit - ibp);
9185 if (length > 1)
9186 ibp += (length - 1);
9187 #endif
9190 break;
9192 case '\'':
9193 case '\"':
9194 /* Notice and skip strings, so that we don't
9195 think that comments start inside them,
9196 and so we don't duplicate newlines in them. */
9198 int quotec = c;
9199 while (ibp < limit) {
9200 *obp++ = c = *ibp++;
9201 if (c == quotec)
9202 break;
9203 if (c == '\n')
9205 if (quotec == '\'')
9206 break;
9208 else if (c == '\\') {
9209 if (ibp < limit && *ibp == '\n') {
9210 ibp++;
9211 obp--;
9212 } else {
9213 while (*ibp == '\\' && ibp[1] == '\n')
9214 ibp += 2;
9215 if (ibp < limit)
9216 *obp++ = *ibp++;
9219 else
9221 #ifdef MULTIBYTE_CHARS
9222 int length;
9223 ibp--;
9224 length = local_mblen (ibp, limit - ibp);
9225 if (length > 1)
9227 obp--;
9228 bcopy (ibp, obp, length);
9229 ibp += length;
9230 obp += length;
9232 else
9233 ibp++;
9234 #endif
9238 break;
9242 return obp - start;
9245 /* Turn newlines to spaces in the string of length LENGTH at START,
9246 except inside of string constants.
9247 The string is copied into itself with its beginning staying fixed. */
9249 static int
9250 change_newlines (start, length)
9251 U_CHAR *start;
9252 int length;
9254 register U_CHAR *ibp;
9255 register U_CHAR *obp;
9256 register U_CHAR *limit;
9257 register int c;
9259 ibp = start;
9260 limit = start + length;
9261 obp = start;
9263 while (ibp < limit) {
9264 *obp++ = c = *ibp++;
9265 switch (c) {
9266 case '\n':
9267 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
9268 string. Skip past the newline and its duplicate.
9269 Put a space in the output. */
9270 if (*ibp == '\n')
9272 ibp++;
9273 obp--;
9274 *obp++ = ' ';
9276 break;
9278 case '\'':
9279 case '\"':
9280 /* Notice and skip strings, so that we don't delete newlines in them. */
9282 int quotec = c;
9283 while (ibp < limit) {
9284 *obp++ = c = *ibp++;
9285 if (c == quotec)
9286 break;
9287 else if (c == '\\' && ibp < limit && *ibp == '\n')
9288 *obp++ = *ibp++;
9289 else if (c == '\n')
9291 if (quotec == '\'')
9292 break;
9294 else
9296 #ifdef MULTIBYTE_CHARS
9297 int length;
9298 ibp--;
9299 length = local_mblen (ibp, limit - ibp);
9300 if (length > 1)
9302 obp--;
9303 bcopy (ibp, obp, length);
9304 ibp += length;
9305 obp += length;
9307 else
9308 ibp++;
9309 #endif
9313 break;
9317 return obp - start;
9320 /* my_strerror - return the descriptive text associated with an
9321 `errno' code. */
9323 static char *
9324 my_strerror (errnum)
9325 int errnum;
9327 char *result;
9329 #ifndef VMS
9330 #ifndef HAVE_STRERROR
9331 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
9332 #else
9333 result = strerror (errnum);
9334 #endif
9335 #else /* VMS */
9336 /* VAXCRTL's strerror() takes an optional second argument, which only
9337 matters when the first argument is EVMSERR. However, it's simplest
9338 just to pass it unconditionally. `vaxc$errno' is declared in
9339 <errno.h>, and maintained by the library in parallel with `errno'.
9340 We assume that caller's `errnum' either matches the last setting of
9341 `errno' by the library or else does not have the value `EVMSERR'. */
9343 result = strerror (errnum, vaxc$errno);
9344 #endif
9346 if (!result)
9347 result = "undocumented I/O error";
9349 return result;
9352 /* error - print error message and increment count of errors. */
9354 void
9355 error VPROTO ((char * msg, ...))
9357 #ifndef ANSI_PROTOTYPES
9358 char * msg;
9359 #endif
9360 va_list args;
9362 VA_START (args, msg);
9364 #ifndef ANSI_PROTOTYPES
9365 msg = va_arg (args, char *);
9366 #endif
9368 verror (msg, args);
9369 va_end (args);
9372 static void
9373 verror (msg, args)
9374 char *msg;
9375 va_list args;
9377 int i;
9378 FILE_BUF *ip = NULL;
9380 print_containing_files ();
9382 for (i = indepth; i >= 0; i--)
9383 if (instack[i].fname != NULL) {
9384 ip = &instack[i];
9385 break;
9388 if (ip != NULL) {
9389 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9390 fprintf (stderr, ":%d: ", ip->lineno);
9392 vfprintf (stderr, msg, args);
9393 fprintf (stderr, "\n");
9394 errors++;
9397 /* Error including a message from `errno'. */
9399 static void
9400 error_from_errno (name)
9401 char *name;
9403 int e = errno;
9404 int i;
9405 FILE_BUF *ip = NULL;
9407 print_containing_files ();
9409 for (i = indepth; i >= 0; i--)
9410 if (instack[i].fname != NULL) {
9411 ip = &instack[i];
9412 break;
9415 if (ip != NULL) {
9416 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9417 fprintf (stderr, ":%d: ", ip->lineno);
9420 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
9422 errors++;
9425 /* Print error message but don't count it. */
9427 void
9428 warning VPROTO ((char * msg, ...))
9430 #ifndef ANSI_PROTOTYPES
9431 char * msg;
9432 #endif
9433 va_list args;
9435 VA_START (args, msg);
9437 #ifndef ANSI_PROTOTYPES
9438 msg = va_arg (args, char *);
9439 #endif
9441 vwarning (msg, args);
9442 va_end (args);
9445 static void
9446 vwarning (msg, args)
9447 char *msg;
9448 va_list args;
9450 int i;
9451 FILE_BUF *ip = NULL;
9453 if (inhibit_warnings)
9454 return;
9456 if (warnings_are_errors)
9457 errors++;
9459 print_containing_files ();
9461 for (i = indepth; i >= 0; i--)
9462 if (instack[i].fname != NULL) {
9463 ip = &instack[i];
9464 break;
9467 if (ip != NULL) {
9468 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9469 fprintf (stderr, ":%d: ", ip->lineno);
9471 fprintf (stderr, "warning: ");
9472 vfprintf (stderr, msg, args);
9473 fprintf (stderr, "\n");
9476 static void
9477 error_with_line VPROTO ((int line, char * msg, ...))
9479 #ifndef ANSI_PROTOTYPES
9480 int line;
9481 char * msg;
9482 #endif
9483 va_list args;
9485 VA_START (args, msg);
9487 #ifndef ANSI_PROTOTYPES
9488 line = va_arg (args, int);
9489 msg = va_arg (args, char *);
9490 #endif
9492 verror_with_line (line, msg, args);
9493 va_end (args);
9496 static void
9497 verror_with_line (line, msg, args)
9498 int line;
9499 char *msg;
9500 va_list args;
9502 int i;
9503 FILE_BUF *ip = NULL;
9505 print_containing_files ();
9507 for (i = indepth; i >= 0; i--)
9508 if (instack[i].fname != NULL) {
9509 ip = &instack[i];
9510 break;
9513 if (ip != NULL) {
9514 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9515 fprintf (stderr, ":%d: ", line);
9517 vfprintf (stderr, msg, args);
9518 fprintf (stderr, "\n");
9519 errors++;
9522 static void
9523 warning_with_line VPROTO ((int line, char * msg, ...))
9525 #ifndef ANSI_PROTOTYPES
9526 int line;
9527 char * msg;
9528 #endif
9529 va_list args;
9531 VA_START (args, msg);
9533 #ifndef ANSI_PROTOTYPES
9534 line = va_arg (args, int);
9535 msg = va_arg (args, char *);
9536 #endif
9538 vwarning_with_line (line, msg, args);
9539 va_end (args);
9542 static void
9543 vwarning_with_line (line, msg, args)
9544 int line;
9545 char *msg;
9546 va_list args;
9548 int i;
9549 FILE_BUF *ip = NULL;
9551 if (inhibit_warnings)
9552 return;
9554 if (warnings_are_errors)
9555 errors++;
9557 print_containing_files ();
9559 for (i = indepth; i >= 0; i--)
9560 if (instack[i].fname != NULL) {
9561 ip = &instack[i];
9562 break;
9565 if (ip != NULL) {
9566 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9567 fprintf (stderr, line ? ":%d: " : ": ", line);
9569 fprintf (stderr, "warning: ");
9570 vfprintf (stderr, msg, args);
9571 fprintf (stderr, "\n");
9574 /* Print an error message and maybe count it. */
9576 void
9577 pedwarn VPROTO ((char * msg, ...))
9579 #ifndef ANSI_PROTOTYPES
9580 char * msg;
9581 #endif
9582 va_list args;
9584 VA_START (args, msg);
9586 #ifndef ANSI_PROTOTYPES
9587 msg = va_arg (args, char *);
9588 #endif
9590 if (pedantic_errors)
9591 verror (msg, args);
9592 else
9593 vwarning (msg, args);
9594 va_end (args);
9597 void
9598 pedwarn_with_line VPROTO ((int line, char * msg, ...))
9600 #ifndef ANSI_PROTOTYPES
9601 int line;
9602 char * msg;
9603 #endif
9604 va_list args;
9606 VA_START (args, msg);
9608 #ifndef ANSI_PROTOTYPES
9609 line = va_arg (args, int);
9610 msg = va_arg (args, char *);
9611 #endif
9613 if (pedantic_errors)
9614 verror_with_line (line, msg, args);
9615 else
9616 vwarning_with_line (line, msg, args);
9617 va_end (args);
9620 /* Report a warning (or an error if pedantic_errors)
9621 giving specified file name and line number, not current. */
9623 static void
9624 pedwarn_with_file_and_line VPROTO ((char *file, size_t file_len, int line,
9625 char * msg, ...))
9627 #ifndef ANSI_PROTOTYPES
9628 char *file;
9629 size_t file_len;
9630 int line;
9631 char * msg;
9632 #endif
9633 va_list args;
9635 if (!pedantic_errors && inhibit_warnings)
9636 return;
9638 VA_START (args, msg);
9640 #ifndef ANSI_PROTOTYPES
9641 file = va_arg (args, char *);
9642 file_len = va_arg (args, size_t);
9643 line = va_arg (args, int);
9644 msg = va_arg (args, char *);
9645 #endif
9647 if (file) {
9648 eprint_string (file, file_len);
9649 fprintf (stderr, ":%d: ", line);
9651 if (pedantic_errors)
9652 errors++;
9653 if (!pedantic_errors)
9654 fprintf (stderr, "warning: ");
9656 vfprintf (stderr, msg, args);
9657 va_end (args);
9658 fprintf (stderr, "\n");
9661 /* Print the file names and line numbers of the #include
9662 directives which led to the current file. */
9664 static void
9665 print_containing_files ()
9667 FILE_BUF *ip = NULL;
9668 int i;
9669 int first = 1;
9671 /* If stack of files hasn't changed since we last printed
9672 this info, don't repeat it. */
9673 if (last_error_tick == input_file_stack_tick)
9674 return;
9676 for (i = indepth; i >= 0; i--)
9677 if (instack[i].fname != NULL) {
9678 ip = &instack[i];
9679 break;
9682 /* Give up if we don't find a source file. */
9683 if (ip == NULL)
9684 return;
9686 /* Find the other, outer source files. */
9687 for (i--; i >= 0; i--)
9688 if (instack[i].fname != NULL) {
9689 ip = &instack[i];
9690 if (first) {
9691 first = 0;
9692 fprintf (stderr, "In file included");
9693 } else {
9694 fprintf (stderr, ",\n ");
9697 fprintf (stderr, " from ");
9698 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9699 fprintf (stderr, ":%d", ip->lineno);
9701 if (! first)
9702 fprintf (stderr, ":\n");
9704 /* Record we have printed the status as of this time. */
9705 last_error_tick = input_file_stack_tick;
9708 /* Return the line at which an error occurred.
9709 The error is not necessarily associated with the current spot
9710 in the input stack, so LINE says where. LINE will have been
9711 copied from ip->lineno for the current input level.
9712 If the current level is for a file, we return LINE.
9713 But if the current level is not for a file, LINE is meaningless.
9714 In that case, we return the lineno of the innermost file. */
9716 static int
9717 line_for_error (line)
9718 int line;
9720 int i;
9721 int line1 = line;
9723 for (i = indepth; i >= 0; ) {
9724 if (instack[i].fname != 0)
9725 return line1;
9726 i--;
9727 if (i < 0)
9728 return 0;
9729 line1 = instack[i].lineno;
9731 abort ();
9732 /*NOTREACHED*/
9733 return 0;
9737 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9739 * As things stand, nothing is ever placed in the output buffer to be
9740 * removed again except when it's KNOWN to be part of an identifier,
9741 * so flushing and moving down everything left, instead of expanding,
9742 * should work ok.
9745 /* You might think void was cleaner for the return type,
9746 but that would get type mismatch in check_expand in strict ANSI. */
9748 static int
9749 grow_outbuf (obuf, needed)
9750 register FILE_BUF *obuf;
9751 register int needed;
9753 register U_CHAR *p;
9754 int minsize;
9756 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9757 return 0;
9759 /* Make it at least twice as big as it is now. */
9760 obuf->length *= 2;
9761 /* Make it have at least 150% of the free space we will need. */
9762 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9763 if (minsize > obuf->length)
9764 obuf->length = minsize;
9766 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9767 memory_full ();
9769 obuf->bufp = p + (obuf->bufp - obuf->buf);
9770 obuf->buf = p;
9772 return 0;
9775 /* Symbol table for macro names and special symbols */
9778 * install a name in the main hash table, even if it is already there.
9779 * name stops with first non alphanumeric, except leading '#'.
9780 * caller must check against redefinition if that is desired.
9781 * delete_macro () removes things installed by install () in fifo order.
9782 * this is important because of the `defined' special symbol used
9783 * in #if, and also if pushdef/popdef directives are ever implemented.
9785 * If LEN is >= 0, it is the length of the name.
9786 * Otherwise, compute the length by scanning the entire name.
9788 * If HASH is >= 0, it is the precomputed hash code.
9789 * Otherwise, compute the hash code.
9792 static HASHNODE *
9793 install (name, len, type, value, hash)
9794 U_CHAR *name;
9795 int len;
9796 enum node_type type;
9797 char *value;
9798 int hash;
9800 register HASHNODE *hp;
9801 register int i, bucket;
9802 register U_CHAR *p, *q;
9804 if (len < 0) {
9805 p = name;
9806 while (is_idchar[*p])
9807 p++;
9808 len = p - name;
9811 if (hash < 0)
9812 hash = hashf (name, len, HASHSIZE);
9814 i = sizeof (HASHNODE) + len + 1;
9815 hp = (HASHNODE *) xmalloc (i);
9816 bucket = hash;
9817 hp->bucket_hdr = &hashtab[bucket];
9818 hp->next = hashtab[bucket];
9819 hashtab[bucket] = hp;
9820 hp->prev = NULL;
9821 if (hp->next != NULL)
9822 hp->next->prev = hp;
9823 hp->type = type;
9824 hp->length = len;
9825 hp->value.cpval = value;
9826 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9827 p = hp->name;
9828 q = name;
9829 for (i = 0; i < len; i++)
9830 *p++ = *q++;
9831 hp->name[len] = 0;
9832 return hp;
9836 * find the most recent hash node for name "name" (ending with first
9837 * non-identifier char) installed by install
9839 * If LEN is >= 0, it is the length of the name.
9840 * Otherwise, compute the length by scanning the entire name.
9842 * If HASH is >= 0, it is the precomputed hash code.
9843 * Otherwise, compute the hash code.
9846 HASHNODE *
9847 lookup (name, len, hash)
9848 U_CHAR *name;
9849 int len;
9850 int hash;
9852 register U_CHAR *bp;
9853 register HASHNODE *bucket;
9855 if (len < 0) {
9856 for (bp = name; is_idchar[*bp]; bp++) ;
9857 len = bp - name;
9860 if (hash < 0)
9861 hash = hashf (name, len, HASHSIZE);
9863 bucket = hashtab[hash];
9864 while (bucket) {
9865 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9866 return bucket;
9867 bucket = bucket->next;
9869 return NULL;
9873 * Delete a hash node. Some weirdness to free junk from macros.
9874 * More such weirdness will have to be added if you define more hash
9875 * types that need it.
9878 /* Note that the DEFINITION of a macro is removed from the hash table
9879 but its storage is not freed. This would be a storage leak
9880 except that it is not reasonable to keep undefining and redefining
9881 large numbers of macros many times.
9882 In any case, this is necessary, because a macro can be #undef'd
9883 in the middle of reading the arguments to a call to it.
9884 If #undef freed the DEFINITION, that would crash. */
9886 static void
9887 delete_macro (hp)
9888 HASHNODE *hp;
9891 if (hp->prev != NULL)
9892 hp->prev->next = hp->next;
9893 if (hp->next != NULL)
9894 hp->next->prev = hp->prev;
9896 /* Make sure that the bucket chain header that the deleted guy was
9897 on points to the right thing afterwards. */
9898 if (hp == *hp->bucket_hdr)
9899 *hp->bucket_hdr = hp->next;
9901 #if 0
9902 if (hp->type == T_MACRO) {
9903 DEFINITION *d = hp->value.defn;
9904 struct reflist *ap, *nextap;
9906 for (ap = d->pattern; ap != NULL; ap = nextap) {
9907 nextap = ap->next;
9908 free (ap);
9910 free (d);
9912 #endif
9913 free (hp);
9917 * return hash function on name. must be compatible with the one
9918 * computed a step at a time, elsewhere
9921 static int
9922 hashf (name, len, hashsize)
9923 register U_CHAR *name;
9924 register int len;
9925 int hashsize;
9927 register int r = 0;
9929 while (len--)
9930 r = HASHSTEP (r, *name++);
9932 return MAKE_POS (r) % hashsize;
9936 /* Dump the definition of a single macro HP to OF. */
9938 static void
9939 dump_single_macro (hp, of)
9940 register HASHNODE *hp;
9941 FILE *of;
9943 register DEFINITION *defn = hp->value.defn;
9944 struct reflist *ap;
9945 int offset;
9946 int concat;
9949 /* Print the definition of the macro HP. */
9951 fprintf (of, "#define %s", hp->name);
9953 if (defn->nargs >= 0) {
9954 int i;
9956 fprintf (of, "(");
9957 for (i = 0; i < defn->nargs; i++) {
9958 dump_arg_n (defn, i, of);
9959 if (i + 1 < defn->nargs)
9960 fprintf (of, ", ");
9962 fprintf (of, ")");
9965 fprintf (of, " ");
9967 offset = 0;
9968 concat = 0;
9969 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9970 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9971 offset += ap->nchars;
9972 if (!traditional) {
9973 if (ap->nchars != 0)
9974 concat = 0;
9975 if (ap->stringify) {
9976 switch (ap->stringify) {
9977 case SHARP_TOKEN: fprintf (of, "#"); break;
9978 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9979 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9980 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9981 default: abort ();
9984 if (ap->raw_before != 0) {
9985 if (concat) {
9986 switch (ap->raw_before) {
9987 case WHITE_SHARP_TOKEN:
9988 case WHITE_PERCENT_COLON_TOKEN:
9989 fprintf (of, " ");
9990 break;
9991 default:
9992 break;
9994 } else {
9995 switch (ap->raw_before) {
9996 case SHARP_TOKEN: fprintf (of, "##"); break;
9997 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9998 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9999 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
10000 default: abort ();
10004 concat = 0;
10006 dump_arg_n (defn, ap->argno, of);
10007 if (!traditional && ap->raw_after != 0) {
10008 switch (ap->raw_after) {
10009 case SHARP_TOKEN: fprintf (of, "##"); break;
10010 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
10011 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
10012 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
10013 default: abort ();
10015 concat = 1;
10018 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
10019 fprintf (of, "\n");
10022 /* Dump all macro definitions as #defines to stdout. */
10024 static void
10025 dump_all_macros ()
10027 int bucket;
10029 for (bucket = 0; bucket < HASHSIZE; bucket++) {
10030 register HASHNODE *hp;
10032 for (hp = hashtab[bucket]; hp; hp= hp->next) {
10033 if (hp->type == T_MACRO)
10034 dump_single_macro (hp, stdout);
10039 /* Output to OF a substring of a macro definition.
10040 BASE is the beginning of the definition.
10041 Output characters START thru LENGTH.
10042 Unless traditional, discard newlines outside of strings, thus
10043 converting funny-space markers to ordinary spaces. */
10045 static void
10046 dump_defn_1 (base, start, length, of)
10047 U_CHAR *base;
10048 int start;
10049 int length;
10050 FILE *of;
10052 U_CHAR *p = base + start;
10053 U_CHAR *limit = base + start + length;
10055 if (traditional)
10056 fwrite (p, sizeof (*p), length, of);
10057 else {
10058 while (p < limit) {
10059 if (*p == '\"' || *p =='\'') {
10060 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
10061 NULL_PTR, NULL_PTR);
10062 fwrite (p, sizeof (*p), p1 - p, of);
10063 p = p1;
10064 } else {
10065 if (*p != '\n')
10066 putc (*p, of);
10067 p++;
10073 /* Print the name of argument number ARGNUM of macro definition DEFN
10074 to OF.
10075 Recall that DEFN->args.argnames contains all the arg names
10076 concatenated in reverse order with comma-space in between. */
10078 static void
10079 dump_arg_n (defn, argnum, of)
10080 DEFINITION *defn;
10081 int argnum;
10082 FILE *of;
10084 register U_CHAR *p = defn->args.argnames;
10085 while (argnum + 1 < defn->nargs) {
10086 p = (U_CHAR *) index ((char *) p, ' ') + 1;
10087 argnum++;
10090 while (*p && *p != ',') {
10091 putc (*p, of);
10092 p++;
10096 /* Initialize syntactic classifications of characters. */
10098 static void
10099 initialize_char_syntax ()
10101 register int i;
10104 * Set up is_idchar and is_idstart tables. These should be
10105 * faster than saying (is_alpha (c) || c == '_'), etc.
10106 * Set up these things before calling any routines tthat
10107 * refer to them.
10109 for (i = 'a'; i <= 'z'; i++) {
10110 is_idchar[i - 'a' + 'A'] = 1;
10111 is_idchar[i] = 1;
10112 is_idstart[i - 'a' + 'A'] = 1;
10113 is_idstart[i] = 1;
10115 for (i = '0'; i <= '9'; i++)
10116 is_idchar[i] = 1;
10117 is_idchar['_'] = 1;
10118 is_idstart['_'] = 1;
10119 is_idchar['$'] = 1;
10120 is_idstart['$'] = 1;
10122 /* horizontal space table */
10123 is_hor_space[' '] = 1;
10124 is_hor_space['\t'] = 1;
10125 is_hor_space['\v'] = 1;
10126 is_hor_space['\f'] = 1;
10127 is_hor_space['\r'] = 1;
10129 is_space[' '] = 1;
10130 is_space['\t'] = 1;
10131 is_space['\v'] = 1;
10132 is_space['\f'] = 1;
10133 is_space['\n'] = 1;
10134 is_space['\r'] = 1;
10136 char_name['\v'] = "vertical tab";
10137 char_name['\f'] = "formfeed";
10138 char_name['\r'] = "carriage return";
10141 /* Initialize the built-in macros. */
10143 static void
10144 initialize_builtins (inp, outp)
10145 FILE_BUF *inp;
10146 FILE_BUF *outp;
10148 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
10149 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
10150 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
10151 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
10152 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
10153 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
10154 #ifndef NO_BUILTIN_SIZE_TYPE
10155 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
10156 #endif
10157 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10158 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
10159 #endif
10160 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
10161 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
10162 NULL_PTR, -1);
10163 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
10164 NULL_PTR, -1);
10165 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
10166 NULL_PTR, -1);
10167 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
10168 if (!traditional) {
10169 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
10170 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
10172 if (objc)
10173 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
10174 /* This is supplied using a -D by the compiler driver
10175 so that it is present only when truly compiling with GNU C. */
10176 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
10177 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
10179 if (debug_output)
10181 char directive[2048];
10182 U_CHAR *udirective = (U_CHAR *) directive;
10183 register struct directive *dp = &directive_table[0];
10184 struct tm *timebuf = timestamp ();
10186 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
10187 instack[0].nominal_fname);
10188 output_line_directive (inp, outp, 0, same_file);
10189 pass_thru_directive (udirective, &udirective[strlen (directive)],
10190 outp, dp);
10192 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
10193 output_line_directive (inp, outp, 0, same_file);
10194 pass_thru_directive (udirective, &udirective[strlen (directive)],
10195 outp, dp);
10197 #ifndef NO_BUILTIN_SIZE_TYPE
10198 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
10199 output_line_directive (inp, outp, 0, same_file);
10200 pass_thru_directive (udirective, &udirective[strlen (directive)],
10201 outp, dp);
10202 #endif
10204 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10205 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
10206 output_line_directive (inp, outp, 0, same_file);
10207 pass_thru_directive (udirective, &udirective[strlen (directive)],
10208 outp, dp);
10209 #endif
10211 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
10212 output_line_directive (inp, outp, 0, same_file);
10213 pass_thru_directive (udirective, &udirective[strlen (directive)],
10214 outp, dp);
10216 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
10217 monthnames[timebuf->tm_mon],
10218 timebuf->tm_mday, timebuf->tm_year + 1900);
10219 output_line_directive (inp, outp, 0, same_file);
10220 pass_thru_directive (udirective, &udirective[strlen (directive)],
10221 outp, dp);
10223 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
10224 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
10225 output_line_directive (inp, outp, 0, same_file);
10226 pass_thru_directive (udirective, &udirective[strlen (directive)],
10227 outp, dp);
10229 if (!traditional)
10231 sprintf (directive, " __STDC__ 1");
10232 output_line_directive (inp, outp, 0, same_file);
10233 pass_thru_directive (udirective, &udirective[strlen (directive)],
10234 outp, dp);
10236 if (objc)
10238 sprintf (directive, " __OBJC__ 1");
10239 output_line_directive (inp, outp, 0, same_file);
10240 pass_thru_directive (udirective, &udirective[strlen (directive)],
10241 outp, dp);
10247 * process a given definition string, for initialization
10248 * If STR is just an identifier, define it with value 1.
10249 * If STR has anything after the identifier, then it should
10250 * be identifier=definition.
10253 static void
10254 make_definition (str)
10255 char *str;
10257 FILE_BUF *ip;
10258 struct directive *kt;
10259 U_CHAR *buf, *p;
10261 p = buf = (U_CHAR *) str;
10262 if (!is_idstart[*p]) {
10263 error ("malformed option `-D %s'", str);
10264 return;
10266 while (is_idchar[*++p])
10268 if (*p == '(') {
10269 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
10271 if (*p++ != ')')
10272 p = (U_CHAR *) str; /* Error */
10274 if (*p == 0) {
10275 buf = (U_CHAR *) alloca (p - buf + 4);
10276 strcpy ((char *)buf, str);
10277 strcat ((char *)buf, " 1");
10278 } else if (*p != '=') {
10279 error ("malformed option `-D %s'", str);
10280 return;
10281 } else {
10282 U_CHAR *q;
10283 /* Copy the entire option so we can modify it. */
10284 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
10285 strncpy ((char *) buf, str, p - (U_CHAR *) str);
10286 /* Change the = to a space. */
10287 buf[p - (U_CHAR *) str] = ' ';
10288 /* Scan for any backslash-newline and remove it. */
10289 p++;
10290 q = &buf[p - (U_CHAR *) str];
10291 while (*p) {
10292 if (*p == '\"' || *p == '\'') {
10293 int unterminated = 0;
10294 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
10295 NULL_PTR, NULL_PTR, &unterminated);
10296 if (unterminated)
10297 return;
10298 while (p != p1)
10299 *q++ = *p++;
10300 } else if (*p == '\\' && p[1] == '\n')
10301 p += 2;
10302 /* Change newline chars into newline-markers. */
10303 else if (*p == '\n')
10305 *q++ = '\n';
10306 *q++ = '\n';
10307 p++;
10309 else
10310 *q++ = *p++;
10312 *q = 0;
10315 ip = &instack[++indepth];
10316 ip->nominal_fname = ip->fname = "*Initialization*";
10317 ip->nominal_fname_len = strlen (ip->nominal_fname);
10319 ip->buf = ip->bufp = buf;
10320 ip->length = strlen ((char *) buf);
10321 ip->lineno = 1;
10322 ip->macro = 0;
10323 ip->free_ptr = 0;
10324 ip->if_stack = if_stack;
10325 ip->system_header_p = 0;
10327 for (kt = directive_table; kt->type != T_DEFINE; kt++)
10330 /* Pass NULL instead of OP, since this is a "predefined" macro. */
10331 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
10332 --indepth;
10335 /* JF, this does the work for the -U option */
10337 static void
10338 make_undef (str, op)
10339 char *str;
10340 FILE_BUF *op;
10342 FILE_BUF *ip;
10343 struct directive *kt;
10345 ip = &instack[++indepth];
10346 ip->nominal_fname = ip->fname = "*undef*";
10347 ip->nominal_fname_len = strlen (ip->nominal_fname);
10349 ip->buf = ip->bufp = (U_CHAR *) str;
10350 ip->length = strlen (str);
10351 ip->lineno = 1;
10352 ip->macro = 0;
10353 ip->free_ptr = 0;
10354 ip->if_stack = if_stack;
10355 ip->system_header_p = 0;
10357 for (kt = directive_table; kt->type != T_UNDEF; kt++)
10360 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
10361 --indepth;
10364 /* Process the string STR as if it appeared as the body of a #assert.
10365 OPTION is the option name for which STR was the argument. */
10367 static void
10368 make_assertion (option, str)
10369 char *option;
10370 char *str;
10372 FILE_BUF *ip;
10373 struct directive *kt;
10374 U_CHAR *buf, *p, *q;
10376 /* Copy the entire option so we can modify it. */
10377 buf = (U_CHAR *) alloca (strlen (str) + 1);
10378 strcpy ((char *) buf, str);
10379 /* Scan for any backslash-newline and remove it. */
10380 p = q = buf;
10381 while (*p) {
10382 if (*p == '\\' && p[1] == '\n')
10383 p += 2;
10384 else
10385 *q++ = *p++;
10387 *q = 0;
10389 p = buf;
10390 if (!is_idstart[*p]) {
10391 error ("malformed option `%s %s'", option, str);
10392 return;
10394 while (is_idchar[*++p])
10396 SKIP_WHITE_SPACE (p);
10397 if (! (*p == 0 || *p == '(')) {
10398 error ("malformed option `%s %s'", option, str);
10399 return;
10402 ip = &instack[++indepth];
10403 ip->nominal_fname = ip->fname = "*Initialization*";
10404 ip->nominal_fname_len = strlen (ip->nominal_fname);
10406 ip->buf = ip->bufp = buf;
10407 ip->length = strlen ((char *) buf);
10408 ip->lineno = 1;
10409 ip->macro = 0;
10410 ip->free_ptr = 0;
10411 ip->if_stack = if_stack;
10412 ip->system_header_p = 0;
10414 for (kt = directive_table; kt->type != T_ASSERT; kt++)
10417 /* Pass NULL as output ptr to do_define since we KNOW it never does
10418 any output.... */
10419 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
10420 --indepth;
10423 #ifndef DIR_SEPARATOR
10424 #define DIR_SEPARATOR '/'
10425 #endif
10427 /* The previous include prefix, if any, is PREV_FILE_NAME.
10428 Translate any pathnames with COMPONENT.
10429 Allocate a new include prefix whose name is the
10430 simplified concatenation of PREFIX and NAME,
10431 with a trailing / added if needed.
10432 But return 0 if the include prefix should be ignored,
10433 e.g. because it is a duplicate of PREV_FILE_NAME. */
10435 static struct file_name_list *
10436 new_include_prefix (prev_file_name, component, prefix, name)
10437 struct file_name_list *prev_file_name;
10438 const char *component;
10439 const char *prefix;
10440 const char *name;
10442 if (name == 0)
10443 fatal ("Directory name missing after command line option");
10445 if (*name == 0)
10446 /* Ignore the empty string. */
10447 return 0;
10449 prefix = update_path (prefix, component);
10450 name = update_path (name, component);
10453 struct file_name_list *dir
10454 = ((struct file_name_list *)
10455 xmalloc (sizeof (struct file_name_list)
10456 + strlen (prefix) + strlen (name) + 2));
10457 size_t len;
10458 strcpy (dir->fname, prefix);
10459 strcat (dir->fname, name);
10460 len = simplify_filename (dir->fname);
10462 /* Convert directory name to a prefix. */
10463 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10464 if (len == 1 && dir->fname[len - 1] == '.')
10465 len = 0;
10466 else
10467 #ifdef VMS
10468 /* must be '/', hack_vms_include_specification triggers on it. */
10469 dir->fname[len++] = '/';
10470 #else
10471 dir->fname[len++] = DIR_SEPARATOR;
10472 #endif
10473 dir->fname[len] = 0;
10476 /* Ignore a directory whose name matches the previous one. */
10477 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10478 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10479 if (!first_bracket_include)
10480 first_bracket_include = prev_file_name;
10481 free (dir);
10482 return 0;
10485 #ifndef VMS
10486 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10488 /* Add a trailing "." if there is a filename. This increases the number
10489 of systems that can stat directories. We remove it below. */
10490 if (len != 0)
10492 dir->fname[len] = '.';
10493 dir->fname[len + 1] = 0;
10496 /* Ignore a nonexistent directory. */
10497 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10498 if (errno != ENOENT && errno != ENOTDIR)
10499 error_from_errno (dir->fname);
10500 free (dir);
10501 return 0;
10504 if (len != 0)
10505 dir->fname[len] = 0;
10507 /* Ignore a directory whose identity matches the previous one. */
10508 if (prev_file_name
10509 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10510 && prev_file_name->st.st_dev == dir->st.st_dev) {
10511 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10512 if (!first_bracket_include)
10513 first_bracket_include = prev_file_name;
10514 free (dir);
10515 return 0;
10517 #endif /* ! VMS */
10519 dir->next = 0;
10520 dir->c_system_include_path = 0;
10521 dir->got_name_map = 0;
10523 return dir;
10527 /* Append a chain of `struct file_name_list's
10528 to the end of the main include chain.
10529 FIRST is the beginning of the chain to append, and LAST is the end. */
10531 static void
10532 append_include_chain (first, last)
10533 struct file_name_list *first, *last;
10535 struct file_name_list *dir;
10537 if (!first || !last)
10538 return;
10540 if (include == 0)
10541 include = first;
10542 else
10543 last_include->next = first;
10545 if (first_bracket_include == 0)
10546 first_bracket_include = first;
10548 for (dir = first; ; dir = dir->next) {
10549 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10550 if (len > max_include_len)
10551 max_include_len = len;
10552 if (dir == last)
10553 break;
10556 last->next = NULL;
10557 last_include = last;
10560 /* Place into DST a representation of the file named SRC that is suitable
10561 for `make'. Do not null-terminate DST. Return its length. */
10562 static int
10563 quote_string_for_make (dst, src)
10564 char *dst;
10565 char *src;
10567 char *p = src;
10568 int i = 0;
10569 for (;;)
10571 char c = *p++;
10572 switch (c)
10574 case '\0':
10575 case ' ':
10576 case '\t':
10578 /* GNU make uses a weird quoting scheme for white space.
10579 A space or tab preceded by 2N+1 backslashes represents
10580 N backslashes followed by space; a space or tab
10581 preceded by 2N backslashes represents N backslashes at
10582 the end of a file name; and backslashes in other
10583 contexts should not be doubled. */
10584 char *q;
10585 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10587 if (dst)
10588 dst[i] = '\\';
10589 i++;
10592 if (!c)
10593 return i;
10594 if (dst)
10595 dst[i] = '\\';
10596 i++;
10597 goto ordinary_char;
10599 case '$':
10600 if (dst)
10601 dst[i] = c;
10602 i++;
10603 /* Fall through. This can mishandle things like "$(" but
10604 there's no easy fix. */
10605 default:
10606 ordinary_char:
10607 /* This can mishandle characters in the string "\0\n%*?[\\~";
10608 exactly which chars are mishandled depends on the `make' version.
10609 We know of no portable solution for this;
10610 even GNU make 3.76.1 doesn't solve the problem entirely.
10611 (Also, '\0' is mishandled due to our calling conventions.) */
10612 if (dst)
10613 dst[i] = c;
10614 i++;
10615 break;
10621 /* Add output to `deps_buffer' for the -M switch.
10622 STRING points to the text to be output.
10623 SPACER is ':' for targets, ' ' for dependencies. */
10625 static void
10626 deps_output (string, spacer)
10627 char *string;
10628 int spacer;
10630 int size = quote_string_for_make ((char *) 0, string);
10632 if (size == 0)
10633 return;
10635 #ifndef MAX_OUTPUT_COLUMNS
10636 #define MAX_OUTPUT_COLUMNS 72
10637 #endif
10638 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10639 && 1 < deps_column) {
10640 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10641 deps_size += 4;
10642 deps_column = 1;
10643 if (spacer == ' ')
10644 spacer = 0;
10647 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10648 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10649 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10651 if (spacer == ' ') {
10652 deps_buffer[deps_size++] = ' ';
10653 deps_column++;
10655 quote_string_for_make (&deps_buffer[deps_size], string);
10656 deps_size += size;
10657 deps_column += size;
10658 if (spacer == ':') {
10659 deps_buffer[deps_size++] = ':';
10660 deps_column++;
10662 deps_buffer[deps_size] = 0;
10665 static void
10666 fatal VPROTO ((char * msg, ...))
10668 #ifndef ANSI_PROTOTYPES
10669 char * msg;
10670 #endif
10671 va_list args;
10673 fprintf (stderr, "%s: ", progname);
10674 VA_START (args, msg);
10676 #ifndef ANSI_PROTOTYPES
10677 msg = va_arg (args, char *);
10678 #endif
10680 vfprintf (stderr, msg, args);
10681 va_end (args);
10682 fprintf (stderr, "\n");
10683 exit (FATAL_EXIT_CODE);
10686 /* More 'friendly' abort that prints the line and file.
10687 config.h can #define abort fancy_abort if you like that sort of thing. */
10689 void
10690 fancy_abort ()
10692 fatal ("Internal gcc abort.");
10695 static void
10696 perror_with_name (name)
10697 char *name;
10699 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10700 errors++;
10703 static void
10704 pfatal_with_name (name)
10705 char *name;
10707 perror_with_name (name);
10708 #ifdef VMS
10709 exit (vaxc$errno);
10710 #else
10711 exit (FATAL_EXIT_CODE);
10712 #endif
10715 /* Handler for SIGPIPE. */
10717 static void
10718 pipe_closed (signo)
10719 /* If this is missing, some compilers complain. */
10720 int signo ATTRIBUTE_UNUSED;
10722 fatal ("output pipe has been closed");
10725 static void
10726 memory_full ()
10728 fatal ("Memory exhausted.");
10732 xmalloc (size)
10733 size_t size;
10735 register PTR ptr = (PTR) malloc (size);
10736 if (!ptr)
10737 memory_full ();
10738 return ptr;
10742 xrealloc (old, size)
10743 PTR old;
10744 size_t size;
10746 register PTR ptr = (PTR) realloc (old, size);
10747 if (!ptr)
10748 memory_full ();
10749 return ptr;
10753 xcalloc (number, size)
10754 size_t number, size;
10756 register size_t total = number * size;
10757 register PTR ptr = (PTR) malloc (total);
10758 if (!ptr)
10759 memory_full ();
10760 bzero (ptr, total);
10761 return ptr;
10764 char *
10765 xstrdup (input)
10766 const char *input;
10768 register size_t len = strlen (input) + 1;
10769 register char *output = xmalloc (len);
10770 memcpy (output, input, len);
10771 return output;
10774 #ifdef VMS
10776 /* Under VMS we need to fix up the "include" specification filename.
10778 Rules for possible conversions
10780 fullname tried paths
10782 name name
10783 ./dir/name [.dir]name
10784 /dir/name dir:name
10785 /name [000000]name, name
10786 dir/name dir:[000000]name, dir:name, dir/name
10787 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10788 path:/name path:[000000]name, path:name
10789 path:/dir/name path:[000000.dir]name, path:[dir]name
10790 path:dir/name path:[dir]name
10791 [path]:[dir]name [path.dir]name
10792 path/[dir]name [path.dir]name
10794 The path:/name input is constructed when expanding <> includes.
10796 return 1 if name was changed, 0 else. */
10798 static int
10799 hack_vms_include_specification (fullname, vaxc_include)
10800 char *fullname;
10801 int vaxc_include;
10803 register char *basename, *unixname, *local_ptr, *first_slash;
10804 int f, check_filename_before_returning, must_revert;
10805 char Local[512];
10807 check_filename_before_returning = 0;
10808 must_revert = 0;
10809 /* See if we can find a 1st slash. If not, there's no path information. */
10810 first_slash = index (fullname, '/');
10811 if (first_slash == 0)
10812 return 0; /* Nothing to do!!! */
10814 /* construct device spec if none given. */
10816 if (index (fullname, ':') == 0)
10819 /* If fullname has a slash, take it as device spec. */
10821 if (first_slash == fullname)
10823 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10824 if (first_slash)
10825 *first_slash = ':'; /* make device spec */
10826 for (basename = fullname; *basename != 0; basename++)
10827 *basename = *(basename+1); /* remove leading slash */
10829 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10830 && (first_slash[-1] != ':')
10831 && (first_slash[-1] != ']')) /* or a vms path */
10833 *first_slash = ':';
10835 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10836 && (first_slash[-1] == '.'))
10837 fullname += 2;
10840 /* Get part after first ':' (basename[-1] == ':')
10841 or last '/' (basename[-1] == '/'). */
10843 basename = base_name (fullname);
10846 * Check if we have a vax-c style '#include filename'
10847 * and add the missing .h
10850 if (vaxc_include && !index (basename,'.'))
10851 strcat (basename, ".h");
10853 local_ptr = Local; /* initialize */
10855 /* We are trying to do a number of things here. First of all, we are
10856 trying to hammer the filenames into a standard format, such that later
10857 processing can handle them.
10859 If the file name contains something like [dir.], then it recognizes this
10860 as a root, and strips the ".]". Later processing will add whatever is
10861 needed to get things working properly.
10863 If no device is specified, then the first directory name is taken to be
10864 a device name (or a rooted logical). */
10866 /* Point to the UNIX filename part (which needs to be fixed!)
10867 but skip vms path information.
10868 [basename != fullname since first_slash != 0]. */
10870 if ((basename[-1] == ':') /* vms path spec. */
10871 || (basename[-1] == ']')
10872 || (basename[-1] == '>'))
10873 unixname = basename;
10874 else
10875 unixname = fullname;
10877 if (*unixname == '/')
10878 unixname++;
10880 /* If the directory spec is not rooted, we can just copy
10881 the UNIX filename part and we are done. */
10883 if (((basename - fullname) > 1)
10884 && ( (basename[-1] == ']')
10885 || (basename[-1] == '>')))
10887 if (basename[-2] != '.')
10890 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10891 -> PATH]:/name (basename = '/name', unixname = 'name')
10892 We strip the `]', and then splice the two parts of the name in the
10893 usual way. Given the default locations for include files in cccp.c,
10894 we will only use this code if the user specifies alternate locations
10895 with the /include (-I) switch on the command line. */
10897 basename -= 1; /* Strip "]" */
10898 unixname--; /* backspace */
10900 else
10903 /* The VMS part has a ".]" at the end, and this will not do. Later
10904 processing will add a second directory spec, and this would be a syntax
10905 error. Thus we strip the ".]", and thus merge the directory specs.
10906 We also backspace unixname, so that it points to a '/'. This inhibits the
10907 generation of the 000000 root directory spec (which does not belong here
10908 in this case). */
10910 basename -= 2; /* Strip ".]" */
10911 unixname--; /* backspace */
10915 else
10919 /* We drop in here if there is no VMS style directory specification yet.
10920 If there is no device specification either, we make the first dir a
10921 device and try that. If we do not do this, then we will be essentially
10922 searching the users default directory (as if they did a #include "asdf.h").
10924 Then all we need to do is to push a '[' into the output string. Later
10925 processing will fill this in, and close the bracket. */
10927 if ((unixname != fullname) /* vms path spec found. */
10928 && (basename[-1] != ':'))
10929 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10931 *local_ptr++ = '['; /* Open the directory specification */
10934 if (unixname == fullname) /* no vms dir spec. */
10936 must_revert = 1;
10937 if ((first_slash != 0) /* unix dir spec. */
10938 && (*unixname != '/') /* not beginning with '/' */
10939 && (*unixname != '.')) /* or './' or '../' */
10940 *local_ptr++ = '.'; /* dir is local ! */
10943 /* at this point we assume that we have the device spec, and (at least
10944 the opening "[" for a directory specification. We may have directories
10945 specified already.
10947 If there are no other slashes then the filename will be
10948 in the "root" directory. Otherwise, we need to add
10949 directory specifications. */
10951 if (index (unixname, '/') == 0)
10953 /* if no directories specified yet and none are following. */
10954 if (local_ptr[-1] == '[')
10956 /* Just add "000000]" as the directory string */
10957 strcpy (local_ptr, "000000]");
10958 local_ptr += strlen (local_ptr);
10959 check_filename_before_returning = 1; /* we might need to fool with this later */
10962 else
10965 /* As long as there are still subdirectories to add, do them. */
10966 while (index (unixname, '/') != 0)
10968 /* If this token is "." we can ignore it
10969 if it's not at the beginning of a path. */
10970 if ((unixname[0] == '.') && (unixname[1] == '/'))
10972 /* remove it at beginning of path. */
10973 if ( ((unixname == fullname) /* no device spec */
10974 && (fullname+2 != basename)) /* starts with ./ */
10975 /* or */
10976 || ((basename[-1] == ':') /* device spec */
10977 && (unixname-1 == basename))) /* and ./ afterwards */
10978 *local_ptr++ = '.'; /* make '[.' start of path. */
10979 unixname += 2;
10980 continue;
10983 /* Add a subdirectory spec. Do not duplicate "." */
10984 if ( local_ptr[-1] != '.'
10985 && local_ptr[-1] != '['
10986 && local_ptr[-1] != '<')
10987 *local_ptr++ = '.';
10989 /* If this is ".." then the spec becomes "-" */
10990 if ( (unixname[0] == '.')
10991 && (unixname[1] == '.')
10992 && (unixname[2] == '/'))
10994 /* Add "-" and skip the ".." */
10995 if ((local_ptr[-1] == '.')
10996 && (local_ptr[-2] == '['))
10997 local_ptr--; /* prevent [.- */
10998 *local_ptr++ = '-';
10999 unixname += 3;
11000 continue;
11003 /* Copy the subdirectory */
11004 while (*unixname != '/')
11005 *local_ptr++= *unixname++;
11007 unixname++; /* Skip the "/" */
11010 /* Close the directory specification */
11011 if (local_ptr[-1] == '.') /* no trailing periods */
11012 local_ptr--;
11014 if (local_ptr[-1] == '[') /* no dir needed */
11015 local_ptr--;
11016 else
11017 *local_ptr++ = ']';
11020 /* Now add the filename. */
11022 while (*unixname)
11023 *local_ptr++ = *unixname++;
11024 *local_ptr = 0;
11026 /* Now append it to the original VMS spec. */
11028 strcpy ((must_revert==1)?fullname:basename, Local);
11030 /* If we put a [000000] in the filename, try to open it first. If this fails,
11031 remove the [000000], and return that name. This provides flexibility
11032 to the user in that they can use both rooted and non-rooted logical names
11033 to point to the location of the file. */
11035 if (check_filename_before_returning)
11037 f = open (fullname, O_RDONLY, 0666);
11038 if (f >= 0)
11040 /* The file name is OK as it is, so return it as is. */
11041 close (f);
11042 return 1;
11045 /* The filename did not work. Try to remove the [000000] from the name,
11046 and return it. */
11048 basename = index (fullname, '[');
11049 local_ptr = index (fullname, ']') + 1;
11050 strcpy (basename, local_ptr); /* this gets rid of it */
11054 return 1;
11056 #endif /* VMS */
11058 #ifdef VMS
11060 /* The following wrapper functions supply additional arguments to the VMS
11061 I/O routines to optimize performance with file handling. The arguments
11062 are:
11063 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
11064 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
11065 "fop=tef"- Truncate unused portions of file when closing file.
11066 "shr=nil"- Disallow file sharing while file is open. */
11068 static FILE *
11069 VMS_freopen (fname, type, oldfile)
11070 char *fname;
11071 char *type;
11072 FILE *oldfile;
11074 #undef freopen /* Get back the real freopen routine. */
11075 if (strcmp (type, "w") == 0)
11076 return freopen (fname, type, oldfile,
11077 "mbc=16", "deq=64", "fop=tef", "shr=nil");
11078 return freopen (fname, type, oldfile, "mbc=16");
11081 static FILE *
11082 VMS_fopen (fname, type)
11083 char *fname;
11084 char *type;
11086 #undef fopen /* Get back the real fopen routine. */
11087 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
11088 fixed arguments, which matches ANSI's specification but not VAXCRTL's
11089 pre-ANSI implementation. This hack circumvents the mismatch problem. */
11090 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
11092 if (*type == 'w')
11093 return (*vmslib_fopen) (fname, type, "mbc=32",
11094 "deq=64", "fop=tef", "shr=nil");
11095 else
11096 return (*vmslib_fopen) (fname, type, "mbc=32");
11099 static int
11100 VMS_open (fname, flags, prot)
11101 char *fname;
11102 int flags;
11103 int prot;
11105 #undef open /* Get back the real open routine. */
11106 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
11109 /* more VMS hackery */
11110 #include <fab.h>
11111 #include <nam.h>
11113 extern unsigned long SYS$PARSE(), SYS$SEARCH();
11115 /* Work around another library bug. If a file is located via a searchlist,
11116 and if the device it's on is not the same device as the one specified
11117 in the first element of that searchlist, then both stat() and fstat()
11118 will fail to return info about it. `errno' will be set to EVMSERR, and
11119 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
11120 We can get around this by fully parsing the filename and then passing
11121 that absolute name to stat().
11123 Without this fix, we can end up failing to find header files, which is
11124 bad enough, but then compounding the problem by reporting the reason for
11125 failure as "normal successful completion." */
11127 #undef fstat /* Get back to the library version. */
11129 static int
11130 VMS_fstat (fd, statbuf)
11131 int fd;
11132 struct stat *statbuf;
11134 int result = fstat (fd, statbuf);
11136 if (result < 0)
11138 FILE *fp;
11139 char nambuf[NAM$C_MAXRSS+1];
11141 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
11142 result = VMS_stat (nambuf, statbuf);
11143 /* No fclose(fp) here; that would close(fd) as well. */
11146 return result;
11149 static int
11150 VMS_stat (name, statbuf)
11151 const char *name;
11152 struct stat *statbuf;
11154 int result = stat (name, statbuf);
11156 if (result < 0)
11158 struct FAB fab;
11159 struct NAM nam;
11160 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
11161 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
11163 fab = cc$rms_fab;
11164 fab.fab$l_fna = (char *) name;
11165 fab.fab$b_fns = (unsigned char) strlen (name);
11166 fab.fab$l_nam = (void *) &nam;
11167 nam = cc$rms_nam;
11168 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
11169 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
11170 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
11171 if (SYS$PARSE (&fab) & 1)
11173 if (SYS$SEARCH (&fab) & 1)
11175 res_nam[nam.nam$b_rsl] = '\0';
11176 result = stat (res_nam, statbuf);
11178 /* Clean up searchlist context cached by the system. */
11179 nam.nam$b_nop = NAM$M_SYNCHK;
11180 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
11181 (void) SYS$PARSE (&fab);
11185 return result;
11187 #endif /* VMS */