1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-97, 1998 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
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. */
22 #if defined (__STDC__) && defined (HAVE_VPRINTF)
24 # define PRINTF_ALIST(msg) char *msg, ...
25 # define PRINTF_DCL(msg)
26 # define PRINTF_PROTO(ARGS, m, n) PROTO (ARGS) __attribute__ ((format (__printf__, m, n)))
29 # define PRINTF_ALIST(msg) msg, va_alist
30 # define PRINTF_DCL(msg) char *msg; va_dcl
31 # define PRINTF_PROTO(ARGS, m, n) () __attribute__ ((format (__printf__, m, n)))
32 # define vfprintf(file, msg, args) \
34 char *a0 = va_arg(args, char *); \
35 char *a1 = va_arg(args, char *); \
36 char *a2 = va_arg(args, char *); \
37 char *a3 = va_arg(args, char *); \
38 fprintf (file, msg, a0, a1, a2, a3); \
42 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
43 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
44 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
45 #define PRINTF_PROTO_4(ARGS) PRINTF_PROTO(ARGS, 4, 5)
51 #ifdef HAVE_SYS_RESOURCE_H
52 # include <sys/resource.h>
55 typedef unsigned char U_CHAR;
57 #include "gansidecl.h"
60 #ifndef GET_ENVIRONMENT
61 #define GET_ENVIRONMENT(ENV_VALUE,ENV_NAME) ENV_VALUE = getenv (ENV_NAME)
64 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
65 # define __attribute__(x)
68 #ifndef STANDARD_INCLUDE_DIR
69 # define STANDARD_INCLUDE_DIR "/usr/include"
72 /* By default, colon separates directories in a path. */
73 #ifndef PATH_SEPARATOR
74 # define PATH_SEPARATOR ':'
77 /* By default, the suffix for object files is ".o". */
79 # define HAVE_OBJECT_SUFFIX
81 # define OBJECT_SUFFIX ".o"
84 /* VMS-specific definitions */
89 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
90 #define fopen(fname,mode) VMS_fopen (fname,mode)
91 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
92 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
93 static int VMS_fstat (), VMS_stat ();
94 static int VMS_open ();
95 static FILE *VMS_fopen ();
96 static FILE *VMS_freopen ();
97 static void hack_vms_include_specification ();
98 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
99 #define INO_T_HASH(a) 0
100 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
103 /* Windows does not natively support inodes, and neither does MSDOS. */
104 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
105 #define INO_T_EQ(a, b) 0
110 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
111 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
113 /* Find the largest host integer type and set its size and type.
114 Watch out: on some crazy hosts `long' is shorter than `int'. */
116 #ifndef HOST_WIDE_INT
118 # include <inttypes.h>
119 # define HOST_WIDE_INT intmax_t
121 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
122 # define HOST_WIDE_INT int
124 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
125 # define HOST_WIDE_INT long
127 # define HOST_WIDE_INT long long
134 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
138 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
142 #define INO_T_EQ(a, b) ((a) == (b))
146 #define INO_T_HASH(a) (a)
149 #ifndef INCLUDE_LEN_FUDGE
150 #define INCLUDE_LEN_FUDGE 0
153 /* External declarations. */
155 extern char *version_string;
156 extern char *update_path PROTO((char *, char *));
158 #ifndef HAVE_STRERROR
160 extern char *sys_errlist[];
161 #else /* HAVE_STRERROR */
165 char *strerror (int,...);
167 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
168 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
170 /* Name under which this program was invoked. */
172 static char *progname;
174 /* Nonzero means use extra default include directories for C++. */
176 static int cplusplus;
178 /* Nonzero means handle cplusplus style comments */
180 static int cplusplus_comments;
182 /* Nonzero means handle #import, for objective C. */
186 /* Nonzero means this is an assembly file, and allow
187 unknown directives, which could be comments. */
191 /* Current maximum length of directory names in the search path
192 for include files. (Altered as we get more of them.) */
194 static int max_include_len;
196 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
198 static int for_lint = 0;
200 /* Nonzero means copy comments into the output file. */
202 static int put_out_comments = 0;
204 /* Nonzero means don't process the ANSI trigraph sequences. */
206 static int no_trigraphs = 0;
208 /* Nonzero means print the names of included files rather than
209 the preprocessed output. 1 means just the #include "...",
210 2 means #include <...> as well. */
212 static int print_deps = 0;
214 /* Nonzero if missing .h files in -M output are assumed to be generated
215 files and not errors. */
217 static int print_deps_missing_files = 0;
219 /* Nonzero means print names of header files (-H). */
221 static int print_include_names = 0;
223 /* Nonzero means don't output line number information. */
225 static int no_line_directives;
227 /* Nonzero means output the text in failing conditionals,
228 inside #failed ... #endfailed. */
230 static int output_conditionals;
232 /* dump_only means inhibit output of the preprocessed text
233 and instead output the definitions of all user-defined
234 macros in a form suitable for use as input to cccp.
235 dump_names means pass #define and the macro name through to output.
236 dump_definitions means pass the whole definition (plus #define) through
239 static enum {dump_none, dump_only, dump_names, dump_definitions}
240 dump_macros = dump_none;
242 /* Nonzero means pass all #define and #undef directives which we actually
243 process through to the output stream. This feature is used primarily
244 to allow cc1 to record the #defines and #undefs for the sake of
245 debuggers which understand about preprocessor macros, but it may
246 also be useful with -E to figure out how symbols are defined, and
247 where they are defined. */
248 static int debug_output = 0;
250 /* Nonzero means pass #include lines through to the output,
251 even if they are ifdefed out. */
252 static int dump_includes;
254 /* Nonzero indicates special processing used by the pcp program. The
255 special effects of this mode are:
257 Inhibit all macro expansion, except those inside #if directives.
259 Process #define directives normally, and output their contents
262 Output preconditions to pcp_outfile indicating all the relevant
263 preconditions for use of this file in a later cpp run.
265 static FILE *pcp_outfile;
267 /* Nonzero means we are inside an IF during a -pcp run. In this mode
268 macro expansion is done, and preconditions are output for all macro
269 uses requiring them. */
270 static int pcp_inside_if;
272 /* Nonzero means never to include precompiled files.
273 This is 1 since there's no way now to make precompiled files,
274 so it's not worth testing for them. */
275 static int no_precomp = 1;
277 /* Nonzero means give all the error messages the ANSI standard requires. */
281 /* Nonzero means try to make failure to fit ANSI C an error. */
283 static int pedantic_errors;
285 /* Nonzero means don't print warning messages. -w. */
287 static int inhibit_warnings = 0;
289 /* Nonzero means warn if slash-star appears in a slash-star comment,
290 or if newline-backslash appears in a slash-slash comment. */
292 static int warn_comments;
294 /* Nonzero means warn if a macro argument is (or would be)
295 stringified with -traditional. */
297 static int warn_stringify;
299 /* Nonzero means warn if there are any trigraphs. */
301 static int warn_trigraphs;
303 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
305 static int warn_undef;
307 /* Nonzero means warn if #import is used. */
309 static int warn_import = 1;
311 /* Nonzero means turn warnings into errors. */
313 static int warnings_are_errors;
315 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
319 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
323 /* Nonzero causes output not to be done,
324 but directives such as #define that have side effects
327 static int no_output;
329 /* Nonzero means we should look for header.gcc files that remap file names. */
332 /* Nonzero means this file was included with a -imacros or -include
333 command line and should not be recorded as an include file. */
335 static int no_record_file;
337 /* Nonzero means that we have finished processing the command line options.
338 This flag is used to decide whether or not to issue certain errors
341 static int done_initializing = 0;
343 /* Line where a newline was first seen in a string constant. */
345 static int multiline_string_line = 0;
347 /* I/O buffer structure.
348 The `fname' field is nonzero for source files and #include files
349 and for the dummy text used for -D and -U.
350 It is zero for rescanning results of macro expansion
351 and for expanding macro arguments. */
352 #define INPUT_STACK_MAX 400
353 static struct file_buf {
355 /* Filename specified with #line directive. */
357 /* The length of nominal_fname, which may contain embedded NULs. */
358 size_t nominal_fname_len;
359 /* Include file description. */
360 struct include_file *inc;
361 /* Record where in the search path this file was found.
362 For #include_next. */
363 struct file_name_list *dir;
368 /* Macro that this level is the expansion of.
369 Included so that we can reenable the macro
370 at the end of this level. */
371 struct hashnode *macro;
372 /* Value of if_stack at start of this file.
373 Used to prohibit unmatched #endif (etc) in an include file. */
374 struct if_stack *if_stack;
375 /* Object to be freed at end of input at this level. */
377 /* True if this is a system header file; see is_system_include. */
378 char system_header_p;
379 } instack[INPUT_STACK_MAX];
381 static int last_error_tick; /* Incremented each time we print it. */
382 static int input_file_stack_tick; /* Incremented when the status changes. */
384 /* Current nesting level of input sources.
385 `instack[indepth]' is the level currently being read. */
386 static int indepth = -1;
387 #define CHECK_DEPTH(code) \
388 if (indepth >= (INPUT_STACK_MAX - 1)) \
390 error_with_line (line_for_error (instack[indepth].lineno), \
391 "macro or `#include' recursion too deep"); \
395 /* Current depth in #include directives that use <...>. */
396 static int system_include_depth = 0;
398 typedef struct file_buf FILE_BUF;
400 /* The output buffer. Its LENGTH field is the amount of room allocated
401 for the buffer, not the number of chars actually present. To get
402 that, subtract outbuf.buf from outbuf.bufp. */
404 #define OUTBUF_SIZE 10 /* initial size of output buffer */
405 static FILE_BUF outbuf;
407 /* Grow output buffer OBUF points at
408 so it can hold at least NEEDED more chars. */
410 #define check_expand(OBUF, NEEDED) \
411 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
412 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
414 struct file_name_list
416 struct file_name_list *next;
417 /* If the following is 1, it is a C-language system include
419 int c_system_include_path;
420 /* Mapping of file names for this directory. */
421 struct file_name_map *name_map;
422 /* Non-zero if name_map is valid. */
424 /* The include directory status. */
426 /* The include prefix: "" denotes the working directory,
427 otherwise fname must end in '/'.
428 The actual size is dynamically allocated. */
432 /* #include "file" looks in source file dir, then stack. */
433 /* #include <file> just looks in the stack. */
434 /* -I directories are added to the end, then the defaults are added. */
436 static struct default_include {
437 char *fname; /* The name of the directory. */
438 char *component; /* The component containing the directory */
439 int cplusplus; /* Only look here if we're compiling C++. */
440 int cxx_aware; /* Includes in this directory don't need to
441 be wrapped in extern "C" when compiling
443 } include_defaults_array[]
444 #ifdef INCLUDE_DEFAULTS
448 /* Pick up GNU C++ specific include files. */
449 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
450 { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
452 /* This is the dir for fixincludes. Put it just before
453 the files that we fix. */
454 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
455 /* For cross-compilation, this dir name is generated
456 automatically in Makefile.in. */
457 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
458 #ifdef TOOL_INCLUDE_DIR
459 /* This is another place that the target system's headers might be. */
460 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
462 #else /* not CROSS_COMPILE */
463 #ifdef LOCAL_INCLUDE_DIR
464 /* This should be /usr/local/include and should come before
465 the fixincludes-fixed header files. */
466 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
468 #ifdef TOOL_INCLUDE_DIR
469 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
470 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
471 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
473 /* This is the dir for fixincludes. Put it just before
474 the files that we fix. */
475 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
476 /* Some systems have an extra dir of include files. */
477 #ifdef SYSTEM_INCLUDE_DIR
478 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
480 #ifndef STANDARD_INCLUDE_COMPONENT
481 #define STANDARD_INCLUDE_COMPONENT 0
483 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
484 #endif /* not CROSS_COMPILE */
487 #endif /* no INCLUDE_DEFAULTS */
489 /* The code looks at the defaults through this pointer, rather than through
490 the constant structure above. This pointer gets changed if an environment
491 variable specifies other defaults. */
492 static struct default_include *include_defaults = include_defaults_array;
494 static struct file_name_list *include = 0; /* First dir to search */
495 /* First dir to search for <file> */
496 /* This is the first element to use for #include <...>.
497 If it is 0, use the entire chain for such includes. */
498 static struct file_name_list *first_bracket_include = 0;
499 /* This is the first element in the chain that corresponds to
500 a directory of system header files. */
501 static struct file_name_list *first_system_include = 0;
502 static struct file_name_list *last_include = 0; /* Last in chain */
504 /* Chain of include directories to put at the end of the other chain. */
505 static struct file_name_list *after_include = 0;
506 static struct file_name_list *last_after_include = 0; /* Last in chain */
508 /* Chain to put at the start of the system include files. */
509 static struct file_name_list *before_system = 0;
510 static struct file_name_list *last_before_system = 0; /* Last in chain */
512 /* Directory prefix that should replace `/usr' in the standard
513 include file directories. */
514 static char *include_prefix;
516 /* Maintain and search list of included files. */
518 struct include_file {
519 struct include_file *next; /* for include_hashtab */
520 struct include_file *next_ino; /* for include_ino_hashtab */
522 /* If the following is the empty string, it means #pragma once
523 was seen in this include file, or #import was applied to the file.
524 Otherwise, if it is nonzero, it is a macro name.
525 Don't include the file again if that macro is defined. */
526 U_CHAR *control_macro;
527 /* Nonzero if the dependency on this include file has been output. */
532 /* Hash tables of files already included with #include or #import.
533 include_hashtab is by full name; include_ino_hashtab is by inode number. */
535 #define INCLUDE_HASHSIZE 61
536 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
537 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
539 /* Global list of strings read in from precompiled files. This list
540 is kept in the order the strings are read in, with new strings being
541 added at the end through stringlist_tailp. We use this list to output
542 the strings at the end of the run.
544 static STRINGDEF *stringlist;
545 static STRINGDEF **stringlist_tailp = &stringlist;
548 /* Structure returned by create_definition */
549 typedef struct macrodef MACRODEF;
552 struct definition *defn;
557 enum sharp_token_type {
558 NO_SHARP_TOKEN = 0, /* token not present */
560 SHARP_TOKEN = '#', /* token spelled with # only */
561 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
563 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
564 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
567 /* Structure allocated for every #define. For a simple replacement
570 nargs = -1, the `pattern' list is null, and the expansion is just
571 the replacement text. Nargs = 0 means a functionlike macro with no args,
573 #define getchar() getc (stdin) .
574 When there are args, the expansion is the replacement text with the
575 args squashed out, and the reflist is a list describing how to
576 build the output from the input: e.g., "3 chars, then the 1st arg,
577 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
578 The chars here come from the expansion. Whatever is left of the
579 expansion after the last arg-occurrence is copied after that arg.
580 Note that the reflist can be arbitrarily long---
581 its length depends on the number of times the arguments appear in
582 the replacement text, not how many args there are. Example:
583 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
585 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
586 where (x, y) means (nchars, argno). */
588 typedef struct definition DEFINITION;
591 int length; /* length of expansion string */
592 int predefined; /* True if the macro was builtin or */
593 /* came from the command line */
595 int line; /* Line number of definition */
596 char *file; /* File of definition */
597 size_t file_len; /* Length of file (which can contain NULs) */
598 char rest_args; /* Nonzero if last arg. absorbs the rest */
600 struct reflist *next;
602 enum sharp_token_type stringify; /* set if a # operator before arg */
603 enum sharp_token_type raw_before; /* set if a ## operator before arg */
604 enum sharp_token_type raw_after; /* set if a ## operator after arg */
606 char rest_args; /* Nonzero if this arg. absorbs the rest */
607 int nchars; /* Number of literal chars to copy before
608 this arg occurrence. */
609 int argno; /* Number of arg to substitute (origin-0) */
612 /* Names of macro args, concatenated in reverse order
613 with comma-space between them.
614 The only use of this is that we warn on redefinition
615 if this differs between the old and new definitions. */
620 /* different kinds of things that can appear in the value field
621 of a hash node. Actually, this may be useless now. */
629 * special extension string that can be added to the last macro argument to
630 * allow it to absorb the "rest" of the arguments when expanded. Ex:
631 * #define wow(a, b...) process (b, a, b)
632 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
633 * { wow (one, two); } -> { process (two, one, two); }
634 * if this "rest_arg" is used with the concat token '##' and if it is not
635 * supplied then the token attached to with ## will not be outputted. Ex:
636 * #define wow (a, b...) process (b ## , a, ## b)
637 * { wow (1, 2); } -> { process (2, 1, 2); }
638 * { wow (one); } -> { process (one); {
640 static char rest_extension[] = "...";
641 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
643 /* The structure of a node in the hash table. The hash table
644 has entries for all tokens defined by #define directives (type T_MACRO),
645 plus some special tokens like __LINE__ (these each have their own
646 type, and the appropriate code is run when that type of node is seen.
647 It does not contain control words like "#define", which are recognized
648 by a separate piece of code. */
650 /* different flavors of hash nodes --- also used in keyword table */
652 T_DEFINE = 1, /* the `#define' keyword */
653 T_INCLUDE, /* the `#include' keyword */
654 T_INCLUDE_NEXT, /* the `#include_next' keyword */
655 T_IMPORT, /* the `#import' keyword */
656 T_IFDEF, /* the `#ifdef' keyword */
657 T_IFNDEF, /* the `#ifndef' keyword */
658 T_IF, /* the `#if' keyword */
659 T_ELSE, /* `#else' */
660 T_PRAGMA, /* `#pragma' */
661 T_ELIF, /* `#elif' */
662 T_UNDEF, /* `#undef' */
663 T_LINE, /* `#line' */
664 T_ERROR, /* `#error' */
665 T_WARNING, /* `#warning' */
666 T_ENDIF, /* `#endif' */
667 T_SCCS, /* `#sccs', used on system V. */
668 T_IDENT, /* `#ident', used on system V. */
669 T_ASSERT, /* `#assert', taken from system V. */
670 T_UNASSERT, /* `#unassert', taken from system V. */
671 T_SPECLINE, /* special symbol `__LINE__' */
672 T_DATE, /* `__DATE__' */
673 T_FILE, /* `__FILE__' */
674 T_BASE_FILE, /* `__BASE_FILE__' */
675 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
676 T_VERSION, /* `__VERSION__' */
677 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
678 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
679 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
680 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
681 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
682 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
683 T_TIME, /* `__TIME__' */
684 T_CONST, /* Constant value, used by `__STDC__' */
685 T_MACRO, /* macro defined by `#define' */
686 T_DISABLED, /* macro temporarily turned off for rescan */
687 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
688 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
689 T_UNUSED /* Used for something not defined. */
693 struct hashnode *next; /* double links for easy deletion */
694 struct hashnode *prev;
695 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
696 chain is kept, in case the node is the head
697 of the chain and gets deleted. */
698 enum node_type type; /* type of special token */
699 int length; /* length of token, for quick comparison */
700 U_CHAR *name; /* the actual name */
701 union hashval value; /* pointer to expansion, or whatever */
704 typedef struct hashnode HASHNODE;
706 /* Some definitions for the hash table. The hash function MUST be
707 computed as shown in hashf () below. That is because the rescan
708 loop computes the hash value `on the fly' for most tokens,
709 in order to avoid the overhead of a lot of procedure calls to
710 the hashf () function. Hashf () only exists for the sake of
711 politeness, for use when speed isn't so important. */
713 #define HASHSIZE 1403
714 static HASHNODE *hashtab[HASHSIZE];
715 #define HASHSTEP(old, c) ((old << 2) + c)
716 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
718 /* Symbols to predefine. */
720 #ifdef CPP_PREDEFINES
721 static char *predefs = CPP_PREDEFINES;
723 static char *predefs = "";
726 /* We let tm.h override the types used here, to handle trivial differences
727 such as the choice of unsigned int or long unsigned int for size_t.
728 When machines start needing nontrivial differences in the size type,
729 it would be best to do something here to figure out automatically
730 from other information what type to use. */
732 /* The string value for __SIZE_TYPE__. */
735 #define SIZE_TYPE "long unsigned int"
738 /* The string value for __PTRDIFF_TYPE__. */
741 #define PTRDIFF_TYPE "long int"
744 /* The string value for __WCHAR_TYPE__. */
747 #define WCHAR_TYPE "int"
749 char * wchar_type = WCHAR_TYPE;
752 /* The string value for __USER_LABEL_PREFIX__ */
754 #ifndef USER_LABEL_PREFIX
755 #define USER_LABEL_PREFIX ""
758 /* The string value for __REGISTER_PREFIX__ */
760 #ifndef REGISTER_PREFIX
761 #define REGISTER_PREFIX ""
764 /* The string value for __IMMEDIATE_PREFIX__ */
766 #ifndef IMMEDIATE_PREFIX
767 #define IMMEDIATE_PREFIX ""
770 /* In the definition of a #assert name, this structure forms
771 a list of the individual values asserted.
772 Each value is itself a list of "tokens".
773 These are strings that are compared by name. */
775 struct tokenlist_list {
776 struct tokenlist_list *next;
777 struct arglist *tokens;
780 struct assertion_hashnode {
781 struct assertion_hashnode *next; /* double links for easy deletion */
782 struct assertion_hashnode *prev;
783 /* also, a back pointer to this node's hash
784 chain is kept, in case the node is the head
785 of the chain and gets deleted. */
786 struct assertion_hashnode **bucket_hdr;
787 int length; /* length of token, for quick comparison */
788 U_CHAR *name; /* the actual name */
789 /* List of token-sequences. */
790 struct tokenlist_list *value;
793 typedef struct assertion_hashnode ASSERTION_HASHNODE;
795 /* Some definitions for the hash table. The hash function MUST be
796 computed as shown in hashf below. That is because the rescan
797 loop computes the hash value `on the fly' for most tokens,
798 in order to avoid the overhead of a lot of procedure calls to
799 the hashf function. hashf only exists for the sake of
800 politeness, for use when speed isn't so important. */
802 #define ASSERTION_HASHSIZE 37
803 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
805 /* Nonzero means inhibit macroexpansion of what seem to be
806 assertion tests, in rescan. For #if. */
807 static int assertions_flag;
809 /* `struct directive' defines one #-directive, including how to handle it. */
811 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
814 int length; /* Length of name */
815 int (*func) DO_PROTO; /* Function to handle directive */
816 char *name; /* Name of directive */
817 enum node_type type; /* Code which describes which directive. */
820 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
821 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
823 /* These functions are declared to return int instead of void since they
824 are going to be placed in the table and some old compilers have trouble with
825 pointers to functions returning void. */
827 static int do_assert DO_PROTO;
828 static int do_define DO_PROTO;
829 static int do_elif DO_PROTO;
830 static int do_else DO_PROTO;
831 static int do_endif DO_PROTO;
832 static int do_error DO_PROTO;
833 static int do_ident DO_PROTO;
834 static int do_if DO_PROTO;
835 static int do_include DO_PROTO;
836 static int do_line DO_PROTO;
837 static int do_pragma DO_PROTO;
838 #ifdef SCCS_DIRECTIVE
839 static int do_sccs DO_PROTO;
841 static int do_unassert DO_PROTO;
842 static int do_undef DO_PROTO;
843 static int do_warning DO_PROTO;
844 static int do_xifdef DO_PROTO;
846 /* Here is the actual list of #-directives, most-often-used first. */
848 static struct directive directive_table[] = {
849 { 6, do_define, "define", T_DEFINE},
850 { 2, do_if, "if", T_IF},
851 { 5, do_xifdef, "ifdef", T_IFDEF},
852 { 6, do_xifdef, "ifndef", T_IFNDEF},
853 { 5, do_endif, "endif", T_ENDIF},
854 { 4, do_else, "else", T_ELSE},
855 { 4, do_elif, "elif", T_ELIF},
856 { 4, do_line, "line", T_LINE},
857 { 7, do_include, "include", T_INCLUDE},
858 { 12, do_include, "include_next", T_INCLUDE_NEXT},
859 { 6, do_include, "import", T_IMPORT},
860 { 5, do_undef, "undef", T_UNDEF},
861 { 5, do_error, "error", T_ERROR},
862 { 7, do_warning, "warning", T_WARNING},
863 #ifdef SCCS_DIRECTIVE
864 { 4, do_sccs, "sccs", T_SCCS},
866 { 6, do_pragma, "pragma", T_PRAGMA},
867 { 5, do_ident, "ident", T_IDENT},
868 { 6, do_assert, "assert", T_ASSERT},
869 { 8, do_unassert, "unassert", T_UNASSERT},
870 { -1, 0, "", T_UNUSED},
873 /* When a directive handler is called,
874 this points to the # (or the : of the %:) that started the directive. */
875 U_CHAR *directive_start;
877 /* table to tell if char can be part of a C identifier. */
878 U_CHAR is_idchar[256];
879 /* table to tell if char can be first char of a c identifier. */
880 U_CHAR is_idstart[256];
881 /* table to tell if c is horizontal space. */
882 static U_CHAR is_hor_space[256];
883 /* table to tell if c is horizontal or vertical space. */
884 U_CHAR is_space[256];
885 /* names of some characters */
886 static char *char_name[256];
888 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
889 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
891 static int errors = 0; /* Error counter for exit code */
893 /* Name of output file, for error messages. */
894 static char *out_fname;
897 /* Stack of conditionals currently in progress
898 (including both successful and failing conditionals). */
901 struct if_stack *next; /* for chaining to the next stack frame */
902 char *fname; /* copied from input when frame is made */
903 size_t fname_len; /* similarly */
904 int lineno; /* similarly */
905 int if_succeeded; /* true if a leg of this if-group
906 has been passed through rescan */
907 U_CHAR *control_macro; /* For #ifndef at start of file,
908 this is the macro name tested. */
909 enum node_type type; /* type of last directive seen in this group */
911 typedef struct if_stack IF_STACK_FRAME;
912 static IF_STACK_FRAME *if_stack = NULL;
914 /* Buffer of -M output. */
915 static char *deps_buffer;
917 /* Number of bytes allocated in above. */
918 static int deps_allocated_size;
920 /* Number of bytes used. */
921 static int deps_size;
923 /* Number of bytes since the last newline. */
924 static int deps_column;
926 /* Nonzero means -I- has been seen,
927 so don't look for #include "foo" the source-file directory. */
928 static int ignore_srcdir;
930 static int safe_read PROTO((int, char *, int));
931 static void safe_write PROTO((int, char *, int));
932 static void eprint_string PROTO((char *, size_t));
934 int main PROTO((int, char **));
936 static void path_include PROTO((char *));
938 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
940 static void trigraph_pcp PROTO((FILE_BUF *));
942 static void newline_fix PROTO((U_CHAR *));
943 static void name_newline_fix PROTO((U_CHAR *));
945 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
947 static void rescan PROTO((FILE_BUF *, int));
949 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
951 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
953 static struct tm *timestamp PROTO((void));
954 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
956 static int is_system_include PROTO((char *));
957 static char *base_name PROTO((char *));
958 static int absolute_filename PROTO((char *));
959 static size_t simplify_filename PROTO((char *));
961 static char *read_filename_string PROTO((int, FILE *));
962 static struct file_name_map *read_name_map PROTO((char *));
963 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
964 static char *remap_include_file PROTO((char *, struct file_name_list *));
965 static int lookup_ino_include PROTO((struct include_file *));
967 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
968 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
970 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
971 static int check_preconditions PROTO((char *));
972 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
973 static void pcstring_used PROTO((HASHNODE *));
974 static void write_output PROTO((void));
975 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
977 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
979 static int check_macro_name PROTO((U_CHAR *, char *));
980 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
981 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
983 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
985 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
986 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
988 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
989 static void free_token_list PROTO((struct arglist *));
991 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
992 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
993 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
995 static void do_once PROTO((void));
997 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
998 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
999 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1000 static void validate_else PROTO((U_CHAR *, U_CHAR *));
1002 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1003 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1004 static char *quote_string PROTO((char *, char *, size_t));
1005 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1007 /* Last arg to output_line_directive. */
1008 enum file_change_code {same_file, enter_file, leave_file};
1009 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1011 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1014 static char *macarg PROTO((struct argdata *, int));
1016 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
1018 static int discard_comments PROTO((U_CHAR *, int, int));
1020 static int change_newlines PROTO((U_CHAR *, int));
1022 char *my_strerror PROTO((int));
1023 void error PRINTF_PROTO_1((char *, ...));
1024 static void verror PROTO((char *, va_list));
1025 static void error_from_errno PROTO((char *));
1026 void warning PRINTF_PROTO_1((char *, ...));
1027 static void vwarning PROTO((char *, va_list));
1028 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1029 static void verror_with_line PROTO((int, char *, va_list));
1030 static void vwarning_with_line PROTO((int, char *, va_list));
1031 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1032 void pedwarn PRINTF_PROTO_1((char *, ...));
1033 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1034 static void pedwarn_with_file_and_line PRINTF_PROTO_4((char *, size_t, int, char *, ...));
1036 static void print_containing_files PROTO((void));
1038 static int line_for_error PROTO((int));
1039 static int grow_outbuf PROTO((FILE_BUF *, int));
1041 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1042 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1043 static void delete_macro PROTO((HASHNODE *));
1044 static int hashf PROTO((U_CHAR *, int, int));
1046 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1047 static void dump_all_macros PROTO((void));
1048 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1049 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1051 static void initialize_char_syntax PROTO((void));
1052 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1054 static void make_definition PROTO((char *, FILE_BUF *));
1055 static void make_undef PROTO((char *, FILE_BUF *));
1057 static void make_assertion PROTO((char *, char *));
1059 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1060 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1062 static int quote_string_for_make PROTO((char *, char *));
1063 static void deps_output PROTO((char *, int));
1065 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1066 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1067 static void perror_with_name PROTO((char *));
1068 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1069 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1071 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1072 GENERIC_PTR xmalloc PROTO((size_t));
1073 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1074 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1075 static char *savestring PROTO((char *));
1077 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1078 retrying if necessary. If MAX_READ_LEN is defined, read at most
1079 that bytes at a time. Return a negative value if an error occurs,
1080 otherwise return the actual number of bytes read,
1081 which must be LEN unless end-of-file was reached. */
1084 safe_read (desc, ptr, len)
1089 int left, rcount, nchars;
1095 if (rcount > MAX_READ_LEN)
1096 rcount = MAX_READ_LEN;
1098 nchars = read (desc, ptr, rcount);
1115 /* Write LEN bytes at PTR to descriptor DESC,
1116 retrying if necessary, and treating any real error as fatal.
1117 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1120 safe_write (desc, ptr, len)
1125 int wcount, written;
1129 #ifdef MAX_WRITE_LEN
1130 if (wcount > MAX_WRITE_LEN)
1131 wcount = MAX_WRITE_LEN;
1133 written = write (desc, ptr, wcount);
1140 pfatal_with_name (out_fname);
1147 /* Print a string to stderr, with extra handling in case it contains
1148 embedded NUL characters. Any present are written as is.
1150 Using fwrite for this purpose produces undesireable results on VMS
1151 when stderr happens to be a record oriented file, such as a batch log
1152 file, rather than a stream oriented one. */
1155 eprint_string (string, length)
1159 size_t segment_length;
1162 fprintf(stderr, "%s", string);
1163 length -= (segment_length = strlen(string));
1166 fputc('\0', stderr);
1168 /* Advance past the portion which has already been printed. */
1169 string += segment_length + 1;
1171 } while (length > 0);
1185 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1186 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1187 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1188 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1189 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1191 /* Record the option used with each element of pend_assertions.
1192 This is preparation for supporting more than one option for making
1194 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1195 int inhibit_predefs = 0;
1196 int no_standard_includes = 0;
1197 int no_standard_cplusplus_includes = 0;
1198 int missing_newline = 0;
1200 /* Non-0 means don't output the preprocessed program. */
1201 int inhibit_output = 0;
1202 /* Non-0 means -v, so print the full set of include dirs. */
1205 /* File name which deps are being written to.
1206 This is 0 if deps are being written to stdout. */
1207 char *deps_file = 0;
1208 /* Fopen file mode to open deps_file with. */
1209 char *deps_mode = "a";
1210 /* Stream on which to print the dependency information. */
1211 FILE *deps_stream = 0;
1212 /* Target-name to write with the dependency information. */
1213 char *deps_target = 0;
1215 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1216 /* Get rid of any avoidable limit on stack size. */
1220 /* Set the stack limit huge so that alloca (particularly stringtab
1221 in dbxread.c) does not fail. */
1222 getrlimit (RLIMIT_STACK, &rlim);
1223 rlim.rlim_cur = rlim.rlim_max;
1224 setrlimit (RLIMIT_STACK, &rlim);
1229 signal (SIGPIPE, pipe_closed);
1232 progname = base_name (argv[0]);
1236 /* Remove extension from PROGNAME. */
1238 char *s = progname = savestring (progname);
1240 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1241 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1242 && (p[1] == 'e' || p[1] == 'E')
1243 && (p[2] == 'x' || p[2] == 'X')
1244 && (p[3] == 'e' || p[3] == 'E')
1253 /* Initialize is_idchar. */
1254 initialize_char_syntax ();
1256 no_line_directives = 0;
1258 dump_macros = dump_none;
1261 cplusplus_comments = 1;
1263 bzero ((char *) pend_files, argc * sizeof (char *));
1264 bzero ((char *) pend_defs, argc * sizeof (char *));
1265 bzero ((char *) pend_undefs, argc * sizeof (char *));
1266 bzero ((char *) pend_assertions, argc * sizeof (char *));
1267 bzero ((char *) pend_includes, argc * sizeof (char *));
1269 /* Process switches and find input file name. */
1271 for (i = 1; i < argc; i++) {
1272 if (argv[i][0] != '-') {
1273 if (out_fname != NULL)
1274 fatal ("Usage: %s [switches] input output", argv[0]);
1275 else if (in_fname != NULL)
1276 out_fname = argv[i];
1280 switch (argv[i][1]) {
1283 if (!strcmp (argv[i], "-include")) {
1287 fatal ("Filename missing after `-include' option");
1289 simplify_filename (pend_includes[temp] = argv[++i]);
1291 if (!strcmp (argv[i], "-imacros")) {
1295 fatal ("Filename missing after `-imacros' option");
1297 simplify_filename (pend_files[temp] = argv[++i]);
1299 if (!strcmp (argv[i], "-iprefix")) {
1301 fatal ("Filename missing after `-iprefix' option");
1303 include_prefix = argv[++i];
1305 if (!strcmp (argv[i], "-ifoutput")) {
1306 output_conditionals = 1;
1308 if (!strcmp (argv[i], "-isystem")) {
1309 struct file_name_list *dirtmp;
1311 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1314 dirtmp->c_system_include_path = 1;
1316 if (before_system == 0)
1317 before_system = dirtmp;
1319 last_before_system->next = dirtmp;
1320 last_before_system = dirtmp; /* Tail follows the last one */
1322 /* Add directory to end of path for includes,
1323 with the default prefix at the front of its name. */
1324 if (!strcmp (argv[i], "-iwithprefix")) {
1325 struct file_name_list *dirtmp;
1328 if (include_prefix != 0)
1329 prefix = include_prefix;
1331 prefix = savestring (GCC_INCLUDE_DIR);
1332 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1333 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1334 prefix[strlen (prefix) - 7] = 0;
1337 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1338 prefix, argv[++i])))
1341 if (after_include == 0)
1342 after_include = dirtmp;
1344 last_after_include->next = dirtmp;
1345 last_after_include = dirtmp; /* Tail follows the last one */
1347 /* Add directory to main path for includes,
1348 with the default prefix at the front of its name. */
1349 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1350 struct file_name_list *dirtmp;
1353 if (include_prefix != 0)
1354 prefix = include_prefix;
1356 prefix = savestring (GCC_INCLUDE_DIR);
1357 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1358 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1359 prefix[strlen (prefix) - 7] = 0;
1362 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1363 append_include_chain (dirtmp, dirtmp);
1365 /* Add directory to end of path for includes. */
1366 if (!strcmp (argv[i], "-idirafter")) {
1367 struct file_name_list *dirtmp;
1369 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1373 if (after_include == 0)
1374 after_include = dirtmp;
1376 last_after_include->next = dirtmp;
1377 last_after_include = dirtmp; /* Tail follows the last one */
1382 if (out_fname != NULL)
1383 fatal ("Output filename specified twice");
1385 fatal ("Filename missing after -o option");
1386 out_fname = argv[++i];
1387 if (!strcmp (out_fname, "-"))
1392 if (!strcmp (argv[i], "-pedantic"))
1394 else if (!strcmp (argv[i], "-pedantic-errors")) {
1396 pedantic_errors = 1;
1397 } else if (!strcmp (argv[i], "-pcp")) {
1400 fatal ("Filename missing after -pcp option");
1401 pcp_fname = argv[++i];
1403 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1404 ? fopen (pcp_fname, "w")
1406 if (pcp_outfile == 0)
1407 pfatal_with_name (pcp_fname);
1413 if (!strcmp (argv[i], "-traditional")) {
1415 cplusplus_comments = 0;
1416 } else if (!strcmp (argv[i], "-trigraphs")) {
1422 if (! strcmp (argv[i], "-lang-c"))
1423 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1424 if (! strcmp (argv[i], "-lang-c89"))
1425 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1426 if (! strcmp (argv[i], "-lang-c++"))
1427 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1428 if (! strcmp (argv[i], "-lang-objc"))
1429 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1430 if (! strcmp (argv[i], "-lang-objc++"))
1431 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1432 if (! strcmp (argv[i], "-lang-asm"))
1434 if (! strcmp (argv[i], "-lint"))
1439 cplusplus = 1, cplusplus_comments = 1;
1443 inhibit_warnings = 1;
1447 if (!strcmp (argv[i], "-Wtrigraphs"))
1449 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1451 else if (!strcmp (argv[i], "-Wcomment"))
1453 else if (!strcmp (argv[i], "-Wno-comment"))
1455 else if (!strcmp (argv[i], "-Wcomments"))
1457 else if (!strcmp (argv[i], "-Wno-comments"))
1459 else if (!strcmp (argv[i], "-Wtraditional"))
1461 else if (!strcmp (argv[i], "-Wno-traditional"))
1463 else if (!strcmp (argv[i], "-Wundef"))
1465 else if (!strcmp (argv[i], "-Wno-undef"))
1467 else if (!strcmp (argv[i], "-Wimport"))
1469 else if (!strcmp (argv[i], "-Wno-import"))
1471 else if (!strcmp (argv[i], "-Werror"))
1472 warnings_are_errors = 1;
1473 else if (!strcmp (argv[i], "-Wno-error"))
1474 warnings_are_errors = 0;
1475 else if (!strcmp (argv[i], "-Wall"))
1483 /* The style of the choices here is a bit mixed.
1484 The chosen scheme is a hybrid of keeping all options in one string
1485 and specifying each option in a separate argument:
1486 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1487 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1488 -M[M][G][D file]. This is awkward to handle in specs, and is not
1490 /* ??? -MG must be specified in addition to one of -M or -MM.
1491 This can be relaxed in the future without breaking anything.
1492 The converse isn't true. */
1494 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1495 if (!strcmp (argv[i], "-MG"))
1497 print_deps_missing_files = 1;
1500 if (!strcmp (argv[i], "-M"))
1502 else if (!strcmp (argv[i], "-MM"))
1504 else if (!strcmp (argv[i], "-MD"))
1506 else if (!strcmp (argv[i], "-MMD"))
1508 /* For -MD and -MMD options, write deps on file named by next arg. */
1509 if (!strcmp (argv[i], "-MD")
1510 || !strcmp (argv[i], "-MMD")) {
1512 fatal ("Filename missing after %s option", argv[i]);
1514 deps_file = argv[i];
1517 /* For -M and -MM, write deps on standard output
1518 and suppress the usual output. */
1519 deps_stream = stdout;
1526 char *p = argv[i] + 2;
1528 while ((c = *p++)) {
1529 /* Arg to -d specifies what parts of macros to dump */
1532 dump_macros = dump_only;
1536 dump_macros = dump_names;
1539 dump_macros = dump_definitions;
1550 if (argv[i][2] == '3')
1555 fprintf (stderr, "GNU CPP version %s", version_string);
1556 #ifdef TARGET_VERSION
1559 fprintf (stderr, "\n");
1564 print_include_names = 1;
1568 if (argv[i][2] != 0)
1569 pend_defs[i] = argv[i] + 2;
1570 else if (i + 1 == argc)
1571 fatal ("Macro name missing after -D option");
1573 i++, pend_defs[i] = argv[i];
1580 if (argv[i][2] != 0)
1582 else if (i + 1 == argc)
1583 fatal ("Assertion missing after -A option");
1587 if (!strcmp (p, "-")) {
1588 /* -A- eliminates all predefined macros and assertions.
1589 Let's include also any that were specified earlier
1590 on the command line. That way we can get rid of any
1591 that were passed automatically in from GCC. */
1593 inhibit_predefs = 1;
1594 for (j = 0; j < i; j++)
1595 pend_defs[j] = pend_assertions[j] = 0;
1597 pend_assertions[i] = p;
1598 pend_assertion_options[i] = "-A";
1603 case 'U': /* JF #undef something */
1604 if (argv[i][2] != 0)
1605 pend_undefs[i] = argv[i] + 2;
1606 else if (i + 1 == argc)
1607 fatal ("Macro name missing after -U option");
1609 pend_undefs[i] = argv[i+1], i++;
1613 put_out_comments = 1;
1616 case 'E': /* -E comes from cc -E; ignore it. */
1620 no_line_directives = 1;
1623 case '$': /* Don't include $ in identifiers. */
1624 is_idchar['$'] = is_idstart['$'] = 0;
1627 case 'I': /* Add directory to path for includes. */
1629 struct file_name_list *dirtmp;
1631 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1633 /* Don't use any preceding -I directories for #include <...>. */
1634 first_bracket_include = 0;
1637 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1638 argv[i][2] ? argv[i] + 2 : argv[++i]);
1639 append_include_chain (dirtmp, dirtmp);
1645 if (!strcmp (argv[i], "-nostdinc"))
1646 /* -nostdinc causes no default include directories.
1647 You must specify all include-file directories with -I. */
1648 no_standard_includes = 1;
1649 else if (!strcmp (argv[i], "-nostdinc++"))
1650 /* -nostdinc++ causes no default C++-specific include directories. */
1651 no_standard_cplusplus_includes = 1;
1652 else if (!strcmp (argv[i], "-noprecomp"))
1657 if (!strcmp (argv[i], "-remap"))
1662 /* Sun compiler passes undocumented switch "-undef".
1663 Let's assume it means to inhibit the predefined symbols. */
1664 inhibit_predefs = 1;
1667 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1668 if (in_fname == NULL) {
1671 } else if (out_fname == NULL) {
1674 } /* else fall through into error */
1677 fatal ("Invalid option `%s'", argv[i]);
1682 /* Add dirs from CPATH after dirs from -I. */
1683 /* There seems to be confusion about what CPATH should do,
1684 so for the moment it is not documented. */
1685 /* Some people say that CPATH should replace the standard include dirs,
1686 but that seems pointless: it comes before them, so it overrides them
1688 GET_ENVIRONMENT (cp, "CPATH");
1689 if (cp && ! no_standard_includes)
1692 /* Initialize output buffer */
1694 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1695 outbuf.bufp = outbuf.buf;
1696 outbuf.length = OUTBUF_SIZE;
1698 /* Do partial setup of input buffer for the sake of generating
1699 early #line directives (when -g is in effect). */
1701 fp = &instack[++indepth];
1702 if (in_fname == NULL)
1704 fp->nominal_fname = fp->fname = in_fname;
1705 fp->nominal_fname_len = strlen (in_fname);
1708 /* In C++, wchar_t is a distinct basic type, and we can expect
1709 __wchar_t to be defined by cc1plus. */
1711 wchar_type = "__wchar_t";
1713 /* Install __LINE__, etc. Must follow initialize_char_syntax
1714 and option processing. */
1715 initialize_builtins (fp, &outbuf);
1717 /* Do standard #defines and assertions
1718 that identify system and machine type. */
1720 if (!inhibit_predefs) {
1721 char *p = (char *) alloca (strlen (predefs) + 1);
1724 struct dsc$descriptor_s lcl_name;
1726 unsigned short length; /* input length */
1727 unsigned short code; /* item code */
1728 unsigned long dptr; /* data ptr */
1729 unsigned long lptr; /* output length ptr */
1732 unsigned long syi_length;
1735 struct item_list items[] = {
1736 { 16, SYI$_VERSION, 0, 0 },
1740 items[0].dptr = (unsigned long)syi_data;
1741 items[0].lptr = (unsigned long)(&syi_length);
1743 if (SYS$GETSYIW (0, 0, 0, items, NULL, NULL, NULL, NULL) == SS$_NORMAL)
1745 unsigned long vms_version_value;
1749 vms_version_value = 0;
1753 if (isdigit (*vers))
1755 vms_version_value = (*vers - '0') * 10000000;
1761 if (isdigit (*vers))
1763 vms_version_value += (*vers - '0') * 100000;
1767 if (vms_version_value > 0)
1771 sprintf (versbuf, "__VMS_VER=%08ld", vms_version_value);
1773 output_line_directive (fp, &outbuf, 0, same_file);
1774 make_definition (versbuf, &outbuf);
1779 strcpy (p, predefs);
1782 while (*p == ' ' || *p == '\t')
1784 /* Handle -D options. */
1785 if (p[0] == '-' && p[1] == 'D') {
1787 while (*p && *p != ' ' && *p != '\t')
1792 output_line_directive (fp, &outbuf, 0, same_file);
1793 make_definition (q, &outbuf);
1794 while (*p == ' ' || *p == '\t')
1796 } else if (p[0] == '-' && p[1] == 'A') {
1797 /* Handle -A options (assertions). */
1806 past_name = assertion;
1807 /* Locate end of name. */
1808 while (*past_name && *past_name != ' '
1809 && *past_name != '\t' && *past_name != '(')
1811 /* Locate `(' at start of value. */
1813 while (*value && (*value == ' ' || *value == '\t'))
1815 if (*value++ != '(')
1817 while (*value && (*value == ' ' || *value == '\t'))
1820 /* Locate end of value. */
1821 while (*past_value && *past_value != ' '
1822 && *past_value != '\t' && *past_value != ')')
1824 termination = past_value;
1825 while (*termination && (*termination == ' ' || *termination == '\t'))
1827 if (*termination++ != ')')
1829 if (*termination && *termination != ' ' && *termination != '\t')
1831 /* Temporarily null-terminate the value. */
1832 save_char = *termination;
1833 *termination = '\0';
1834 /* Install the assertion. */
1835 make_assertion ("-A", assertion);
1836 *termination = (char) save_char;
1838 while (*p == ' ' || *p == '\t')
1846 /* Now handle the command line options. */
1848 /* Do -U's, -D's and -A's in the order they were seen. */
1849 for (i = 1; i < argc; i++) {
1850 if (pend_undefs[i]) {
1852 output_line_directive (fp, &outbuf, 0, same_file);
1853 make_undef (pend_undefs[i], &outbuf);
1857 output_line_directive (fp, &outbuf, 0, same_file);
1858 make_definition (pend_defs[i], &outbuf);
1860 if (pend_assertions[i])
1861 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1864 done_initializing = 1;
1866 { /* Read the appropriate environment variable and if it exists
1867 replace include_defaults with the listed path. */
1869 switch ((objc << 1) + cplusplus)
1872 GET_ENVIRONMENT (epath, "C_INCLUDE_PATH");
1875 GET_ENVIRONMENT (epath, "CPLUS_INCLUDE_PATH");
1878 GET_ENVIRONMENT (epath, "OBJC_INCLUDE_PATH");
1881 GET_ENVIRONMENT (epath, "OBJCPLUS_INCLUDE_PATH");
1884 /* If the environment var for this language is set,
1885 add to the default list of include directories. */
1888 char *startp, *endp;
1890 for (num_dirs = 1, startp = epath; *startp; startp++)
1891 if (*startp == PATH_SEPARATOR)
1894 = (struct default_include *) xmalloc ((num_dirs
1895 * sizeof (struct default_include))
1896 + sizeof (include_defaults_array));
1897 startp = endp = epath;
1901 if (c == PATH_SEPARATOR || !c) {
1903 include_defaults[num_dirs].fname
1904 = startp == endp ? "." : savestring (startp);
1906 include_defaults[num_dirs].component = 0;
1907 include_defaults[num_dirs].cplusplus = cplusplus;
1908 include_defaults[num_dirs].cxx_aware = 1;
1915 /* Put the usual defaults back in at the end. */
1916 bcopy ((char *) include_defaults_array,
1917 (char *) &include_defaults[num_dirs],
1918 sizeof (include_defaults_array));
1922 append_include_chain (before_system, last_before_system);
1923 first_system_include = before_system;
1925 /* Unless -fnostdinc,
1926 tack on the standard include file dirs to the specified list */
1927 if (!no_standard_includes) {
1928 struct default_include *p = include_defaults;
1929 char *specd_prefix = include_prefix;
1930 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1931 int default_len = 0;
1932 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1933 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1934 default_len = strlen (default_prefix) - 7;
1935 default_prefix[default_len] = 0;
1937 /* Search "translated" versions of GNU directories.
1938 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1939 if (specd_prefix != 0 && default_len != 0)
1940 for (p = include_defaults; p->fname; p++) {
1941 /* Some standard dirs are only for C++. */
1942 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1943 /* Does this dir start with the prefix? */
1944 if (!strncmp (p->fname, default_prefix, default_len)) {
1945 /* Yes; change prefix and add to search list. */
1946 struct file_name_list *new
1947 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1948 p->fname + default_len);
1950 new->c_system_include_path = !p->cxx_aware;
1951 append_include_chain (new, new);
1952 if (first_system_include == 0)
1953 first_system_include = new;
1958 /* Search ordinary names for GNU include directories. */
1959 for (p = include_defaults; p->fname; p++) {
1960 /* Some standard dirs are only for C++. */
1961 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1962 struct file_name_list *new
1963 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1965 new->c_system_include_path = !p->cxx_aware;
1966 append_include_chain (new, new);
1967 if (first_system_include == 0)
1968 first_system_include = new;
1974 /* Tack the after_include chain at the end of the include chain. */
1975 append_include_chain (after_include, last_after_include);
1976 if (first_system_include == 0)
1977 first_system_include = after_include;
1979 /* With -v, print the list of dirs to search. */
1981 struct file_name_list *p;
1982 fprintf (stderr, "#include \"...\" search starts here:\n");
1983 for (p = include; p; p = p->next) {
1984 if (p == first_bracket_include)
1985 fprintf (stderr, "#include <...> search starts here:\n");
1987 fprintf (stderr, " .\n");
1988 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1989 fprintf (stderr, " %s\n", p->fname);
1991 /* Omit trailing '/'. */
1992 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1994 fprintf (stderr, "End of search list.\n");
1997 /* -MG doesn't select the form of output and must be specified with one of
1998 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1999 inhibit compilation. */
2000 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2001 fatal ("-MG must be specified with one of -M or -MM");
2003 /* Either of two environment variables can specify output of deps.
2004 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2005 where OUTPUT_FILE is the file to write deps info to
2006 and DEPS_TARGET is the target to mention in the deps. */
2009 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2010 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2011 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2016 spec = getenv ("SUNPRO_DEPENDENCIES");
2023 /* Find the space before the DEPS_TARGET, if there is one. */
2024 /* This should use index. (mrs) */
2025 while (*s != 0 && *s != ' ') s++;
2027 deps_target = s + 1;
2028 output_file = xmalloc (s - spec + 1);
2029 bcopy (spec, output_file, s - spec);
2030 output_file[s - spec] = 0;
2037 deps_file = output_file;
2041 /* For -M, print the expected object file name
2042 as the target of this Make-rule. */
2044 deps_allocated_size = 200;
2045 deps_buffer = xmalloc (deps_allocated_size);
2051 deps_output (deps_target, ':');
2052 } else if (*in_fname == 0) {
2053 deps_output ("-", ':');
2058 q = base_name (in_fname);
2060 /* Copy remainder to mungable area. */
2061 p = (char *) alloca (strlen(q) + 8);
2064 /* Output P, but remove known suffixes. */
2068 && p[len - 2] == '.'
2069 && index("cCsSm", p[len - 1]))
2072 && p[len - 3] == '.'
2073 && p[len - 2] == 'c'
2074 && p[len - 1] == 'c')
2077 && p[len - 4] == '.'
2078 && p[len - 3] == 'c'
2079 && p[len - 2] == 'x'
2080 && p[len - 1] == 'x')
2083 && p[len - 4] == '.'
2084 && p[len - 3] == 'c'
2085 && p[len - 2] == 'p'
2086 && p[len - 1] == 'p')
2089 /* Supply our own suffix. */
2090 strcpy (q, OBJECT_SUFFIX);
2092 deps_output (p, ':');
2093 deps_output (in_fname, ' ');
2097 /* Scan the -imacros files before the main input.
2098 Much like #including them, but with no_output set
2099 so that only their macro definitions matter. */
2101 no_output++; no_record_file++;
2102 for (i = 1; i < argc; i++)
2103 if (pend_files[i]) {
2104 struct include_file *inc;
2105 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2107 perror_with_name (pend_files[i]);
2108 return FATAL_EXIT_CODE;
2110 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2112 no_output--; no_record_file--;
2114 /* Copy the entire contents of the main input file into
2115 the stacked input buffer previously allocated for it. */
2117 /* JF check for stdin */
2118 if (in_fname == NULL || *in_fname == 0) {
2121 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2124 if (fstat (f, &st) != 0)
2125 pfatal_with_name (in_fname);
2126 fp->nominal_fname = fp->fname = in_fname;
2127 fp->nominal_fname_len = strlen (in_fname);
2129 fp->system_header_p = 0;
2130 /* JF all this is mine about reading pipes and ttys */
2131 if (! S_ISREG (st.st_mode)) {
2132 /* Read input from a file that is not a normal disk file.
2133 We cannot preallocate a buffer with the correct size,
2134 so we must read in the file a piece at the time and make it bigger. */
2139 if (S_ISDIR (st.st_mode))
2140 fatal ("Input file `%s' is a directory", in_fname);
2144 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2146 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2147 if (cnt < 0) goto perror; /* error! */
2149 if (size != bsize) break; /* End of file */
2151 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2155 /* Read a file whose size we can determine in advance.
2156 For the sake of VMS, st.st_size is just an upper bound. */
2157 size_t s = (size_t) st.st_size;
2158 if (s != st.st_size || s + 2 < s)
2160 fp->buf = (U_CHAR *) xmalloc (s + 2);
2161 fp->length = safe_read (f, (char *) fp->buf, s);
2162 if (fp->length < 0) goto perror;
2165 fp->if_stack = if_stack;
2167 /* Make sure data ends with a newline. And put a null after it. */
2169 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2170 /* Backslash-newline at end is not good enough. */
2171 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2172 fp->buf[fp->length++] = '\n';
2173 missing_newline = 1;
2175 fp->buf[fp->length] = '\0';
2177 /* Unless inhibited, convert trigraphs in the input. */
2182 /* Now that we know the input file is valid, open the output. */
2184 if (!out_fname || !strcmp (out_fname, ""))
2185 out_fname = "stdout";
2186 else if (! freopen (out_fname, "w", stdout))
2187 pfatal_with_name (out_fname);
2189 output_line_directive (fp, &outbuf, 0, same_file);
2191 /* Scan the -include files before the main input. */
2194 for (i = 1; i < argc; i++)
2195 if (pend_includes[i]) {
2196 struct include_file *inc;
2197 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2199 perror_with_name (pend_includes[i]);
2200 return FATAL_EXIT_CODE;
2202 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2206 /* Scan the input, processing macros and directives. */
2208 rescan (&outbuf, 0);
2210 if (missing_newline)
2213 if (pedantic && missing_newline)
2214 pedwarn ("file does not end in newline");
2216 /* Now we have processed the entire input
2217 Write whichever kind of output has been requested. */
2219 if (dump_macros == dump_only)
2221 else if (! inhibit_output) {
2226 /* Don't actually write the deps file if compilation has failed. */
2228 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2229 pfatal_with_name (deps_file);
2230 fputs (deps_buffer, deps_stream);
2231 putc ('\n', deps_stream);
2233 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2234 fatal ("I/O error on output");
2239 if (pcp_outfile && pcp_outfile != stdout
2240 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2241 fatal ("I/O error on `-pcp' output");
2243 if (ferror (stdout) || fclose (stdout) != 0)
2244 fatal ("I/O error on output");
2247 exit (FATAL_EXIT_CODE);
2248 exit (SUCCESS_EXIT_CODE);
2251 pfatal_with_name (in_fname);
2255 /* Given a colon-separated list of file names PATH,
2256 add all the names to the search path for include files. */
2270 struct file_name_list *dirtmp;
2272 /* Find the end of this name. */
2273 while ((c = *q++) != PATH_SEPARATOR && c)
2277 dirtmp = new_include_prefix (last_include, NULL_PTR,
2278 "", p == q ? "." : p);
2280 append_include_chain (dirtmp, dirtmp);
2282 /* Advance past this name. */
2289 /* Return the address of the first character in S that equals C.
2290 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2291 Return 0 if there is no such character. Assume that C itself is not '\0'.
2292 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2293 but unfortunately memchr isn't autoconfigured yet. */
2301 char *p = (char *) s;
2303 char *q = index (p, c);
2305 return (U_CHAR *) q;
2307 size_t l = strlen (p);
2317 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2318 before main CCCP processing. Name `pcp' is also in honor of the
2319 drugs the trigraph designers must have been on.
2321 Using an extra pass through the buffer takes a little extra time,
2322 but is infinitely less hairy than trying to handle trigraphs inside
2323 strings, etc. everywhere, and also makes sure that trigraphs are
2324 only translated in the top level of processing. */
2330 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2333 fptr = bptr = sptr = buf->buf;
2334 lptr = fptr + buf->length;
2335 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2372 len = sptr - fptr - 2;
2374 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2375 C, this will be memmove (). */
2376 if (bptr != fptr && len > 0)
2377 bcopy ((char *) fptr, (char *) bptr, len);
2383 len = buf->length - (fptr - buf->buf);
2384 if (bptr != fptr && len > 0)
2385 bcopy ((char *) fptr, (char *) bptr, len);
2386 buf->length -= fptr - bptr;
2387 buf->buf[buf->length] = '\0';
2388 if (warn_trigraphs && fptr != bptr)
2389 warning_with_line (0, "%lu trigraph(s) encountered",
2390 (unsigned long) (fptr - bptr) / 2);
2393 /* Move all backslash-newline pairs out of embarrassing places.
2394 Exchange all such pairs following BP
2395 with any potentially-embarrassing characters that follow them.
2396 Potentially-embarrassing characters are / and *
2397 (because a backslash-newline inside a comment delimiter
2398 would cause it not to be recognized). */
2404 register U_CHAR *p = bp;
2406 /* First count the backslash-newline pairs here. */
2408 while (p[0] == '\\' && p[1] == '\n')
2411 /* What follows the backslash-newlines is not embarrassing. */
2413 if (*p != '/' && *p != '*')
2416 /* Copy all potentially embarrassing characters
2417 that follow the backslash-newline pairs
2418 down to where the pairs originally started. */
2420 while (*p == '*' || *p == '/')
2423 /* Now write the same number of pairs after the embarrassing chars. */
2430 /* Like newline_fix but for use within a directive-name.
2431 Move any backslash-newlines up past any following symbol constituents. */
2434 name_newline_fix (bp)
2437 register U_CHAR *p = bp;
2439 /* First count the backslash-newline pairs here. */
2440 while (p[0] == '\\' && p[1] == '\n')
2443 /* What follows the backslash-newlines is not embarrassing. */
2448 /* Copy all potentially embarrassing characters
2449 that follow the backslash-newline pairs
2450 down to where the pairs originally started. */
2452 while (is_idchar[*p])
2455 /* Now write the same number of pairs after the embarrassing chars. */
2462 /* Look for lint commands in comments.
2464 When we come in here, ibp points into a comment. Limit is as one expects.
2465 scan within the comment -- it should start, after lwsp, with a lint command.
2466 If so that command is returned as a (constant) string.
2468 Upon return, any arg will be pointed to with argstart and will be
2469 arglen long. Note that we don't parse that arg since it will just
2470 be printed out again. */
2473 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2474 register U_CHAR *ibp;
2475 register U_CHAR *limit;
2476 U_CHAR **argstart; /* point to command arg */
2477 int *arglen, *cmdlen; /* how long they are */
2479 HOST_WIDE_INT linsize;
2480 register U_CHAR *numptr; /* temp for arg parsing */
2484 SKIP_WHITE_SPACE (ibp);
2486 if (ibp >= limit) return NULL;
2488 linsize = limit - ibp;
2490 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2491 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2493 return "NOTREACHED";
2495 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2499 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2501 return "LINTLIBRARY";
2503 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2505 ibp += 7; linsize -= 7;
2506 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2508 /* OK, read a number */
2509 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2511 *arglen = numptr - *argstart;
2518 * The main loop of the program.
2520 * Read characters from the input stack, transferring them to the
2523 * Macros are expanded and push levels on the input stack.
2524 * At the end of such a level it is popped off and we keep reading.
2525 * At the end of any other kind of level, we return.
2526 * #-directives are handled, except within macros.
2528 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2529 * and insert them when appropriate. This is set while scanning macro
2530 * arguments before substitution. It is zero when scanning for final output.
2531 * There are three types of Newline markers:
2532 * * Newline - follows a macro name that was not expanded
2533 * because it appeared inside an expansion of the same macro.
2534 * This marker prevents future expansion of that identifier.
2535 * When the input is rescanned into the final output, these are deleted.
2536 * These are also deleted by ## concatenation.
2537 * * Newline Space (or Newline and any other whitespace character)
2538 * stands for a place that tokens must be separated or whitespace
2539 * is otherwise desirable, but where the ANSI standard specifies there
2540 * is no whitespace. This marker turns into a Space (or whichever other
2541 * whitespace char appears in the marker) in the final output,
2542 * but it turns into nothing in an argument that is stringified with #.
2543 * Such stringified arguments are the only place where the ANSI standard
2544 * specifies with precision that whitespace may not appear.
2546 * During this function, IP->bufp is kept cached in IBP for speed of access.
2547 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2548 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2549 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2550 * explicitly, and before RECACHE, since RECACHE uses OBP.
2554 rescan (op, output_marks)
2558 /* Character being scanned in main loop. */
2561 /* Length of pending accumulated identifier. */
2562 register int ident_length = 0;
2564 /* Hash code of pending accumulated identifier. */
2565 register int hash = 0;
2567 /* Current input level (&instack[indepth]). */
2570 /* Pointer for scanning input. */
2571 register U_CHAR *ibp;
2573 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2574 register U_CHAR *limit;
2576 /* Pointer for storing output. */
2577 register U_CHAR *obp;
2579 /* REDO_CHAR is nonzero if we are processing an identifier
2580 after backing up over the terminating character.
2581 Sometimes we process an identifier without backing up over
2582 the terminating character, if the terminating character
2583 is not special. Backing up is done so that the terminating character
2584 will be dispatched on again once the identifier is dealt with. */
2587 /* 1 if within an identifier inside of which a concatenation
2588 marker (Newline -) has been seen. */
2589 int concatenated = 0;
2591 /* While scanning a comment or a string constant,
2592 this records the line it started on, for error messages. */
2595 /* Record position of last `real' newline. */
2596 U_CHAR *beg_of_line;
2598 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2601 do { ip->macro->type = T_MACRO; \
2602 if (ip->free_ptr) free (ip->free_ptr); \
2603 --indepth; } while (0)
2605 /* Reload `rescan's local variables that describe the current
2606 level of the input stack. */
2609 do { ip = &instack[indepth]; \
2611 limit = ip->buf + ip->length; \
2613 check_expand (op, limit - ibp); \
2615 obp = op->bufp; } while (0)
2617 if (no_output && instack[indepth].fname != 0)
2618 skip_if_group (&instack[indepth], 1, NULL);
2625 /* Our caller must always put a null after the end of
2626 the input at each input stack level. */
2636 if (*ibp == '\n' && !ip->macro) {
2637 /* At the top level, always merge lines ending with backslash-newline,
2638 even in middle of identifier. But do not merge lines in a macro,
2639 since backslash might be followed by a newline-space marker. */
2642 --obp; /* remove backslash from obuf */
2645 /* If ANSI, backslash is just another character outside a string. */
2648 /* Otherwise, backslash suppresses specialness of following char,
2649 so copy it here to prevent the switch from seeing it.
2650 But first get any pending identifier processed. */
2651 if (ident_length > 0)
2658 if (ident_length || ip->macro || traditional)
2660 while (*ibp == '\\' && ibp[1] == '\n') {
2666 /* Treat this %: digraph as if it were #. */
2670 if (assertions_flag) {
2673 /* Copy #foo (bar lose) without macro expansion. */
2674 obp[-1] = '#'; /* In case it was '%'. */
2675 SKIP_WHITE_SPACE (ibp);
2676 while (is_idchar[*ibp])
2678 SKIP_WHITE_SPACE (ibp);
2681 skip_paren_group (ip);
2682 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2683 obp += ip->bufp - ibp;
2689 /* If this is expanding a macro definition, don't recognize
2690 preprocessing directives. */
2693 /* If this is expand_into_temp_buffer,
2694 don't recognize them either. Warn about them
2695 only after an actual newline at this level,
2696 not at the beginning of the input level. */
2698 if (ip->buf != beg_of_line)
2699 warning ("preprocessing directive not recognized within macro arg");
2706 /* # keyword: a # must be first nonblank char on the line */
2707 if (beg_of_line == 0)
2712 /* Scan from start of line, skipping whitespace, comments
2713 and backslash-newlines, and see if we reach this #.
2714 If not, this # is not special. */
2716 /* If -traditional, require # to be at beginning of line. */
2719 if (is_hor_space[*bp])
2721 else if (*bp == '\\' && bp[1] == '\n')
2723 else if (*bp == '/' && bp[1] == '*') {
2725 while (!(*bp == '*' && bp[1] == '/'))
2729 /* There is no point in trying to deal with C++ // comments here,
2730 because if there is one, then this # must be part of the
2731 comment and we would never reach here. */
2737 while (bp[1] == '\\' && bp[2] == '\n')
2741 /* %: appears at start of line; skip past the ':' too. */
2750 /* This # can start a directive. */
2752 --obp; /* Don't copy the '#' */
2756 if (! handle_directive (ip, op)) {
2760 /* Not a known directive: treat it as ordinary text.
2761 IP, OP, IBP, etc. have not been changed. */
2762 if (no_output && instack[indepth].fname) {
2763 /* If not generating expanded output,
2764 what we do with ordinary text is skip it.
2765 Discard everything until next # directive. */
2766 skip_if_group (&instack[indepth], 1, 0);
2771 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2772 /* Don't expand an identifier that could be a macro directive.
2773 (Section 3.8.3 of the ANSI C standard) */
2774 SKIP_WHITE_SPACE (ibp);
2775 if (is_idstart[*ibp])
2778 while (is_idchar[*ibp])
2786 /* A # directive has been successfully processed. */
2787 /* If not generating expanded output, ignore everything until
2788 next # directive. */
2789 if (no_output && instack[indepth].fname)
2790 skip_if_group (&instack[indepth], 1, 0);
2796 case '\"': /* skip quoted string */
2798 /* A single quoted string is treated like a double -- some
2799 programs (e.g., troff) are perverse this way */
2801 /* Handle any pending identifier;
2802 but the L in L'...' or L"..." is not an identifier. */
2804 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2806 ident_length = hash = 0;
2809 start_line = ip->lineno;
2811 /* Skip ahead to a matching quote. */
2815 if (ip->macro != 0) {
2816 /* try harder: this string crosses a macro expansion boundary.
2817 This can happen naturally if -traditional.
2818 Otherwise, only -D can make a macro with an unmatched quote. */
2824 error_with_line (line_for_error (start_line),
2825 "unterminated string or character constant");
2826 if (multiline_string_line) {
2827 error_with_line (multiline_string_line,
2828 "possible real start of unterminated constant");
2829 multiline_string_line = 0;
2839 /* Traditionally, end of line ends a string constant with no error.
2840 So exit the loop and record the new line. */
2846 error_with_line (line_for_error (start_line),
2847 "unterminated character constant");
2850 if (multiline_string_line == 0) {
2852 pedwarn_with_line (line_for_error (start_line),
2853 "string constant runs past end of line");
2854 multiline_string_line = ip->lineno - 1;
2860 /* Backslash newline is replaced by nothing at all, but
2861 keep the line counts correct. But if we are reading
2862 from a macro, keep the backslash newline, since backslash
2863 newlines have already been processed. */
2871 /* ANSI stupidly requires that in \\ the second \
2872 is *not* prevented from combining with a newline. */
2874 while (*ibp == '\\' && ibp[1] == '\n') {
2896 if (*ibp == '\\' && ibp[1] == '\n')
2899 && !(cplusplus_comments && *ibp == '/'))
2905 /* C++ style comment... */
2906 start_line = ip->lineno;
2908 /* Comments are equivalent to spaces. */
2909 if (! put_out_comments)
2913 U_CHAR *before_bp = ibp;
2915 while (++ibp < limit) {
2917 if (ibp[-1] != '\\') {
2918 if (put_out_comments) {
2919 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2920 obp += ibp - before_bp;
2925 warning ("multiline `//' comment");
2927 /* Copy the newline into the output buffer, in order to
2928 avoid the pain of a #line every time a multiline comment
2930 if (!put_out_comments)
2939 /* Ordinary C comment. Skip it, optionally copying it to output. */
2941 start_line = ip->lineno;
2943 ++ibp; /* Skip the star. */
2945 /* If this cpp is for lint, we peek inside the comments: */
2949 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2951 if (lintcmd != NULL) {
2953 check_expand (op, cmdlen + arglen + 14);
2955 /* I believe it is always safe to emit this newline: */
2957 bcopy ("#pragma lint ", (char *) obp, 13);
2959 bcopy (lintcmd, (char *) obp, cmdlen);
2964 bcopy (argbp, (char *) obp, arglen);
2968 /* OK, now bring us back to the state we were in before we entered
2969 this branch. We need #line because the #pragma's newline always
2970 messes up the line count. */
2972 output_line_directive (ip, op, 0, same_file);
2973 check_expand (op, limit - ibp + 2);
2979 /* Comments are equivalent to spaces.
2980 Note that we already output the slash; we might not want it.
2981 For -traditional, a comment is equivalent to nothing. */
2982 if (! put_out_comments) {
2992 U_CHAR *before_bp = ibp;
2997 if (ibp[-2] == '/' && warn_comments)
2998 warning ("`/*' within comment");
2999 if (*ibp == '\\' && ibp[1] == '\n')
3007 /* Copy the newline into the output buffer, in order to
3008 avoid the pain of a #line every time a multiline comment
3010 if (!put_out_comments)
3017 error_with_line (line_for_error (start_line),
3018 "unterminated comment");
3027 if (put_out_comments) {
3028 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3029 obp += ibp - before_bp;
3035 if (! is_idchar['$'])
3038 pedwarn ("`$' in identifier");
3041 case '0': case '1': case '2': case '3': case '4':
3042 case '5': case '6': case '7': case '8': case '9':
3043 /* If digit is not part of identifier, it starts a number,
3044 which means that following letters are not an identifier.
3045 "0x5" does not refer to an identifier "x5".
3046 So copy all alphanumerics that follow without accumulating
3047 as an identifier. Periods also, for sake of "3.e7". */
3049 if (ident_length == 0) {
3052 while (ibp[0] == '\\' && ibp[1] == '\n') {
3058 if (!is_idchar[c] && c != '.') {
3063 /* A sign can be part of a preprocessing number
3064 if it follows an `e' or `p'. */
3065 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3067 while (ibp[0] == '\\' && ibp[1] == '\n') {
3072 if (*ibp == '+' || *ibp == '-') {
3074 /* But traditional C does not let the token go past the sign,
3075 and C89 does not allow `p'. */
3076 if (traditional || (c89 && (c == 'p' || c == 'P')))
3086 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3087 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3088 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3089 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3091 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3092 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3093 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3094 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3098 /* Compute step of hash function, to avoid a proc call on every token */
3099 hash = HASHSTEP (hash, c);
3103 if (ip->fname == 0 && *ibp == '-') {
3104 /* Newline - inhibits expansion of preceding token.
3105 If expanding a macro arg, we keep the newline -.
3106 In final output, it is deleted.
3107 We recognize Newline - in macro bodies and macro args. */
3108 if (! concatenated) {
3113 if (!output_marks) {
3116 /* If expanding a macro arg, keep the newline -. */
3122 /* If reprocessing a macro expansion, newline is a special marker. */
3123 else if (ip->macro != 0) {
3124 /* Newline White is a "funny space" to separate tokens that are
3125 supposed to be separate but without space between.
3126 Here White means any whitespace character.
3127 Newline - marks a recursive macro use that is not
3128 supposed to be expandable. */
3130 if (is_space[*ibp]) {
3131 /* Newline Space does not prevent expansion of preceding token
3132 so expand the preceding token and then come back. */
3133 if (ident_length > 0)
3136 /* If generating final output, newline space makes a space. */
3137 if (!output_marks) {
3139 /* And Newline Newline makes a newline, so count it. */
3140 if (obp[-1] == '\n')
3143 /* If expanding a macro arg, keep the newline space.
3144 If the arg gets stringified, newline space makes nothing. */
3147 } else abort (); /* Newline followed by something random? */
3151 /* If there is a pending identifier, handle it and come back here. */
3152 if (ident_length > 0)
3157 /* Update the line counts and output a #line if necessary. */
3160 if (ip->lineno != op->lineno) {
3162 output_line_directive (ip, op, 1, same_file);
3163 check_expand (op, limit - ibp);
3168 /* Come here either after (1) a null character that is part of the input
3169 or (2) at the end of the input, because there is a null there. */
3172 /* Our input really contains a null character. */
3176 /* At end of a macro-expansion level, pop it and read next level. */
3177 if (ip->macro != 0) {
3180 /* If traditional, and we have an identifier that ends here,
3181 process it now, so we get the right error for recursion. */
3182 if (traditional && ident_length
3183 && ! is_idchar[*instack[indepth - 1].bufp]) {
3192 /* If we don't have a pending identifier,
3193 return at end of input. */
3194 if (ident_length == 0) {
3202 /* If we do have a pending identifier, just consider this null
3203 a special character and arrange to dispatch on it again.
3204 The second time, IDENT_LENGTH will be zero so we will return. */
3210 /* Handle the case of a character such as /, ', " or null
3211 seen following an identifier. Back over it so that
3212 after the identifier is processed the special char
3213 will be dispatched on again. */
3223 if (ident_length > 0) {
3224 register HASHNODE *hp;
3226 /* We have just seen an identifier end. If it's a macro, expand it.
3228 IDENT_LENGTH is the length of the identifier
3229 and HASH is its hash code.
3231 The identifier has already been copied to the output,
3232 so if it is a macro we must remove it.
3234 If REDO_CHAR is 0, the char that terminated the identifier
3235 has been skipped in the output and the input.
3236 OBP-IDENT_LENGTH-1 points to the identifier.
3237 If the identifier is a macro, we must back over the terminator.
3239 If REDO_CHAR is 1, the terminating char has already been
3240 backed over. OBP-IDENT_LENGTH points to the identifier. */
3242 if (!pcp_outfile || pcp_inside_if) {
3243 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3246 if (hp->length == ident_length) {
3247 int obufp_before_macroname;
3248 int op_lineno_before_macroname;
3249 register int i = ident_length;
3250 register U_CHAR *p = hp->name;
3251 register U_CHAR *q = obp - i;
3257 do { /* All this to avoid a strncmp () */
3262 /* We found a use of a macro name.
3263 see if the context shows it is a macro call. */
3265 /* Back up over terminating character if not already done. */
3271 /* Save this as a displacement from the beginning of the output
3272 buffer. We can not save this as a position in the output
3273 buffer, because it may get realloc'ed by RECACHE. */
3274 obufp_before_macroname = (obp - op->buf) - ident_length;
3275 op_lineno_before_macroname = op->lineno;
3277 if (hp->type == T_PCSTRING) {
3278 pcstring_used (hp); /* Mark the definition of this key
3279 as needed, ensuring that it
3281 break; /* Exit loop, since the key cannot have a
3282 definition any longer. */
3285 /* Record whether the macro is disabled. */
3286 disabled = hp->type == T_DISABLED;
3288 /* This looks like a macro ref, but if the macro was disabled,
3289 just copy its name and put in a marker if requested. */
3293 /* This error check caught useful cases such as
3294 #define foo(x,y) bar (x (y,0), y)
3297 error ("recursive use of macro `%s'", hp->name);
3301 check_expand (op, limit - ibp + 2);
3308 /* If macro wants an arglist, verify that a '(' follows.
3309 first skip all whitespace, copying it to the output
3310 after the macro name. Then, if there is no '(',
3311 decide this is not a macro call and leave things that way. */
3312 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3313 && hp->value.defn->nargs >= 0)
3315 U_CHAR *old_ibp = ibp;
3316 U_CHAR *old_obp = obp;
3317 int old_iln = ip->lineno;
3318 int old_oln = op->lineno;
3321 /* Scan forward over whitespace, copying it to the output. */
3322 if (ibp == limit && ip->macro != 0) {
3327 old_iln = ip->lineno;
3328 old_oln = op->lineno;
3330 else if (is_space[*ibp]) {
3332 if (ibp[-1] == '\n') {
3333 if (ip->macro == 0) {
3334 /* Newline in a file. Count it. */
3337 } else if (!output_marks) {
3338 /* A newline mark, and we don't want marks
3339 in the output. If it is newline-hyphen,
3340 discard it entirely. Otherwise, it is
3341 newline-whitechar, so keep the whitechar. */
3351 /* A newline mark; copy both chars to the output. */
3358 else if (*ibp == '/') {
3359 /* If a comment, copy it unchanged or discard it. */
3360 if (ibp[1] == '\\' && ibp[2] == '\n')
3361 newline_fix (ibp + 1);
3362 if (ibp[1] == '*') {
3363 if (put_out_comments) {
3366 } else if (! traditional) {
3369 for (ibp += 2; ibp < limit; ibp++) {
3370 /* We need not worry about newline-marks,
3371 since they are never found in comments. */
3372 if (ibp[0] == '*') {
3373 if (ibp[1] == '\\' && ibp[2] == '\n')
3374 newline_fix (ibp + 1);
3375 if (ibp[1] == '/') {
3377 if (put_out_comments) {
3385 /* Newline in a file. Count it. */
3389 if (put_out_comments)
3392 } else if (ibp[1] == '/' && cplusplus_comments) {
3393 if (put_out_comments) {
3396 } else if (! traditional) {
3399 for (ibp += 2; *ibp != '\n' || ibp[-1] == '\\'; ibp++)
3400 if (put_out_comments)
3405 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3412 /* It isn't a macro call.
3413 Put back the space that we just skipped. */
3416 ip->lineno = old_iln;
3417 op->lineno = old_oln;
3418 /* Exit the for loop. */
3423 /* This is now known to be a macro call.
3424 Discard the macro name from the output,
3425 along with any following whitespace just copied,
3426 but preserve newlines if not outputting marks since this
3427 is more likely to do the right thing with line numbers. */
3428 obp = op->buf + obufp_before_macroname;
3430 op->lineno = op_lineno_before_macroname;
3432 int newlines = op->lineno - op_lineno_before_macroname;
3433 while (0 < newlines--)
3437 /* Prevent accidental token-pasting with a character
3438 before the macro call. */
3439 if (!traditional && obp != op->buf) {
3441 case '!': case '%': case '&': case '*':
3442 case '+': case '-': case '.': case '/':
3443 case ':': case '<': case '=': case '>':
3445 /* If we are expanding a macro arg, make a newline marker
3446 to separate the tokens. If we are making real output,
3447 a plain space will do. */
3454 /* Expand the macro, reading arguments as needed,
3455 and push the expansion on the input stack. */
3458 macroexpand (hp, op);
3460 /* Reexamine input stack, since macroexpand has pushed
3461 a new level on it. */
3468 } /* End hash-table-search loop */
3470 ident_length = hash = 0; /* Stop collecting identifier */
3473 } /* End if (ident_length > 0) */
3475 } /* End per-char loop */
3477 /* Come here to return -- but first give an error message
3478 if there was an unterminated successful conditional. */
3480 if (if_stack != ip->if_stack)
3484 switch (if_stack->type)
3505 error_with_line (line_for_error (if_stack->lineno),
3506 "unterminated `#%s' conditional", str);
3508 if_stack = ip->if_stack;
3512 * Rescan a string into a temporary buffer and return the result
3513 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3515 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3516 * and insert such markers when appropriate. See `rescan' for details.
3517 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3518 * before substitution; it is 0 for other uses.
3521 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3522 U_CHAR *buf, *limit;
3523 int output_marks, assertions;
3525 register FILE_BUF *ip;
3527 int length = limit - buf;
3529 int odepth = indepth;
3530 int save_assertions_flag = assertions_flag;
3532 assertions_flag = assertions;
3537 /* Set up the input on the input stack. */
3539 buf1 = (U_CHAR *) alloca (length + 1);
3541 register U_CHAR *p1 = buf;
3542 register U_CHAR *p2 = buf1;
3549 /* Set up to receive the output. */
3551 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3552 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3553 obuf.nominal_fname = 0;
3560 obuf.system_header_p = 0;
3562 CHECK_DEPTH ({return obuf;});
3566 ip = &instack[indepth];
3568 ip->nominal_fname = 0;
3569 ip->nominal_fname_len = 0;
3571 ip->system_header_p = 0;
3574 ip->length = length;
3575 ip->buf = ip->bufp = buf1;
3576 ip->if_stack = if_stack;
3578 ip->lineno = obuf.lineno = 1;
3580 /* Scan the input, create the output. */
3581 rescan (&obuf, output_marks);
3583 /* Pop input stack to original state. */
3586 if (indepth != odepth)
3589 /* Record the output. */
3590 obuf.length = obuf.bufp - obuf.buf;
3592 assertions_flag = save_assertions_flag;
3597 * Process a # directive. Expects IP->bufp to point after the '#', as in
3598 * `#define foo bar'. Passes to the directive handler
3599 * (do_define, do_include, etc.): the addresses of the 1st and
3600 * last chars of the directive (starting immediately after the #
3601 * keyword), plus op and the keyword table pointer. If the directive
3602 * contains comments it is copied into a temporary buffer sans comments
3603 * and the temporary buffer is passed to the directive handler instead.
3604 * Likewise for backslash-newlines.
3606 * Returns nonzero if this was a known # directive.
3607 * Otherwise, returns zero, without advancing the input pointer.
3611 handle_directive (ip, op)
3614 register U_CHAR *bp, *cp;
3615 register struct directive *kt;
3616 register int ident_length;
3619 /* Nonzero means we must copy the entire directive
3620 to get rid of comments or backslash-newlines. */
3621 int copy_directive = 0;
3623 U_CHAR *ident, *after_ident;
3627 /* Record where the directive started. do_xifdef needs this. */
3628 directive_start = bp - 1;
3630 /* Skip whitespace and \-newline. */
3632 if (is_hor_space[*bp]) {
3633 if (*bp != ' ' && *bp != '\t' && pedantic)
3634 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3636 } else if (*bp == '/') {
3637 if (bp[1] == '\\' && bp[2] == '\n')
3638 newline_fix (bp + 1);
3639 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3642 skip_to_end_of_comment (ip, &ip->lineno, 0);
3644 } else if (*bp == '\\' && bp[1] == '\n') {
3645 bp += 2; ip->lineno++;
3649 /* Now find end of directive name.
3650 If we encounter a backslash-newline, exchange it with any following
3651 symbol-constituents so that we end up with a contiguous name. */
3658 if (*cp == '\\' && cp[1] == '\n')
3659 name_newline_fix (cp);
3665 ident_length = cp - bp;
3669 /* A line of just `#' becomes blank. */
3671 if (ident_length == 0 && *after_ident == '\n') {
3672 ip->bufp = after_ident;
3676 if (ident_length == 0 || !is_idstart[*ident]) {
3678 while (is_idchar[*p]) {
3679 if (*p < '0' || *p > '9')
3683 /* Handle # followed by a line number. */
3684 if (p != ident && !is_idchar[*p]) {
3685 static struct directive line_directive_table[] = {
3686 { 4, do_line, "line", T_LINE},
3689 pedwarn ("`#' followed by integer");
3690 after_ident = ident;
3691 kt = line_directive_table;
3695 /* Avoid error for `###' and similar cases unless -pedantic. */
3697 while (*p == '#' || is_hor_space[*p]) p++;
3699 if (pedantic && !lang_asm)
3700 warning ("invalid preprocessing directive");
3706 error ("invalid preprocessing directive name");
3712 * Decode the keyword and call the appropriate expansion
3713 * routine, after moving the input pointer up to the next line.
3715 for (kt = directive_table; kt->length > 0; kt++) {
3716 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3717 register U_CHAR *buf;
3718 register U_CHAR *limit;
3721 int *already_output;
3723 /* Nonzero means do not delete comments within the directive.
3724 #define needs this when -traditional. */
3729 limit = ip->buf + ip->length;
3732 keep_comments = traditional && kt->type == T_DEFINE;
3733 /* #import is defined only in Objective C, or when on the NeXT. */
3734 if (kt->type == T_IMPORT
3735 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3738 /* Find the end of this directive (first newline not backslashed
3739 and not in a string or comment).
3740 Set COPY_DIRECTIVE if the directive must be copied
3741 (it contains a backslash-newline or a comment). */
3743 buf = bp = after_ident;
3744 while (bp < limit) {
3745 register U_CHAR c = *bp++;
3753 } else if (traditional)
3759 /* "..." is special for #include. */
3760 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3761 while (bp < limit && *bp != '\n') {
3766 if (*bp == '\\' && bp[1] == '\n') {
3777 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3778 /* Don't bother calling the directive if we already got an error
3779 message due to unterminated string. Skip everything and pretend
3780 we called the directive. */
3783 /* Traditional preprocessing permits unterminated strings. */
3792 /* <...> is special for #include. */
3794 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3796 while (bp < limit && *bp != '>' && *bp != '\n') {
3797 if (*bp == '\\' && bp[1] == '\n') {
3807 if (*bp == '\\' && bp[1] == '\n')
3810 || (cplusplus_comments && *bp == '/')) {
3811 U_CHAR *obp = bp - 1;
3813 skip_to_end_of_comment (ip, &ip->lineno, 0);
3815 /* No need to copy the directive because of a comment at the end;
3816 just don't include the comment in the directive. */
3817 if (!put_out_comments) {
3819 for (p = bp; *p == ' ' || *p == '\t'; p++)
3826 /* Don't remove the comments if -traditional. */
3827 if (! keep_comments)
3836 pedwarn ("%s in preprocessing directive", char_name[c]);
3840 --bp; /* Point to the newline */
3848 resume_p = ip->bufp;
3849 /* BP is the end of the directive.
3850 RESUME_P is the next interesting data after the directive.
3851 A comment may come between. */
3853 /* If a directive should be copied through, and -C was given,
3854 pass it through before removing comments. */
3855 if (!no_output && put_out_comments
3856 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
3857 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3858 : kt->type == T_PRAGMA)) {
3861 /* Output directive name. */
3862 check_expand (op, kt->length + 2);
3863 /* Make sure # is at the start of a line */
3864 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3869 bcopy (kt->name, op->bufp, kt->length);
3870 op->bufp += kt->length;
3872 /* Output arguments. */
3874 check_expand (op, len);
3875 bcopy (buf, (char *) op->bufp, len);
3877 /* Take account of any (escaped) newlines just output. */
3879 if (buf[len] == '\n')
3882 already_output = &junk;
3883 } /* Don't we need a newline or #line? */
3885 if (copy_directive) {
3886 register U_CHAR *xp = buf;
3887 /* Need to copy entire directive into temp buffer before dispatching */
3889 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3893 /* Copy to the new buffer, deleting comments
3894 and backslash-newlines (and whitespace surrounding the latter). */
3897 register U_CHAR c = *xp++;
3902 abort (); /* A bare newline should never part of the line. */
3905 /* <...> is special for #include. */
3907 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3909 while (xp < bp && c != '>') {
3911 if (c == '\\' && xp < bp && *xp == '\n')
3922 if (cp != buf && is_hor_space[cp[-1]]) {
3923 while (cp - 1 != buf && is_hor_space[cp[-2]])
3925 SKIP_WHITE_SPACE (xp);
3926 } else if (is_hor_space[*xp]) {
3928 SKIP_WHITE_SPACE (xp);
3930 } else if (traditional && xp < bp) {
3938 register U_CHAR *bp1
3939 = skip_quoted_string (xp - 1, bp, ip->lineno,
3940 NULL_PTR, NULL_PTR, NULL_PTR);
3948 || (cplusplus_comments && *xp == '/')) {
3950 /* If we already copied the directive through,
3951 already_output != 0 prevents outputting comment now. */
3952 skip_to_end_of_comment (ip, already_output, 0);
3954 while (xp != ip->bufp)
3956 /* Delete or replace the slash. */
3957 else if (traditional)
3966 /* Null-terminate the copy. */
3972 ip->bufp = resume_p;
3974 /* Some directives should be written out for cc1 to process,
3975 just as if they were not defined. And sometimes we're copying
3976 directives through. */
3978 if (!no_output && already_output == 0
3979 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
3980 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3981 : kt->type == T_PRAGMA)) {
3984 /* Output directive name. */
3985 check_expand (op, kt->length + 1);
3987 bcopy (kt->name, (char *) op->bufp, kt->length);
3988 op->bufp += kt->length;
3990 if (kt->type == T_DEFINE && dump_macros == dump_names) {
3991 /* Output `#define name' only. */
3994 SKIP_WHITE_SPACE (xp);
3996 while (is_idchar[*xp]) xp++;
3998 check_expand (op, len + 1);
4000 bcopy (yp, (char *) op->bufp, len);
4002 /* Output entire directive. */
4004 check_expand (op, len);
4005 bcopy (buf, (char *) op->bufp, len);
4008 } /* Don't we need a newline or #line? */
4010 /* Call the appropriate directive handler. buf now points to
4011 either the appropriate place in the input buffer, or to
4012 the temp buffer if it was necessary to make one. cp
4013 points to the first char after the contents of the (possibly
4014 copied) directive, in either case. */
4015 (*kt->func) (buf, cp, op, kt);
4016 check_expand (op, ip->length - (ip->bufp - ip->buf));
4022 /* It is deliberate that we don't warn about undefined directives.
4023 That is the responsibility of cc1. */
4030 static struct tm *timebuf;
4032 time_t t = time ((time_t *) 0);
4033 timebuf = localtime (&t);
4038 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4039 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4043 * expand things like __FILE__. Place the expansion into the output
4044 * buffer *without* rescanning.
4048 special_symbol (hp, op)
4055 FILE_BUF *ip = NULL;
4058 int paren = 0; /* For special `defined' keyword */
4060 if (pcp_outfile && pcp_inside_if
4061 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4062 error ("Predefined macro `%s' used inside `#if' during precompilation",
4065 for (i = indepth; i >= 0; i--)
4066 if (instack[i].fname != NULL) {
4071 error ("cccp error: not in any file?!");
4072 return; /* the show must go on */
4079 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4080 char *string = p->nominal_fname;
4084 size_t string_len = p->nominal_fname_len;
4085 buf = (char *) alloca (3 + 4 * string_len);
4086 quote_string (buf, string, string_len);
4094 case T_INCLUDE_LEVEL:
4096 for (i = indepth; i >= 0; i--)
4097 if (instack[i].fname != NULL)
4100 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4101 sprintf (buf, "%d", true_indepth - 1);
4105 buf = (char *) alloca (3 + strlen (version_string));
4106 sprintf (buf, "\"%s\"", version_string);
4109 #ifndef NO_BUILTIN_SIZE_TYPE
4115 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4116 case T_PTRDIFF_TYPE:
4125 case T_USER_LABEL_PREFIX_TYPE:
4126 buf = USER_LABEL_PREFIX;
4129 case T_REGISTER_PREFIX_TYPE:
4130 buf = REGISTER_PREFIX;
4133 case T_IMMEDIATE_PREFIX_TYPE:
4134 buf = IMMEDIATE_PREFIX;
4138 buf = hp->value.cpval;
4139 #ifdef STDC_0_IN_SYSTEM_HEADERS
4140 if (ip->system_header_p
4141 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4142 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4145 if (pcp_inside_if && pcp_outfile)
4146 /* Output a precondition for this macro use */
4147 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4151 buf = (char *) alloca (10);
4152 sprintf (buf, "%d", ip->lineno);
4157 buf = (char *) alloca (20);
4158 timebuf = timestamp ();
4159 if (hp->type == T_DATE)
4160 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4161 timebuf->tm_mday, timebuf->tm_year + 1900);
4163 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4167 case T_SPEC_DEFINED:
4168 buf = " 0 "; /* Assume symbol is not defined */
4169 ip = &instack[indepth];
4170 SKIP_WHITE_SPACE (ip->bufp);
4171 if (*ip->bufp == '(') {
4173 ip->bufp++; /* Skip over the paren */
4174 SKIP_WHITE_SPACE (ip->bufp);
4177 if (!is_idstart[*ip->bufp])
4179 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4181 if ((hp = lookup (ip->bufp, -1, -1))) {
4182 if (pcp_outfile && pcp_inside_if
4183 && (hp->type == T_CONST
4184 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4185 /* Output a precondition for this macro use. */
4186 fprintf (pcp_outfile, "#define %s\n", hp->name);
4190 if (pcp_outfile && pcp_inside_if) {
4191 /* Output a precondition for this macro use */
4192 U_CHAR *cp = ip->bufp;
4193 fprintf (pcp_outfile, "#undef ");
4194 while (is_idchar[*cp]) /* Ick! */
4195 fputc (*cp++, pcp_outfile);
4196 putc ('\n', pcp_outfile);
4198 while (is_idchar[*ip->bufp])
4200 SKIP_WHITE_SPACE (ip->bufp);
4202 if (*ip->bufp != ')')
4210 error ("`defined' without an identifier");
4214 error ("cccp error: invalid special hash type"); /* time for gdb */
4218 check_expand (op, len);
4219 bcopy (buf, (char *) op->bufp, len);
4226 /* Routines to handle #directives */
4228 /* Handle #include and #import.
4229 This function expects to see "fname" or <fname> on the input. */
4232 do_include (buf, limit, op, keyword)
4233 U_CHAR *buf, *limit;
4235 struct directive *keyword;
4237 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4238 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4239 static int import_warning = 0;
4240 char *fname; /* Dynamically allocated fname buffer */
4243 char *fbeg, *fend; /* Beginning and end of fname */
4246 struct file_name_list *search_start = include; /* Chain of dirs to search */
4247 struct file_name_list *dsp; /* First in chain, if #include "..." */
4248 struct file_name_list *searchptr = 0;
4251 int f = -3; /* file number */
4252 struct include_file *inc = 0;
4254 int retried = 0; /* Have already tried macro
4255 expanding the include line*/
4256 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4258 int vaxc_include = 0; /* 1 for token without punctuation */
4265 if (pedantic && !instack[indepth].system_header_p)
4268 pedwarn ("ANSI C does not allow `#import'");
4270 pedwarn ("ANSI C does not allow `#include_next'");
4273 if (importing && warn_import && !inhibit_warnings
4274 && !instack[indepth].system_header_p && !import_warning) {
4276 warning ("using `#import' is not recommended");
4277 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4278 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4279 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4280 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4281 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4282 fprintf (stderr, " ... <real contents of file> ...\n");
4283 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4284 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4285 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4286 fprintf (stderr, "when it is equipped with such a conditional.\n");
4292 SKIP_WHITE_SPACE (fin);
4293 /* Discard trailing whitespace so we can easily see
4294 if we have parsed all the significant chars we were given. */
4295 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4296 fbeg = fend = (char *) alloca (limit - fin);
4302 /* Copy the operand text, concatenating the strings. */
4307 goto invalid_include_file_name;
4315 /* If not at the end, there had better be another string. */
4316 /* Skip just horiz space, and don't go past limit. */
4317 while (fin != limit && is_hor_space[*fin]) fin++;
4318 if (fin != limit && *fin == '\"')
4325 /* We have "filename". Figure out directory this source
4326 file is coming from and put it on the front of the list. */
4328 /* If -I- was specified, don't search current dir, only spec'd ones. */
4329 if (ignore_srcdir) break;
4331 for (fp = &instack[indepth]; fp >= instack; fp--)
4336 if ((nam = fp->nominal_fname) != NULL) {
4337 /* Found a named file. Figure out dir of the file,
4338 and put it in front of the search list. */
4339 dsp = ((struct file_name_list *)
4340 alloca (sizeof (struct file_name_list)
4341 + fp->nominal_fname_len));
4342 strcpy (dsp->fname, nam);
4343 simplify_filename (dsp->fname);
4344 nam = base_name (dsp->fname);
4346 /* But for efficiency's sake, do not insert the dir
4347 if it matches the search list's first dir. */
4348 dsp->next = search_start;
4349 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4351 n = nam - dsp->fname;
4352 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4353 max_include_len = n + INCLUDE_LEN_FUDGE;
4355 dsp[0].got_name_map = 0;
4363 while (fin != limit && *fin != '>')
4365 if (*fin == '>' && fin + 1 == limit) {
4367 /* If -I-, start with the first -I dir after the -I-. */
4368 search_start = first_bracket_include;
4376 * Support '#include xyz' like VAX-C to allow for easy use of all the
4377 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4378 * code from case '<' is repeated here) and generates a warning.
4379 * (Note: macro expansion of `xyz' takes precedence.)
4381 if (retried && isalpha(*(U_CHAR *) (--fbeg))) {
4382 while (fin != limit && (!isspace(*fin)))
4384 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4388 /* If -I-, start with the first -I dir after the -I-. */
4389 search_start = first_bracket_include;
4397 /* Expand buffer and then remove any newline markers.
4398 We can't just tell expand_to_temp_buffer to omit the markers,
4399 since it would put extra spaces in include file names. */
4402 int errors_before_expansion = errors;
4403 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4404 if (errors != errors_before_expansion) {
4406 goto invalid_include_file_name;
4409 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4411 while (src != trybuf.bufp) {
4412 switch ((*limit++ = *src++)) {
4421 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4422 NULL_PTR, NULL_PTR, NULL_PTR);
4435 invalid_include_file_name:
4436 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4440 /* For #include_next, skip in the search path
4441 past the dir in which the containing file was found. */
4444 for (fp = &instack[indepth]; fp >= instack; fp--)
4445 if (fp->fname != NULL) {
4446 /* fp->dir is null if the containing file was specified
4447 with an absolute file name. In that case, don't skip anything. */
4449 search_start = fp->dir->next;
4455 flen = simplify_filename (fbeg);
4459 error ("empty file name in `#%s'", keyword->name);
4463 /* Allocate this permanently, because it gets stored in the definitions
4465 fname = xmalloc (max_include_len + flen + 1);
4466 /* + 1 above for terminating null. */
4468 system_include_depth += angle_brackets;
4470 /* If specified file name is absolute, just open it. */
4472 if (absolute_filename (fbeg)) {
4473 strcpy (fname, fbeg);
4474 f = open_include_file (fname, NULL_PTR, importing, &inc);
4478 struct bypass_dir *next;
4480 struct file_name_list *searchptr;
4481 } **bypass_slot = 0;
4483 /* Search directory path, trying to open the file.
4484 Copy each filename tried into FNAME. */
4486 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4488 if (searchptr == first_bracket_include) {
4489 /* Go to bypass directory if we know we've seen this file before. */
4490 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4491 struct bypass_dir *p;
4492 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4494 for (p = *bypass_slot; p; p = p->next)
4495 if (!strcmp (fbeg, p->fname)) {
4496 searchptr = p->searchptr;
4502 strcpy (fname, searchptr->fname);
4503 strcat (fname, fbeg);
4505 /* Change this 1/2 Unix 1/2 VMS file specification into a
4506 full VMS file specification */
4507 if (searchptr->fname[0]) {
4508 /* Fix up the filename */
4509 hack_vms_include_specification (fname, vaxc_include);
4511 /* This is a normal VMS filespec, so use it unchanged. */
4512 strcpy (fname, fbeg);
4513 /* if it's '#include filename', add the missing .h */
4514 if (vaxc_include && index(fname,'.')==NULL) {
4515 strcat (fname, ".h");
4519 f = open_include_file (fname, searchptr, importing, &inc);
4521 if (bypass_slot && searchptr != first_bracket_include) {
4522 /* This is the first time we found this include file,
4523 and we found it after first_bracket_include.
4524 Record its location so that we can bypass to here next time. */
4525 struct bypass_dir *p
4526 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4527 p->next = *bypass_slot;
4528 p->fname = fname + strlen (searchptr->fname);
4529 p->searchptr = searchptr;
4535 /* Our VMS hacks can produce invalid filespecs, so don't worry
4536 about errors other than EACCES. */
4537 if (errno == EACCES)
4540 if (errno != ENOENT && errno != ENOTDIR)
4550 /* The file was already included. */
4552 /* If generating dependencies and -MG was specified, we assume missing
4553 files are leaf files, living in the same directory as the source file
4554 or other similar place; these missing files may be generated from
4555 other files and may not exist yet (eg: y.tab.h). */
4556 } else if (print_deps_missing_files
4557 && (system_include_depth != 0) < print_deps)
4559 /* If it was requested as a system header file,
4560 then assume it belongs in the first place to look for such. */
4564 char *p = (char *) alloca (strlen (search_start->fname)
4565 + strlen (fbeg) + 1);
4566 strcpy (p, search_start->fname);
4568 deps_output (p, ' ');
4573 /* Otherwise, omit the directory, as if the file existed
4574 in the directory with the source. */
4575 deps_output (fbeg, ' ');
4578 /* If -M was specified, and this header file won't be added to the
4579 dependency list, then don't count this as an error, because we can
4580 still produce correct output. Otherwise, we can't produce correct
4581 output, because there may be dependencies we need inside the missing
4582 file, and we don't know what directory this missing file exists in. */
4583 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4584 warning ("No include path in which to find %s", fbeg);
4586 error_from_errno (fbeg);
4588 error ("No include path in which to find %s", fbeg);
4592 /* Actually process the file. */
4594 pcftry = (char *) alloca (strlen (fname) + 30);
4601 sprintf (pcftry, "%s%d", fname, pcfnum++);
4603 pcf = open (pcftry, O_RDONLY, 0666);
4608 if (fstat (pcf, &s) != 0)
4609 pfatal_with_name (pcftry);
4610 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4611 || inc->st.st_dev != s.st_dev)
4613 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4614 /* Don't need it any more. */
4619 /* Don't need it at all. */
4624 } while (pcf != -1 && !pcfbuf);
4627 /* Actually process the file */
4629 pcfname = xmalloc (strlen (pcftry) + 1);
4630 strcpy (pcfname, pcftry);
4631 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4632 (U_CHAR *) fname, op);
4635 finclude (f, inc, op, is_system_include (fname), searchptr);
4638 system_include_depth -= angle_brackets;
4643 /* Return nonzero if the given FILENAME is an absolute pathname which
4644 designates a file within one of the known "system" include file
4645 directories. We assume here that if the given FILENAME looks like
4646 it is the name of a file which resides either directly in a "system"
4647 include file directory, or within any subdirectory thereof, then the
4648 given file must be a "system" include file. This function tells us
4649 if we should suppress pedantic errors/warnings for the given FILENAME.
4651 The value is 2 if the file is a C-language system header file
4652 for which C++ should (on most systems) assume `extern "C"'. */
4655 is_system_include (filename)
4656 register char *filename;
4658 struct file_name_list *searchptr;
4660 for (searchptr = first_system_include; searchptr;
4661 searchptr = searchptr->next)
4662 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4663 return searchptr->c_system_include_path + 1;
4667 /* Yield the non-directory suffix of a file name. */
4675 #if defined (__MSDOS__) || defined (_WIN32)
4676 if (isalpha (s[0]) && s[1] == ':') s += 2;
4679 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4680 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4681 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4685 if ((p = rindex (s, '/'))) s = p + 1;
4686 #ifdef DIR_SEPARATOR
4687 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4692 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4695 absolute_filename (filename)
4698 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4699 if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4701 #if defined (__CYGWIN32__)
4702 /* At present, any path that begins with a drive spec is absolute. */
4703 if (isalpha (filename[0]) && filename[1] == ':') return 1;
4705 if (filename[0] == '/') return 1;
4706 #ifdef DIR_SEPARATOR
4707 if (filename[0] == DIR_SEPARATOR) return 1;
4712 /* Remove unnecessary characters from FILENAME in place,
4713 to avoid unnecessary filename aliasing.
4714 Return the length of the resulting string.
4716 Do only the simplifications allowed by Posix.
4717 It is OK to miss simplifications on non-Posix hosts,
4718 since this merely leads to suboptimal results. */
4721 simplify_filename (filename)
4724 register char *from = filename;
4725 register char *to = filename;
4728 /* Remove redundant initial /s. */
4731 if (*++from == '/') {
4732 if (*++from == '/') {
4733 /* 3 or more initial /s are equivalent to 1 /. */
4734 while (*++from == '/')
4737 /* On some hosts // differs from /; Posix allows this. */
4738 static int slashslash_vs_slash;
4739 if (slashslash_vs_slash == 0) {
4741 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4742 && INO_T_EQ (s1.st_ino, s2.st_ino)
4743 && s1.st_dev == s2.st_dev)
4746 if (slashslash_vs_slash < 0)
4754 if (from[0] == '.' && from[1] == '/')
4757 /* Copy this component and trailing /, if any. */
4758 while ((*to++ = *from++) != '/') {
4760 /* Trim . component at end of nonempty name. */
4761 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4763 /* Trim unnecessary trailing /s. */
4764 while (to0 < --to && to[-1] == '/')
4768 return to - filename;
4773 /* Skip /s after a /. */
4774 while (*from == '/')
4779 /* The file_name_map structure holds a mapping of file names for a
4780 particular directory. This mapping is read from the file named
4781 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4782 map filenames on a file system with severe filename restrictions,
4783 such as DOS. The format of the file name map file is just a series
4784 of lines with two tokens on each line. The first token is the name
4785 to map, and the second token is the actual name to use. */
4787 struct file_name_map
4789 struct file_name_map *map_next;
4794 #define FILE_NAME_MAP_FILE "header.gcc"
4796 /* Read a space delimited string of unlimited length from a stdio
4800 read_filename_string (ch, f)
4808 set = alloc = xmalloc (len + 1);
4812 while ((ch = getc (f)) != EOF && ! is_space[ch])
4814 if (set - alloc == len)
4817 alloc = xrealloc (alloc, len + 1);
4818 set = alloc + len / 2;
4828 /* Read the file name map file for DIRNAME.
4829 If DIRNAME is empty, read the map file for the working directory;
4830 otherwise DIRNAME must end in '/'. */
4832 static struct file_name_map *
4833 read_name_map (dirname)
4836 /* This structure holds a linked list of file name maps, one per
4838 struct file_name_map_list
4840 struct file_name_map_list *map_list_next;
4841 char *map_list_name;
4842 struct file_name_map *map_list_map;
4844 static struct file_name_map_list *map_list;
4845 register struct file_name_map_list *map_list_ptr;
4850 for (map_list_ptr = map_list; map_list_ptr;
4851 map_list_ptr = map_list_ptr->map_list_next)
4852 if (! strcmp (map_list_ptr->map_list_name, dirname))
4853 return map_list_ptr->map_list_map;
4855 map_list_ptr = ((struct file_name_map_list *)
4856 xmalloc (sizeof (struct file_name_map_list)));
4857 map_list_ptr->map_list_name = savestring (dirname);
4858 map_list_ptr->map_list_map = NULL;
4860 dirlen = strlen (dirname);
4861 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4862 strcpy (name, dirname);
4863 strcat (name, FILE_NAME_MAP_FILE);
4864 f = fopen (name, "r");
4866 map_list_ptr->map_list_map = NULL;
4871 while ((ch = getc (f)) != EOF)
4874 struct file_name_map *ptr;
4879 from = read_filename_string (ch, f);
4880 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4882 to = read_filename_string (ch, f);
4884 simplify_filename (from);
4885 tolen = simplify_filename (to);
4887 ptr = ((struct file_name_map *)
4888 xmalloc (sizeof (struct file_name_map)));
4889 ptr->map_from = from;
4891 /* Make the real filename absolute. */
4892 if (absolute_filename (to))
4896 ptr->map_to = xmalloc (dirlen + tolen + 1);
4897 strcpy (ptr->map_to, dirname);
4898 strcat (ptr->map_to, to);
4902 ptr->map_next = map_list_ptr->map_list_map;
4903 map_list_ptr->map_list_map = ptr;
4905 while ((ch = getc (f)) != '\n')
4912 map_list_ptr->map_list_next = map_list;
4913 map_list = map_list_ptr;
4915 return map_list_ptr->map_list_map;
4918 /* Try to open include file FILENAME. SEARCHPTR is the directory
4919 being tried from the include file search path.
4920 IMPORTING is "" if we are importing, null otherwise.
4921 Return -2 if found, either a matching name or a matching inode.
4922 Otherwise, open the file and return a file descriptor if successful
4923 or -1 if unsuccessful.
4924 Unless unsuccessful, put a descriptor of the included file into *PINC.
4925 This function maps filenames on file systems based on information read by
4929 open_include_file (filename, searchptr, importing, pinc)
4931 struct file_name_list *searchptr;
4933 struct include_file **pinc;
4935 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
4938 /* Look up FNAME in include_hashtab. */
4939 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4942 struct include_file *inc, *head = *phead;
4943 for (inc = head; inc; inc = inc->next)
4944 if (!strcmp (fname, inc->fname))
4948 || ! inc->control_macro
4949 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4951 fd = open (fname, O_RDONLY, 0);
4957 /* FNAME was not in include_hashtab; insert a new entry. */
4958 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4961 inc->control_macro = 0;
4962 inc->deps_output = 0;
4963 if (fstat (fd, &inc->st) != 0)
4964 pfatal_with_name (fname);
4967 /* Look for another file with the same inode and device. */
4968 if (lookup_ino_include (inc)
4969 && inc->control_macro
4970 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4976 /* For -M, add this file to the dependencies. */
4977 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4978 inc->deps_output = 1;
4979 deps_output (fname, ' ');
4982 /* Handle -H option. */
4983 if (print_include_names)
4984 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4988 inc->control_macro = importing;
4994 /* Return the remapped name of the the include file FILENAME.
4995 SEARCHPTR is the directory being tried from the include file path. */
4998 remap_include_file (filename, searchptr)
5000 struct file_name_list *searchptr;
5002 register struct file_name_map *map;
5003 register char *from;
5007 if (! searchptr->got_name_map)
5009 searchptr->name_map = read_name_map (searchptr->fname);
5010 searchptr->got_name_map = 1;
5013 /* Check the mapping for the directory we are using. */
5014 from = filename + strlen (searchptr->fname);
5015 for (map = searchptr->name_map; map; map = map->map_next)
5016 if (! strcmp (map->map_from, from))
5020 from = base_name (filename);
5022 if (from != filename || !searchptr)
5024 /* Try to find a mapping file for the particular directory we are
5025 looking in. Thus #include <sys/types.h> will look up sys/types.h
5026 in /usr/include/header.gcc and look up types.h in
5027 /usr/include/sys/header.gcc. */
5029 char *dir = (char *) alloca (from - filename + 1);
5030 bcopy (filename, dir, from - filename);
5031 dir[from - filename] = '\0';
5033 for (map = read_name_map (dir); map; map = map->map_next)
5034 if (! strcmp (map->map_from, from))
5041 /* Insert INC into the include file table, hashed by device and inode number.
5042 If a file with different name but same dev+ino was already in the table,
5043 return 1 and set INC's control macro to the already-known macro. */
5046 lookup_ino_include (inc)
5047 struct include_file *inc;
5049 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5050 % INCLUDE_HASHSIZE);
5051 struct include_file *i = include_ino_hashtab[hash];
5053 include_ino_hashtab[hash] = inc;
5055 for (; i; i = i->next_ino)
5056 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5057 && inc->st.st_dev == i->st.st_dev) {
5058 inc->control_macro = i->control_macro;
5065 /* Process file descriptor F, which corresponds to include file INC,
5067 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5068 "system" include directories (as decided by the `is_system_include'
5070 DIRPTR is the link in the dir path through which this file was found,
5071 or 0 if the file name was absolute. */
5074 finclude (f, inc, op, system_header_p, dirptr)
5076 struct include_file *inc;
5078 int system_header_p;
5079 struct file_name_list *dirptr;
5081 char *fname = inc->fname;
5083 FILE_BUF *fp; /* For input stack frame */
5084 int missing_newline = 0;
5086 CHECK_DEPTH (return;);
5088 fp = &instack[indepth + 1];
5089 bzero ((char *) fp, sizeof (FILE_BUF));
5090 fp->nominal_fname = fp->fname = fname;
5091 fp->nominal_fname_len = strlen (fname);
5095 fp->if_stack = if_stack;
5096 fp->system_header_p = system_header_p;
5099 if (S_ISREG (inc->st.st_mode)) {
5100 size_t s = (size_t) inc->st.st_size;
5101 if (s != inc->st.st_size || s + 2 < s)
5103 fp->buf = (U_CHAR *) xmalloc (s + 2);
5106 /* Read the file contents, knowing that s is an upper bound
5107 on the number of bytes we can read. */
5108 fp->length = safe_read (f, (char *) fp->buf, s);
5109 if (fp->length < 0) goto nope;
5111 else if (S_ISDIR (inc->st.st_mode)) {
5112 error ("directory `%s' specified in #include", fname);
5116 /* Cannot count its file size before reading.
5117 First read the entire file into heap and
5118 copy them into buffer on stack. */
5123 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5126 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5128 goto nope; /* error! */
5130 if (st_size != bsize)
5131 break; /* End of file */
5133 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5136 fp->length = st_size;
5139 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5140 /* Backslash-newline at end is not good enough. */
5141 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5142 fp->buf[fp->length++] = '\n';
5143 missing_newline = 1;
5145 fp->buf[fp->length] = '\0';
5147 /* Close descriptor now, so nesting does not use lots of descriptors. */
5150 /* Must do this before calling trigraph_pcp, so that the correct file name
5151 will be printed in warning messages. */
5154 input_file_stack_tick++;
5159 output_line_directive (fp, op, 0, enter_file);
5162 if (missing_newline)
5165 if (pedantic && missing_newline)
5166 pedwarn ("file does not end in newline");
5169 input_file_stack_tick++;
5170 output_line_directive (&instack[indepth], op, 0, leave_file);
5176 perror_with_name (fname);
5181 /* Record that inclusion of the include file INC
5182 should be controlled by the macro named MACRO_NAME.
5183 This means that trying to include the file again
5184 will do something if that macro is defined. */
5187 record_control_macro (inc, macro_name)
5188 struct include_file *inc;
5191 if (!inc->control_macro || inc->control_macro[0])
5192 inc->control_macro = macro_name;
5195 /* Load the specified precompiled header into core, and verify its
5196 preconditions. PCF indicates the file descriptor to read, which must
5197 be a regular file. *ST is its file status.
5198 FNAME indicates the file name of the original header.
5199 *LIMIT will be set to an address one past the end of the file.
5200 If the preconditions of the file are not satisfied, the buffer is
5201 freed and we return 0. If the preconditions are satisfied, return
5202 the address of the buffer following the preconditions. The buffer, in
5203 this case, should never be freed because various pieces of it will
5204 be referred to until all precompiled strings are output at the end of
5208 check_precompiled (pcf, st, fname, limit)
5221 if (S_ISREG (st->st_mode))
5223 size_t s = (size_t) st->st_size;
5224 if (s != st->st_size || s + 2 < s)
5226 buf = xmalloc (s + 2);
5227 length = safe_read (pcf, buf, s);
5234 if (length > 0 && buf[length-1] != '\n')
5235 buf[length++] = '\n';
5238 *limit = buf + length;
5240 /* File is in core. Check the preconditions. */
5241 if (!check_preconditions (buf))
5243 for (cp = buf; *cp; cp++)
5246 fprintf (stderr, "Using preinclude %s\n", fname);
5252 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5258 /* PREC (null terminated) points to the preconditions of a
5259 precompiled header. These are a series of #define and #undef
5260 lines which must match the current contents of the hash
5264 check_preconditions (prec)
5271 lineend = index (prec, '\n');
5273 if (*prec++ != '#') {
5274 error ("Bad format encountered while reading precompiled file");
5277 if (!strncmp (prec, "define", 6)) {
5281 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5286 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5287 || (hp->type != T_MACRO && hp->type != T_CONST)
5288 || (hp->type == T_MACRO
5289 && !compare_defs (mdef.defn, hp->value.defn)
5290 && (mdef.defn->length != 2
5291 || mdef.defn->expansion[0] != '\n'
5292 || mdef.defn->expansion[1] != ' ')))
5294 } else if (!strncmp (prec, "undef", 5)) {
5299 while (is_hor_space[(U_CHAR) *prec])
5302 while (is_idchar[(U_CHAR) *prec])
5306 if (lookup ((U_CHAR *) name, len, -1))
5309 error ("Bad format encountered while reading precompiled file");
5314 /* They all passed successfully */
5318 /* Process the main body of a precompiled file. BUF points to the
5319 string section of the file, following the preconditions. LIMIT is one
5320 character past the end. NAME is the name of the file being read
5321 in. OP is the main output buffer. */
5324 pcfinclude (buf, limit, name, op)
5325 U_CHAR *buf, *limit, *name;
5332 /* First in the file comes 4 bytes indicating the number of strings, */
5333 /* in network byte order. (MSB first). */
5335 nstrings = (nstrings << 8) | *cp++;
5336 nstrings = (nstrings << 8) | *cp++;
5337 nstrings = (nstrings << 8) | *cp++;
5339 /* Looping over each string... */
5340 while (nstrings--) {
5341 U_CHAR *string_start;
5342 U_CHAR *endofthiskey;
5346 /* Each string starts with a STRINGDEF structure (str), followed */
5347 /* by the text of the string (string_start) */
5349 /* First skip to a longword boundary */
5350 /* ??? Why a 4-byte boundary? On all machines? */
5351 /* NOTE: This works correctly even if size_t
5352 is narrower than a pointer.
5353 Do not try risky measures here to get another type to use!
5354 Do not include stddef.h--it will fail! */
5355 if ((size_t) cp & 3)
5356 cp += 4 - ((size_t) cp & 3);
5358 /* Now get the string. */
5359 str = (STRINGDEF *) (GENERIC_PTR) cp;
5360 string_start = cp += sizeof (STRINGDEF);
5362 for (; *cp; cp++) /* skip the string */
5365 /* We need to macro expand the string here to ensure that the
5366 proper definition environment is in place. If it were only
5367 expanded when we find out it is needed, macros necessary for
5368 its proper expansion might have had their definitions changed. */
5369 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5370 /* Lineno is already set in the precompiled file */
5371 str->contents = tmpbuf.buf;
5372 str->len = tmpbuf.length;
5374 str->filename = name;
5375 str->output_mark = outbuf.bufp - outbuf.buf;
5378 *stringlist_tailp = str;
5379 stringlist_tailp = &str->chain;
5381 /* Next comes a fourbyte number indicating the number of keys
5384 nkeys = (nkeys << 8) | *cp++;
5385 nkeys = (nkeys << 8) | *cp++;
5386 nkeys = (nkeys << 8) | *cp++;
5388 /* If this number is -1, then the string is mandatory. */
5392 /* Otherwise, for each key, */
5393 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5394 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5397 /* It starts with a KEYDEF structure */
5398 cp += sizeof (KEYDEF);
5400 /* Find the end of the key. At the end of this for loop we
5401 advance CP to the start of the next key using this variable. */
5402 endofthiskey = cp + strlen ((char *) cp);
5405 /* Expand the key, and enter it into the hash table. */
5406 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5407 tmpbuf.bufp = tmpbuf.buf;
5409 while (is_hor_space[*tmpbuf.bufp])
5411 if (!is_idstart[*tmpbuf.bufp]
5412 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5417 hp = lookup (tmpbuf.bufp, -1, -1);
5420 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5422 else if (hp->type == T_PCSTRING) {
5423 kp->chain = hp->value.keydef;
5424 hp->value.keydef = kp;
5430 /* This output_line_directive serves to switch us back to the current
5431 input file in case some of these strings get output (which will
5432 result in line directives for the header file being output). */
5433 output_line_directive (&instack[indepth], op, 0, enter_file);
5436 /* Called from rescan when it hits a key for strings. Mark them all
5437 used and clean up. */
5445 for (kp = hp->value.keydef; kp; kp = kp->chain)
5446 kp->str->writeflag = 1;
5450 /* Write the output, interspersing precompiled strings in their
5451 appropriate places. */
5456 STRINGDEF *next_string;
5457 U_CHAR *cur_buf_loc;
5458 int line_directive_len = 80;
5459 char *line_directive = xmalloc (line_directive_len);
5462 /* In each run through the loop, either cur_buf_loc ==
5463 next_string_loc, in which case we print a series of strings, or
5464 it is less than next_string_loc, in which case we write some of
5466 cur_buf_loc = outbuf.buf;
5467 next_string = stringlist;
5469 while (cur_buf_loc < outbuf.bufp || next_string) {
5471 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5472 if (next_string->writeflag) {
5473 len = 4 * strlen ((char *) next_string->filename) + 32;
5474 while (len > line_directive_len)
5475 line_directive = xrealloc (line_directive,
5476 line_directive_len *= 2);
5477 sprintf (line_directive, "\n# %d ", next_string->lineno);
5478 strcpy (quote_string (line_directive + strlen (line_directive),
5479 (char *) next_string->filename,
5480 strlen ((char *) next_string->filename)),
5482 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5483 safe_write (fileno (stdout),
5484 (char *) next_string->contents, next_string->len);
5486 next_string = next_string->chain;
5490 ? (next_string->output_mark
5491 - (cur_buf_loc - outbuf.buf))
5492 : outbuf.bufp - cur_buf_loc);
5494 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5498 free (line_directive);
5501 /* Pass a directive through to the output file.
5502 BUF points to the contents of the directive, as a contiguous string.
5503 LIMIT points to the first character past the end of the directive.
5504 KEYWORD is the keyword-table entry for the directive. */
5507 pass_thru_directive (buf, limit, op, keyword)
5508 U_CHAR *buf, *limit;
5510 struct directive *keyword;
5512 register unsigned keyword_length = keyword->length;
5514 check_expand (op, 1 + keyword_length + (limit - buf));
5516 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5517 op->bufp += keyword_length;
5518 if (limit != buf && buf[0] != ' ')
5520 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5521 op->bufp += (limit - buf);
5524 /* Count the line we have just made in the output,
5525 to get in sync properly. */
5530 /* The arglist structure is built by do_define to tell
5531 collect_definition where the argument names begin. That
5532 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5533 would contain pointers to the strings x, y, and z.
5534 Collect_definition would then build a DEFINITION node,
5535 with reflist nodes pointing to the places x, y, and z had
5536 appeared. So the arglist is just convenience data passed
5537 between these two routines. It is not kept around after
5538 the current #define has been processed and entered into the
5542 struct arglist *next;
5549 /* Create a DEFINITION node from a #define directive. Arguments are
5550 as for do_define. */
5553 create_definition (buf, limit, op)
5554 U_CHAR *buf, *limit;
5557 U_CHAR *bp; /* temp ptr into input buffer */
5558 U_CHAR *symname; /* remember where symbol name starts */
5559 int sym_length; /* and how long it is */
5560 int line = instack[indepth].lineno;
5561 char *file = instack[indepth].nominal_fname;
5562 size_t file_len = instack[indepth].nominal_fname_len;
5566 int arglengths = 0; /* Accumulate lengths of arg names
5567 plus number of args. */
5572 while (is_hor_space[*bp])
5575 symname = bp; /* remember where it starts */
5576 sym_length = check_macro_name (bp, "macro");
5579 /* Lossage will occur if identifiers or control keywords are broken
5580 across lines using backslash. This is not the right place to take
5584 struct arglist *arg_ptrs = NULL;
5587 bp++; /* skip '(' */
5588 SKIP_WHITE_SPACE (bp);
5590 /* Loop over macro argument names. */
5591 while (*bp != ')') {
5592 struct arglist *temp;
5594 temp = (struct arglist *) alloca (sizeof (struct arglist));
5596 temp->next = arg_ptrs;
5597 temp->argno = argno++;
5598 temp->rest_args = 0;
5602 pedwarn ("another parameter follows `%s'",
5605 if (!is_idstart[*bp])
5606 pedwarn ("invalid character in macro parameter name");
5608 /* Find the end of the arg name. */
5609 while (is_idchar[*bp]) {
5611 /* do we have a "special" rest-args extension here? */
5612 if (limit - bp > REST_EXTENSION_LENGTH
5613 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5614 if (pedantic && !instack[indepth].system_header_p)
5615 pedwarn ("ANSI C does not allow macro with variable arguments");
5617 temp->rest_args = 1;
5621 temp->length = bp - temp->name;
5623 bp += REST_EXTENSION_LENGTH;
5624 arglengths += temp->length + 2;
5625 SKIP_WHITE_SPACE (bp);
5626 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5627 error ("badly punctuated parameter list in `#define'");
5632 SKIP_WHITE_SPACE (bp);
5633 /* A comma at this point can only be followed by an identifier. */
5634 if (!is_idstart[*bp]) {
5635 error ("badly punctuated parameter list in `#define'");
5640 error ("unterminated parameter list in `#define'");
5644 struct arglist *otemp;
5646 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5647 if (temp->length == otemp->length
5648 && bcmp (temp->name, otemp->name, temp->length) == 0) {
5649 error ("duplicate argument name `%.*s' in `#define'",
5650 temp->length, temp->name);
5656 ++bp; /* skip paren */
5657 SKIP_WHITE_SPACE (bp);
5658 /* now everything from bp before limit is the definition. */
5659 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5660 defn->rest_args = rest_args;
5662 /* Now set defn->args.argnames to the result of concatenating
5663 the argument names in reverse order
5664 with comma-space between them. */
5665 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5667 struct arglist *temp;
5669 for (temp = arg_ptrs; temp; temp = temp->next) {
5670 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5672 if (temp->next != 0) {
5673 defn->args.argnames[i++] = ',';
5674 defn->args.argnames[i++] = ' ';
5677 defn->args.argnames[i] = 0;
5680 /* Simple expansion or empty definition. */
5684 if (is_hor_space[*bp]) {
5686 SKIP_WHITE_SPACE (bp);
5687 } else if (sym_length) {
5689 case '!': case '"': case '#': case '%': case '&': case '\'':
5690 case ')': case '*': case '+': case ',': case '-': case '.':
5691 case '/': case ':': case ';': case '<': case '=': case '>':
5692 case '?': case '[': case '\\': case ']': case '^': case '{':
5693 case '|': case '}': case '~':
5694 warning ("missing white space after `#define %.*s'",
5695 sym_length, symname);
5699 pedwarn ("missing white space after `#define %.*s'",
5700 sym_length, symname);
5705 /* Now everything from bp before limit is the definition. */
5706 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5707 defn->args.argnames = (U_CHAR *) "";
5712 defn->file_len = file_len;
5714 /* OP is null if this is a predefinition */
5715 defn->predefined = !op;
5717 mdef.symnam = symname;
5718 mdef.symlen = sym_length;
5727 /* Process a #define directive.
5728 BUF points to the contents of the #define directive, as a contiguous string.
5729 LIMIT points to the first character past the end of the definition.
5730 KEYWORD is the keyword-table entry for #define. */
5733 do_define (buf, limit, op, keyword)
5734 U_CHAR *buf, *limit;
5736 struct directive *keyword;
5741 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5742 if (pcp_outfile && op)
5743 pass_thru_directive (buf, limit, op, keyword);
5745 mdef = create_definition (buf, limit, op);
5749 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5753 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5755 /* Redefining a precompiled key is ok. */
5756 if (hp->type == T_PCSTRING)
5758 /* Redefining a macro is ok if the definitions are the same. */
5759 else if (hp->type == T_MACRO)
5760 ok = ! compare_defs (mdef.defn, hp->value.defn);
5761 /* Redefining a constant is ok with -D. */
5762 else if (hp->type == T_CONST)
5763 ok = ! done_initializing;
5764 /* Print the warning if it's not ok. */
5766 /* If we are passing through #define and #undef directives, do
5767 that for this re-definition now. */
5768 if (debug_output && op)
5769 pass_thru_directive (buf, limit, op, keyword);
5771 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5772 if (hp->type == T_MACRO)
5773 pedwarn_with_file_and_line (hp->value.defn->file,
5774 hp->value.defn->file_len,
5775 hp->value.defn->line,
5776 "this is the location of the previous definition");
5778 /* Replace the old definition. */
5780 hp->value.defn = mdef.defn;
5782 /* If we are passing through #define and #undef directives, do
5783 that for this new definition now. */
5784 if (debug_output && op)
5785 pass_thru_directive (buf, limit, op, keyword);
5786 install (mdef.symnam, mdef.symlen, T_MACRO,
5787 (char *) mdef.defn, hashcode);
5798 /* Check a purported macro name SYMNAME, and yield its length.
5799 USAGE is the kind of name this is intended for. */
5802 check_macro_name (symname, usage)
5809 for (p = symname; is_idchar[*p]; p++)
5811 sym_length = p - symname;
5813 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5814 error ("invalid %s name", usage);
5815 else if (!is_idstart[*symname]
5816 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5817 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5821 /* Return zero if two DEFINITIONs are isomorphic. */
5824 compare_defs (d1, d2)
5825 DEFINITION *d1, *d2;
5827 register struct reflist *a1, *a2;
5828 register U_CHAR *p1 = d1->expansion;
5829 register U_CHAR *p2 = d2->expansion;
5832 if (d1->nargs != d2->nargs)
5835 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5837 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5838 a1 = a1->next, a2 = a2->next) {
5839 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5840 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5841 || a1->argno != a2->argno
5842 || a1->stringify != a2->stringify
5843 || a1->raw_before != a2->raw_before
5844 || a1->raw_after != a2->raw_after)
5852 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5853 p2, d2->length - (p2 - d2->expansion), 1))
5858 /* Return 1 if two parts of two macro definitions are effectively different.
5859 One of the parts starts at BEG1 and has LEN1 chars;
5860 the other has LEN2 chars at BEG2.
5861 Any sequence of whitespace matches any other sequence of whitespace.
5862 FIRST means these parts are the first of a macro definition;
5863 so ignore leading whitespace entirely.
5864 LAST means these parts are the last of a macro definition;
5865 so ignore trailing whitespace entirely. */
5868 comp_def_part (first, beg1, len1, beg2, len2, last)
5870 U_CHAR *beg1, *beg2;
5874 register U_CHAR *end1 = beg1 + len1;
5875 register U_CHAR *end2 = beg2 + len2;
5877 while (beg1 != end1 && is_space[*beg1]) beg1++;
5878 while (beg2 != end2 && is_space[*beg2]) beg2++;
5881 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5882 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5884 while (beg1 != end1 && beg2 != end2) {
5885 if (is_space[*beg1] && is_space[*beg2]) {
5886 while (beg1 != end1 && is_space[*beg1]) beg1++;
5887 while (beg2 != end2 && is_space[*beg2]) beg2++;
5888 } else if (*beg1 == *beg2) {
5892 return (beg1 != end1) || (beg2 != end2);
5895 /* Read a replacement list for a macro with parameters.
5896 Build the DEFINITION structure.
5897 Reads characters of text starting at BUF until END.
5898 ARGLIST specifies the formal parameters to look for
5899 in the text of the definition; NARGS is the number of args
5900 in that list, or -1 for a macro name that wants no argument list.
5901 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5902 and NAMELEN is its length in characters.
5904 Note that comments, backslash-newlines, and leading white space
5905 have already been deleted from the argument. */
5907 /* If there is no trailing whitespace, a Newline Space is added at the end
5908 to prevent concatenation that would be contrary to the standard. */
5911 collect_expansion (buf, end, nargs, arglist)
5914 struct arglist *arglist;
5917 register U_CHAR *p, *limit, *lastp, *exp_p;
5918 struct reflist *endpat = NULL;
5919 /* Pointer to first nonspace after last ## seen. */
5921 /* Pointer to first nonspace after last single-# seen. */
5922 U_CHAR *stringify = 0;
5923 /* How those tokens were spelled. */
5924 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5925 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5927 int expected_delimiter = '\0';
5929 /* Scan thru the replacement list, ignoring comments and quoted
5930 strings, picking up on the macro calls. It does a linear search
5931 thru the arg list on every potential symbol. Profiling might say
5932 that something smarter should happen. */
5937 /* Find the beginning of the trailing whitespace. */
5940 while (p < limit && is_space[limit[-1]]) limit--;
5942 /* Allocate space for the text in the macro definition.
5943 Each input char may or may not need 1 byte,
5944 so this is an upper bound.
5945 The extra 3 are for invented trailing newline-marker and final null. */
5946 maxsize = (sizeof (DEFINITION)
5948 defn = (DEFINITION *) xcalloc (1, maxsize);
5950 defn->nargs = nargs;
5951 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5956 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5957 error ("`##' at start of macro definition");
5958 p += p[0] == '#' ? 2 : 4;
5961 /* Process the main body of the definition. */
5963 int skipped_arg = 0;
5964 register U_CHAR c = *p++;
5972 if (expected_delimiter != '\0') {
5973 if (c == expected_delimiter)
5974 expected_delimiter = '\0';
5976 expected_delimiter = c;
5980 if (p < limit && expected_delimiter) {
5981 /* In a string, backslash goes through
5982 and makes next char ordinary. */
5988 if (!expected_delimiter && *p == ':') {
5989 /* %: is not a digraph if preceded by an odd number of '<'s. */
5991 while (buf < p0 && p0[-1] == '<')
5994 /* Treat %:%: as ## and %: as #. */
5995 if (p[1] == '%' && p[2] == ':') {
5997 goto sharp_sharp_token;
6008 /* # is ordinary inside a string. */
6009 if (expected_delimiter)
6013 /* ##: concatenate preceding and following tokens. */
6014 /* Take out the first #, discard preceding whitespace. */
6016 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6018 /* Skip the second #. */
6020 concat_sharp_token_type = c;
6021 if (is_hor_space[*p]) {
6022 concat_sharp_token_type = c + 1;
6024 SKIP_WHITE_SPACE (p);
6028 error ("`##' at end of macro definition");
6029 } else if (nargs >= 0) {
6030 /* Single #: stringify following argument ref.
6031 Don't leave the # in the expansion. */
6034 stringify_sharp_token_type = c;
6035 if (is_hor_space[*p]) {
6036 stringify_sharp_token_type = c + 1;
6038 SKIP_WHITE_SPACE (p);
6040 if (! is_idstart[*p] || nargs == 0
6041 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6042 error ("`#' operator is not followed by a macro argument name");
6049 /* In -traditional mode, recognize arguments inside strings and
6050 and character constants, and ignore special properties of #.
6051 Arguments inside strings are considered "stringified", but no
6052 extra quote marks are supplied. */
6056 if (expected_delimiter != '\0') {
6057 if (c == expected_delimiter)
6058 expected_delimiter = '\0';
6060 expected_delimiter = c;
6064 /* Backslash quotes delimiters and itself, but not macro args. */
6065 if (expected_delimiter != 0 && p < limit
6066 && (*p == expected_delimiter || *p == '\\')) {
6073 if (expected_delimiter != '\0') /* No comments inside strings. */
6076 /* If we find a comment that wasn't removed by handle_directive,
6077 this must be -traditional. So replace the comment with
6080 while (++p < limit) {
6081 if (p[0] == '*' && p[1] == '/') {
6087 /* Mark this as a concatenation-point, as if it had been ##. */
6095 /* Handle the start of a symbol. */
6096 if (is_idchar[c] && nargs > 0) {
6097 U_CHAR *id_beg = p - 1;
6101 while (p != limit && is_idchar[*p]) p++;
6102 id_len = p - id_beg;
6105 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6106 register struct arglist *arg;
6108 for (arg = arglist; arg != NULL; arg = arg->next) {
6109 struct reflist *tpat;
6111 if (arg->name[0] == c
6112 && arg->length == id_len
6113 && bcmp (arg->name, id_beg, id_len) == 0) {
6114 enum sharp_token_type tpat_stringify;
6115 if (expected_delimiter) {
6116 if (warn_stringify) {
6118 warning ("macro argument `%.*s' is stringified.",
6121 warning ("macro arg `%.*s' would be stringified with -traditional.",
6125 /* If ANSI, don't actually substitute inside a string. */
6128 tpat_stringify = SHARP_TOKEN;
6131 = (stringify == id_beg
6132 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6134 /* make a pat node for this arg and append it to the end of
6136 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6139 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6140 tpat->raw_after = NO_SHARP_TOKEN;
6141 tpat->rest_args = arg->rest_args;
6142 tpat->stringify = tpat_stringify;
6145 defn->pattern = tpat;
6147 endpat->next = tpat;
6150 tpat->argno = arg->argno;
6151 tpat->nchars = exp_p - lastp;
6153 register U_CHAR *p1 = p;
6154 SKIP_WHITE_SPACE (p1);
6157 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6158 tpat->raw_after = p1[0] + (p != p1);
6160 lastp = exp_p; /* place to start copying from next time */
6167 /* If this was not a macro arg, copy it into the expansion. */
6168 if (! skipped_arg) {
6169 register U_CHAR *lim1 = p;
6173 if (stringify == id_beg)
6174 error ("`#' operator should be followed by a macro argument name");
6179 if (!traditional && expected_delimiter == 0) {
6180 /* If ANSI, put in a newline-space marker to prevent token pasting.
6181 But not if "inside a string" (which in ANSI mode happens only for
6189 defn->length = exp_p - defn->expansion;
6191 /* Crash now if we overrun the allocated size. */
6192 if (defn->length + 1 > maxsize)
6196 /* This isn't worth the time it takes. */
6197 /* give back excess storage */
6198 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6205 do_assert (buf, limit, op, keyword)
6206 U_CHAR *buf, *limit;
6208 struct directive *keyword;
6210 U_CHAR *bp; /* temp ptr into input buffer */
6211 U_CHAR *symname; /* remember where symbol name starts */
6212 int sym_length; /* and how long it is */
6213 struct arglist *tokens = NULL;
6215 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6216 pedwarn ("ANSI C does not allow `#assert'");
6220 while (is_hor_space[*bp])
6223 symname = bp; /* remember where it starts */
6224 sym_length = check_macro_name (bp, "assertion");
6226 /* #define doesn't do this, but we should. */
6227 SKIP_WHITE_SPACE (bp);
6229 /* Lossage will occur if identifiers or control tokens are broken
6230 across lines using backslash. This is not the right place to take
6234 error ("missing token-sequence in `#assert'");
6241 bp++; /* skip '(' */
6242 SKIP_WHITE_SPACE (bp);
6244 tokens = read_token_list (&bp, limit, &error_flag);
6248 error ("empty token-sequence in `#assert'");
6252 ++bp; /* skip paren */
6253 SKIP_WHITE_SPACE (bp);
6256 /* If this name isn't already an assertion name, make it one.
6257 Error if it was already in use in some other way. */
6260 ASSERTION_HASHNODE *hp;
6261 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6262 struct tokenlist_list *value
6263 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6265 hp = assertion_lookup (symname, sym_length, hashcode);
6267 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6268 error ("`defined' redefined as assertion");
6269 hp = assertion_install (symname, sym_length, hashcode);
6272 /* Add the spec'd token-sequence to the list of such. */
6273 value->tokens = tokens;
6274 value->next = hp->value;
6282 do_unassert (buf, limit, op, keyword)
6283 U_CHAR *buf, *limit;
6285 struct directive *keyword;
6287 U_CHAR *bp; /* temp ptr into input buffer */
6288 U_CHAR *symname; /* remember where symbol name starts */
6289 int sym_length; /* and how long it is */
6291 struct arglist *tokens = NULL;
6292 int tokens_specified = 0;
6294 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6295 pedwarn ("ANSI C does not allow `#unassert'");
6299 while (is_hor_space[*bp])
6302 symname = bp; /* remember where it starts */
6303 sym_length = check_macro_name (bp, "assertion");
6305 /* #define doesn't do this, but we should. */
6306 SKIP_WHITE_SPACE (bp);
6308 /* Lossage will occur if identifiers or control tokens are broken
6309 across lines using backslash. This is not the right place to take
6315 bp++; /* skip '(' */
6316 SKIP_WHITE_SPACE (bp);
6318 tokens = read_token_list (&bp, limit, &error_flag);
6322 error ("empty token list in `#unassert'");
6326 tokens_specified = 1;
6328 ++bp; /* skip paren */
6329 SKIP_WHITE_SPACE (bp);
6333 ASSERTION_HASHNODE *hp;
6334 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6335 struct tokenlist_list *tail, *prev;
6337 hp = assertion_lookup (symname, sym_length, hashcode);
6341 /* If no token list was specified, then eliminate this assertion
6343 if (! tokens_specified) {
6344 struct tokenlist_list *next;
6345 for (tail = hp->value; tail; tail = next) {
6347 free_token_list (tail->tokens);
6350 delete_assertion (hp);
6352 /* If a list of tokens was given, then delete any matching list. */
6357 struct tokenlist_list *next = tail->next;
6358 if (compare_token_lists (tail->tokens, tokens)) {
6362 hp->value = tail->next;
6363 free_token_list (tail->tokens);
6376 /* Test whether there is an assertion named NAME
6377 and optionally whether it has an asserted token list TOKENS.
6378 NAME is not null terminated; its length is SYM_LENGTH.
6379 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6382 check_assertion (name, sym_length, tokens_specified, tokens)
6385 int tokens_specified;
6386 struct arglist *tokens;
6388 ASSERTION_HASHNODE *hp;
6389 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6391 if (pedantic && !instack[indepth].system_header_p)
6392 pedwarn ("ANSI C does not allow testing assertions");
6394 hp = assertion_lookup (name, sym_length, hashcode);
6396 /* It is not an assertion; just return false. */
6399 /* If no token list was specified, then value is 1. */
6400 if (! tokens_specified)
6404 struct tokenlist_list *tail;
6408 /* If a list of tokens was given,
6409 then succeed if the assertion records a matching list. */
6412 if (compare_token_lists (tail->tokens, tokens))
6417 /* Fail if the assertion has no matching list. */
6422 /* Compare two lists of tokens for equality including order of tokens. */
6425 compare_token_lists (l1, l2)
6426 struct arglist *l1, *l2;
6429 if (l1->length != l2->length)
6431 if (bcmp (l1->name, l2->name, l1->length))
6437 /* Succeed if both lists end at the same time. */
6441 /* Read a space-separated list of tokens ending in a close parenthesis.
6442 Return a list of strings, in the order they were written.
6443 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6444 Parse the text starting at *BPP, and update *BPP.
6445 Don't parse beyond LIMIT. */
6447 static struct arglist *
6448 read_token_list (bpp, limit, error_flag)
6453 struct arglist *token_ptrs = 0;
6459 /* Loop over the assertion value tokens. */
6461 struct arglist *temp;
6465 /* Find the end of the token. */
6469 } else if (*bp == ')') {
6474 } else if (*bp == '"' || *bp == '\'')
6475 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6477 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6478 && *bp != '"' && *bp != '\'' && bp != limit)
6481 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6482 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6483 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6484 temp->name[bp - beg] = 0;
6485 temp->next = token_ptrs;
6487 temp->length = bp - beg;
6489 SKIP_WHITE_SPACE (bp);
6492 error ("unterminated token sequence in `#assert' or `#unassert'");
6499 /* We accumulated the names in reverse order.
6500 Now reverse them to get the proper order. */
6502 register struct arglist *prev = 0, *this, *next;
6503 for (this = token_ptrs; this; this = next) {
6513 free_token_list (tokens)
6514 struct arglist *tokens;
6517 struct arglist *next = tokens->next;
6518 free (tokens->name);
6524 /* Install a name in the assertion hash table.
6526 If LEN is >= 0, it is the length of the name.
6527 Otherwise, compute the length by scanning the entire name.
6529 If HASH is >= 0, it is the precomputed hash code.
6530 Otherwise, compute the hash code. */
6532 static ASSERTION_HASHNODE *
6533 assertion_install (name, len, hash)
6538 register ASSERTION_HASHNODE *hp;
6539 register int i, bucket;
6540 register U_CHAR *p, *q;
6542 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6543 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6545 hp->bucket_hdr = &assertion_hashtab[bucket];
6546 hp->next = assertion_hashtab[bucket];
6547 assertion_hashtab[bucket] = hp;
6549 if (hp->next != NULL)
6550 hp->next->prev = hp;
6553 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6556 for (i = 0; i < len; i++)
6562 /* Find the most recent hash node for name name (ending with first
6563 non-identifier char) installed by install
6565 If LEN is >= 0, it is the length of the name.
6566 Otherwise, compute the length by scanning the entire name.
6568 If HASH is >= 0, it is the precomputed hash code.
6569 Otherwise, compute the hash code. */
6571 static ASSERTION_HASHNODE *
6572 assertion_lookup (name, len, hash)
6577 register ASSERTION_HASHNODE *bucket;
6579 bucket = assertion_hashtab[hash];
6581 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6583 bucket = bucket->next;
6589 delete_assertion (hp)
6590 ASSERTION_HASHNODE *hp;
6593 if (hp->prev != NULL)
6594 hp->prev->next = hp->next;
6595 if (hp->next != NULL)
6596 hp->next->prev = hp->prev;
6598 /* Make sure that the bucket chain header that the deleted guy was
6599 on points to the right thing afterwards. */
6600 if (hp == *hp->bucket_hdr)
6601 *hp->bucket_hdr = hp->next;
6607 * interpret #line directive. Remembers previously seen fnames
6608 * in its very own hash table.
6610 #define FNAME_HASHSIZE 37
6613 do_line (buf, limit, op, keyword)
6614 U_CHAR *buf, *limit;
6616 struct directive *keyword;
6618 register U_CHAR *bp;
6619 FILE_BUF *ip = &instack[indepth];
6622 enum file_change_code file_change = same_file;
6624 /* Expand any macros. */
6625 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6627 /* Point to macroexpanded line, which is null-terminated now. */
6629 SKIP_WHITE_SPACE (bp);
6631 if (!isdigit (*bp)) {
6632 error ("invalid format `#line' directive");
6636 /* The Newline at the end of this line remains to be processed.
6637 To put the next line at the specified line number,
6638 we must store a line number now that is one less. */
6639 new_lineno = atoi ((char *) bp) - 1;
6641 /* NEW_LINENO is one less than the actual line number here. */
6642 if (pedantic && new_lineno < 0)
6643 pedwarn ("line number out of range in `#line' directive");
6645 /* skip over the line number. */
6646 while (isdigit (*bp))
6649 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6650 if (*bp && !is_space[*bp]) {
6651 error ("invalid format `#line' directive");
6656 SKIP_WHITE_SPACE (bp);
6659 static HASHNODE *fname_table[FNAME_HASHSIZE];
6660 HASHNODE *hp, **hash_bucket;
6666 /* Turn the file name, which is a character string literal,
6667 into a null-terminated string. Do this in place. */
6670 switch ((*p++ = *bp++)) {
6672 error ("invalid format `#line' directive");
6677 char *bpc = (char *) bp;
6678 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6679 bp = (U_CHAR *) bpc;
6692 fname_length = p - fname;
6694 SKIP_WHITE_SPACE (bp);
6697 pedwarn ("garbage at end of `#line' directive");
6699 file_change = enter_file;
6700 else if (*bp == '2')
6701 file_change = leave_file;
6702 else if (*bp == '3')
6703 ip->system_header_p = 1;
6704 else if (*bp == '4')
6705 ip->system_header_p = 2;
6707 error ("invalid format `#line' directive");
6712 SKIP_WHITE_SPACE (bp);
6714 ip->system_header_p = 1;
6716 SKIP_WHITE_SPACE (bp);
6719 ip->system_header_p = 2;
6721 SKIP_WHITE_SPACE (bp);
6724 error ("invalid format `#line' directive");
6729 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6730 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6731 if (hp->length == fname_length &&
6732 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6733 ip->nominal_fname = hp->value.cpval;
6734 ip->nominal_fname_len = fname_length;
6738 /* Didn't find it; cons up a new one. */
6739 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6740 hp->next = *hash_bucket;
6743 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6744 ip->nominal_fname_len = hp->length = fname_length;
6745 bcopy (fname, hp->value.cpval, fname_length + 1);
6748 error ("invalid format `#line' directive");
6752 ip->lineno = new_lineno;
6753 output_line_directive (ip, op, 0, file_change);
6754 check_expand (op, ip->length - (ip->bufp - ip->buf));
6758 /* Remove the definition of a symbol from the symbol table.
6759 according to un*x /lib/cpp, it is not an error to undef
6760 something that has no definitions, so it isn't one here either. */
6763 do_undef (buf, limit, op, keyword)
6764 U_CHAR *buf, *limit;
6766 struct directive *keyword;
6770 U_CHAR *orig_buf = buf;
6772 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6773 if (pcp_outfile && op)
6774 pass_thru_directive (buf, limit, op, keyword);
6776 SKIP_WHITE_SPACE (buf);
6777 sym_length = check_macro_name (buf, "macro");
6779 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6780 /* If we are generating additional info for debugging (with -g) we
6781 need to pass through all effective #undef directives. */
6782 if (debug_output && op)
6783 pass_thru_directive (orig_buf, limit, op, keyword);
6784 if (hp->type != T_MACRO)
6785 warning ("undefining `%s'", hp->name);
6791 SKIP_WHITE_SPACE (buf);
6793 pedwarn ("garbage after `#undef' directive");
6798 /* Report an error detected by the program we are processing.
6799 Use the text of the line in the error message.
6800 (We use error because it prints the filename & line#.) */
6803 do_error (buf, limit, op, keyword)
6804 U_CHAR *buf, *limit;
6806 struct directive *keyword;
6808 int length = limit - buf;
6809 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6810 bcopy ((char *) buf, (char *) copy, length);
6812 SKIP_WHITE_SPACE (copy);
6813 error ("#error %s", copy);
6817 /* Report a warning detected by the program we are processing.
6818 Use the text of the line in the warning message, then continue.
6819 (We use error because it prints the filename & line#.) */
6822 do_warning (buf, limit, op, keyword)
6823 U_CHAR *buf, *limit;
6825 struct directive *keyword;
6827 int length = limit - buf;
6828 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6829 bcopy ((char *) buf, (char *) copy, length);
6831 SKIP_WHITE_SPACE (copy);
6833 if (pedantic && !instack[indepth].system_header_p)
6834 pedwarn ("ANSI C does not allow `#warning'");
6836 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
6837 if -pedantic-errors is given, #warning should cause an error. */
6838 pedwarn ("#warning %s", copy);
6842 /* Remember the name of the current file being read from so that we can
6843 avoid ever including it again. */
6850 for (i = indepth; i >= 0; i--)
6851 if (instack[i].inc) {
6852 record_control_macro (instack[i].inc, (U_CHAR *) "");
6857 /* Report program identification. */
6860 do_ident (buf, limit, op, keyword)
6861 U_CHAR *buf, *limit;
6863 struct directive *keyword;
6868 /* Allow #ident in system headers, since that's not user's fault. */
6869 if (pedantic && !instack[indepth].system_header_p)
6870 pedwarn ("ANSI C does not allow `#ident'");
6872 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6874 len = trybuf.bufp - buf;
6876 /* Output expanded directive. */
6877 check_expand (op, 7 + len);
6878 bcopy ("#ident ", (char *) op->bufp, 7);
6880 bcopy ((char *) buf, (char *) op->bufp, len);
6887 /* #pragma and its argument line have already been copied to the output file.
6888 Just check for some recognized pragmas that need validation here. */
6891 do_pragma (buf, limit, op, keyword)
6892 U_CHAR *buf, *limit;
6894 struct directive *keyword;
6896 SKIP_WHITE_SPACE (buf);
6897 if (!strncmp ((char *) buf, "once", 4)) {
6898 /* Allow #pragma once in system headers, since that's not the user's
6900 if (!instack[indepth].system_header_p)
6901 warning ("`#pragma once' is obsolete");
6905 if (!strncmp ((char *) buf, "implementation", 14)) {
6906 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6907 been included yet. */
6910 U_CHAR *p = buf + 14, *fname;
6911 SKIP_WHITE_SPACE (p);
6916 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6919 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6920 struct include_file *inc;
6921 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6922 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6923 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6933 /* This was a fun hack, but #pragma seems to start to be useful.
6934 By failing to recognize it, we pass it through unchanged to cc1. */
6936 /* The behavior of the #pragma directive is implementation defined.
6937 this implementation defines it as follows. */
6943 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6946 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6948 execl ("/usr/games/hack", "#pragma", 0);
6949 execl ("/usr/games/rogue", "#pragma", 0);
6950 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6951 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6953 fatal ("You are in a maze of twisty compiler features, all different");
6957 #ifdef SCCS_DIRECTIVE
6959 /* Just ignore #sccs, on systems where we define it at all. */
6962 do_sccs (buf, limit, op, keyword)
6963 U_CHAR *buf, *limit;
6965 struct directive *keyword;
6968 pedwarn ("ANSI C does not allow `#sccs'");
6972 #endif /* defined (SCCS_DIRECTIVE) */
6974 /* Handle #if directive by
6975 1) inserting special `defined' keyword into the hash table
6976 that gets turned into 0 or 1 by special_symbol (thus,
6977 if the luser has a symbol called `defined' already, it won't
6978 work inside the #if directive)
6979 2) rescan the input into a temporary output buffer
6980 3) pass the output buffer to the yacc parser and collect a value
6981 4) clean up the mess left from steps 1 and 2.
6982 5) call conditional_skip to skip til the next #endif (etc.),
6983 or not, depending on the value from step 3. */
6986 do_if (buf, limit, op, keyword)
6987 U_CHAR *buf, *limit;
6989 struct directive *keyword;
6991 HOST_WIDE_INT value;
6992 FILE_BUF *ip = &instack[indepth];
6994 value = eval_if_expression (buf, limit - buf);
6995 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6999 /* Handle a #elif directive by not changing if_stack either.
7000 see the comment above do_else. */
7003 do_elif (buf, limit, op, keyword)
7004 U_CHAR *buf, *limit;
7006 struct directive *keyword;
7008 HOST_WIDE_INT value;
7009 FILE_BUF *ip = &instack[indepth];
7011 if (if_stack == instack[indepth].if_stack) {
7012 error ("`#elif' not within a conditional");
7015 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7016 error ("`#elif' after `#else'");
7017 fprintf (stderr, " (matches line %d", if_stack->lineno);
7018 if (! (if_stack->fname_len == ip->nominal_fname_len
7019 && !bcmp (if_stack->fname, ip->nominal_fname,
7020 if_stack->fname_len))) {
7021 fprintf (stderr, ", file ");
7022 eprint_string (if_stack->fname, if_stack->fname_len);
7024 fprintf (stderr, ")\n");
7026 if_stack->type = T_ELIF;
7029 if (if_stack->if_succeeded)
7030 skip_if_group (ip, 0, op);
7032 value = eval_if_expression (buf, limit - buf);
7034 skip_if_group (ip, 0, op);
7036 ++if_stack->if_succeeded; /* continue processing input */
7037 output_line_directive (ip, op, 1, same_file);
7043 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7044 result as a C expression and return the value as an int. */
7046 static HOST_WIDE_INT
7047 eval_if_expression (buf, length)
7052 HASHNODE *save_defined;
7053 HOST_WIDE_INT value;
7055 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7058 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7060 delete_macro (save_defined); /* clean up special symbol */
7062 temp_obuf.buf[temp_obuf.length] = '\n';
7063 value = parse_c_expression ((char *) temp_obuf.buf,
7064 warn_undef && !instack[indepth].system_header_p);
7066 free (temp_obuf.buf);
7071 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7072 or don't skip to the #endif/#else/#elif depending on what directive
7073 is actually being processed. */
7076 do_xifdef (buf, limit, op, keyword)
7077 U_CHAR *buf, *limit;
7079 struct directive *keyword;
7082 FILE_BUF *ip = &instack[indepth];
7084 int start_of_file = 0;
7085 U_CHAR *control_macro = 0;
7087 /* Detect a #ifndef at start of file (not counting comments). */
7088 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7089 U_CHAR *p = ip->buf;
7090 while (p != directive_start) {
7094 /* Make no special provision for backslash-newline here; this is
7095 slower if backslash-newlines are present, but it's correct,
7096 and it's not worth it to tune for the rare backslash-newline. */
7098 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7099 /* Skip this comment. */
7101 U_CHAR *save_bufp = ip->bufp;
7103 p = skip_to_end_of_comment (ip, &junk, 1);
7104 ip->bufp = save_bufp;
7109 /* If we get here, this conditional is the beginning of the file. */
7114 /* Discard leading and trailing whitespace. */
7115 SKIP_WHITE_SPACE (buf);
7116 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7118 /* Find the end of the identifier at the beginning. */
7119 for (end = buf; is_idchar[*end]; end++);
7122 skip = (keyword->type == T_IFDEF);
7124 pedwarn (end == limit ? "`#%s' with no argument"
7125 : "`#%s' argument starts with punctuation",
7130 if (! traditional) {
7131 if (isdigit (buf[0]))
7132 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7133 else if (end != limit)
7134 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7137 hp = lookup (buf, end-buf, -1);
7140 /* Output a precondition for this macro. */
7142 && (hp->type == T_CONST
7143 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7144 fprintf (pcp_outfile, "#define %s\n", hp->name);
7147 fprintf (pcp_outfile, "#undef ");
7148 while (is_idchar[*cp]) /* Ick! */
7149 fputc (*cp++, pcp_outfile);
7150 putc ('\n', pcp_outfile);
7154 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7155 if (start_of_file && !skip) {
7156 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7157 bcopy ((char *) buf, (char *) control_macro, end - buf);
7158 control_macro[end - buf] = 0;
7162 conditional_skip (ip, skip, T_IF, control_macro, op);
7166 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7167 If this is a #ifndef starting at the beginning of a file,
7168 CONTROL_MACRO is the macro name tested by the #ifndef.
7169 Otherwise, CONTROL_MACRO is 0. */
7172 conditional_skip (ip, skip, type, control_macro, op)
7175 enum node_type type;
7176 U_CHAR *control_macro;
7179 IF_STACK_FRAME *temp;
7181 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7182 temp->fname = ip->nominal_fname;
7183 temp->fname_len = ip->nominal_fname_len;
7184 temp->lineno = ip->lineno;
7185 temp->next = if_stack;
7186 temp->control_macro = control_macro;
7189 if_stack->type = type;
7192 skip_if_group (ip, 0, op);
7195 ++if_stack->if_succeeded;
7196 output_line_directive (ip, &outbuf, 1, same_file);
7200 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7201 Leaves input ptr at the sharp sign found.
7202 If ANY is nonzero, return at next directive of any sort. */
7205 skip_if_group (ip, any, op)
7210 register U_CHAR *bp = ip->bufp, *cp;
7211 register U_CHAR *endb = ip->buf + ip->length;
7212 struct directive *kt;
7213 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7214 U_CHAR *beg_of_line = bp;
7215 register int ident_length;
7216 U_CHAR *ident, *after_ident;
7217 /* Save info about where the group starts. */
7218 U_CHAR *beg_of_group = bp;
7219 int beg_lineno = ip->lineno;
7220 int skipping_include_directive = 0;
7222 if (output_conditionals && op != 0) {
7223 char *ptr = "#failed\n";
7224 int len = strlen (ptr);
7226 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7231 check_expand (op, len);
7232 bcopy (ptr, (char *) op->bufp, len);
7235 output_line_directive (ip, op, 1, 0);
7240 case '/': /* possible comment */
7241 if (*bp == '\\' && bp[1] == '\n')
7244 || (cplusplus_comments && *bp == '/')) {
7246 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7250 if (skipping_include_directive) {
7251 while (bp < endb && *bp != '>' && *bp != '\n') {
7252 if (*bp == '\\' && bp[1] == '\n') {
7261 if (skipping_include_directive) {
7262 while (bp < endb && *bp != '\n') {
7267 if (*bp == '\\' && bp[1] == '\n') {
7277 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7278 NULL_PTR, NULL_PTR);
7281 /* Char after backslash loses its special meaning in some cases. */
7285 } else if (traditional && bp < endb)
7291 skipping_include_directive = 0;
7294 if (beg_of_line == 0 || traditional)
7297 while (bp[0] == '\\' && bp[1] == '\n')
7303 /* # keyword: a # must be first nonblank char on the line */
7304 if (beg_of_line == 0)
7308 /* Scan from start of line, skipping whitespace, comments
7309 and backslash-newlines, and see if we reach this #.
7310 If not, this # is not special. */
7312 /* If -traditional, require # to be at beginning of line. */
7315 if (is_hor_space[*bp])
7317 else if (*bp == '\\' && bp[1] == '\n')
7319 else if (*bp == '/' && bp[1] == '*') {
7321 while (!(*bp == '*' && bp[1] == '/'))
7325 /* There is no point in trying to deal with C++ // comments here,
7326 because if there is one, then this # must be part of the
7327 comment and we would never reach here. */
7331 if (bp != ip->bufp) {
7332 bp = ip->bufp + 1; /* Reset bp to after the #. */
7336 bp = ip->bufp + 1; /* Point after the '#' */
7337 if (ip->bufp[0] == '%') {
7338 /* Skip past the ':' again. */
7339 while (*bp == '\\') {
7346 /* Skip whitespace and \-newline. */
7348 if (is_hor_space[*bp])
7350 else if (*bp == '\\' && bp[1] == '\n')
7352 else if (*bp == '/') {
7353 if (bp[1] == '\\' && bp[2] == '\n')
7354 newline_fix (bp + 1);
7356 for (bp += 2; ; bp++) {
7359 else if (*bp == '*') {
7360 if (bp[-1] == '/' && warn_comments)
7361 warning ("`/*' within comment");
7362 if (bp[1] == '\\' && bp[2] == '\n')
7363 newline_fix (bp + 1);
7369 } else if (bp[1] == '/' && cplusplus_comments) {
7370 for (bp += 2; ; bp++) {
7375 warning ("multiline `//' comment");
7387 /* Now find end of directive name.
7388 If we encounter a backslash-newline, exchange it with any following
7389 symbol-constituents so that we end up with a contiguous name. */
7395 if (*bp == '\\' && bp[1] == '\n')
7396 name_newline_fix (bp);
7402 ident_length = bp - cp;
7406 /* A line of just `#' becomes blank. */
7408 if (ident_length == 0 && *after_ident == '\n') {
7412 if (ident_length == 0 || !is_idstart[*ident]) {
7414 while (is_idchar[*p]) {
7415 if (*p < '0' || *p > '9')
7419 /* Handle # followed by a line number. */
7420 if (p != ident && !is_idchar[*p]) {
7422 pedwarn ("`#' followed by integer");
7426 /* Avoid error for `###' and similar cases unless -pedantic. */
7428 while (*p == '#' || is_hor_space[*p]) p++;
7430 if (pedantic && !lang_asm)
7431 pedwarn ("invalid preprocessing directive");
7436 if (!lang_asm && pedantic)
7437 pedwarn ("invalid preprocessing directive name");
7441 for (kt = directive_table; kt->length >= 0; kt++) {
7442 IF_STACK_FRAME *temp;
7443 if (ident_length == kt->length
7444 && bcmp (cp, kt->name, kt->length) == 0) {
7445 /* If we are asked to return on next directive, do so now. */
7453 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7454 temp->next = if_stack;
7456 temp->lineno = ip->lineno;
7457 temp->fname = ip->nominal_fname;
7458 temp->fname_len = ip->nominal_fname_len;
7459 temp->type = kt->type;
7463 if (pedantic && if_stack != save_if_stack)
7464 validate_else (bp, endb);
7466 if (if_stack == instack[indepth].if_stack) {
7467 error ("`#%s' not within a conditional", kt->name);
7470 else if (if_stack == save_if_stack)
7471 goto done; /* found what we came for */
7473 if (kt->type != T_ENDIF) {
7474 if (if_stack->type == T_ELSE)
7475 error ("`#else' or `#elif' after `#else'");
7476 if_stack->type = kt->type;
7481 if_stack = if_stack->next;
7486 case T_INCLUDE_NEXT:
7488 skipping_include_directive = 1;
7497 /* Don't let erroneous code go by. */
7498 if (kt->length < 0 && !lang_asm && pedantic)
7499 pedwarn ("invalid preprocessing directive name");
7504 /* after this returns, rescan will exit because ip->bufp
7505 now points to the end of the buffer.
7506 rescan is responsible for the error message also. */
7509 if (output_conditionals && op != 0) {
7510 char *ptr = "#endfailed\n";
7511 int len = strlen (ptr);
7513 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7518 check_expand (op, beg_of_line - beg_of_group);
7519 bcopy ((char *) beg_of_group, (char *) op->bufp,
7520 beg_of_line - beg_of_group);
7521 op->bufp += beg_of_line - beg_of_group;
7522 op->lineno += ip->lineno - beg_lineno;
7523 check_expand (op, len);
7524 bcopy (ptr, (char *) op->bufp, len);
7530 /* Handle a #else directive. Do this by just continuing processing
7531 without changing if_stack ; this is so that the error message
7532 for missing #endif's etc. will point to the original #if. It
7533 is possible that something different would be better. */
7536 do_else (buf, limit, op, keyword)
7537 U_CHAR *buf, *limit;
7539 struct directive *keyword;
7541 FILE_BUF *ip = &instack[indepth];
7544 SKIP_WHITE_SPACE (buf);
7546 pedwarn ("text following `#else' violates ANSI standard");
7549 if (if_stack == instack[indepth].if_stack) {
7550 error ("`#else' not within a conditional");
7553 /* #ifndef can't have its special treatment for containing the whole file
7554 if it has a #else clause. */
7555 if_stack->control_macro = 0;
7557 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7558 error ("`#else' after `#else'");
7559 fprintf (stderr, " (matches line %d", if_stack->lineno);
7560 if (! (if_stack->fname_len == ip->nominal_fname_len
7561 && !bcmp (if_stack->fname, ip->nominal_fname,
7562 if_stack->fname_len))) {
7563 fprintf (stderr, ", file ");
7564 eprint_string (if_stack->fname, if_stack->fname_len);
7566 fprintf (stderr, ")\n");
7568 if_stack->type = T_ELSE;
7571 if (if_stack->if_succeeded)
7572 skip_if_group (ip, 0, op);
7574 ++if_stack->if_succeeded; /* continue processing input */
7575 output_line_directive (ip, op, 1, same_file);
7580 /* Unstack after #endif directive. */
7583 do_endif (buf, limit, op, keyword)
7584 U_CHAR *buf, *limit;
7586 struct directive *keyword;
7589 SKIP_WHITE_SPACE (buf);
7591 pedwarn ("text following `#endif' violates ANSI standard");
7594 if (if_stack == instack[indepth].if_stack)
7595 error ("unbalanced `#endif'");
7597 IF_STACK_FRAME *temp = if_stack;
7598 if_stack = if_stack->next;
7599 if (temp->control_macro != 0) {
7600 /* This #endif matched a #ifndef at the start of the file.
7601 See if it is at the end of the file. */
7602 FILE_BUF *ip = &instack[indepth];
7603 U_CHAR *p = ip->bufp;
7604 U_CHAR *ep = ip->buf + ip->length;
7610 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7611 /* Skip this comment. */
7613 U_CHAR *save_bufp = ip->bufp;
7615 p = skip_to_end_of_comment (ip, &junk, 1);
7616 ip->bufp = save_bufp;
7621 /* If we get here, this #endif ends a #ifndef
7622 that contains all of the file (aside from whitespace).
7623 Arrange not to include the file again
7624 if the macro that was tested is defined.
7626 Do not do this for the top-level file in a -include or any
7627 file in a -imacros. */
7629 && ! (indepth == 1 && no_record_file)
7630 && ! (no_record_file && no_output))
7631 record_control_macro (ip->inc, temp->control_macro);
7635 output_line_directive (&instack[indepth], op, 1, same_file);
7640 /* When an #else or #endif is found while skipping failed conditional,
7641 if -pedantic was specified, this is called to warn about text after
7642 the directive name. P points to the first char after the directive
7646 validate_else (p, limit)
7648 register U_CHAR *limit;
7650 /* Advance P over whitespace and comments. */
7652 while (*p == '\\' && p[1] == '\n')
7654 if (is_hor_space[*p])
7656 else if (*p == '/') {
7657 while (p[1] == '\\' && p[2] == '\n')
7660 /* Don't bother warning about unterminated comments
7661 since that will happen later. Just be sure to exit. */
7662 for (p += 2; ; p++) {
7666 while (p[1] == '\\' && p[2] == '\n')
7675 else if (cplusplus_comments && p[1] == '/')
7681 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7684 /* Skip a comment, assuming the input ptr immediately follows the
7685 initial slash-star. Bump *LINE_COUNTER for each newline.
7686 (The canonical line counter is &ip->lineno.)
7687 Don't use this routine (or the next one) if bumping the line
7688 counter is not sufficient to deal with newlines in the string.
7690 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7691 This feature is useful when processing a comment that is going to
7692 be processed or was processed at another point in the preprocessor,
7693 to avoid a duplicate warning. Likewise for unterminated comment
7697 skip_to_end_of_comment (ip, line_counter, nowarn)
7698 register FILE_BUF *ip;
7699 int *line_counter; /* place to remember newlines, or NULL */
7702 register U_CHAR *limit = ip->buf + ip->length;
7703 register U_CHAR *bp = ip->bufp;
7704 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7705 int start_line = line_counter ? *line_counter : 0;
7707 /* JF this line_counter stuff is a crock to make sure the
7708 comment is only put out once, no matter how many times
7709 the comment is skipped. It almost works */
7712 *op->bufp++ = bp[-1];
7714 if (cplusplus_comments && bp[-1] == '/') {
7715 for (; bp < limit; bp++) {
7719 if (!nowarn && warn_comments)
7720 warning ("multiline `//' comment");
7732 while (bp < limit) {
7737 /* If this is the end of the file, we have an unterminated comment.
7738 Don't swallow the newline. We are guaranteed that there will be a
7739 trailing newline and various pieces assume it's there. */
7746 if (line_counter != NULL)
7752 if (bp[-2] == '/' && !nowarn && warn_comments)
7753 warning ("`/*' within comment");
7754 if (*bp == '\\' && bp[1] == '\n')
7767 error_with_line (line_for_error (start_line), "unterminated comment");
7772 /* Skip over a quoted string. BP points to the opening quote.
7773 Returns a pointer after the closing quote. Don't go past LIMIT.
7774 START_LINE is the line number of the starting point (but it need
7775 not be valid if the starting point is inside a macro expansion).
7777 The input stack state is not changed.
7779 If COUNT_NEWLINES is nonzero, it points to an int to increment
7780 for each newline passed.
7782 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7783 if we pass a backslash-newline.
7785 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
7788 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7789 register U_CHAR *bp;
7790 register U_CHAR *limit;
7792 int *count_newlines;
7793 int *backslash_newlines_p;
7796 register U_CHAR c, match;
7801 error_with_line (line_for_error (start_line),
7802 "unterminated string or character constant");
7803 error_with_line (multiline_string_line,
7804 "possible real start of unterminated constant");
7805 multiline_string_line = 0;
7812 while (*bp == '\\' && bp[1] == '\n') {
7813 if (backslash_newlines_p)
7814 *backslash_newlines_p = 1;
7820 if (backslash_newlines_p)
7821 *backslash_newlines_p = 1;
7826 } else if (c == '\n') {
7828 /* Unterminated strings and character constants are 'valid'. */
7829 bp--; /* Don't consume the newline. */
7834 if (match == '\'') {
7835 error_with_line (line_for_error (start_line),
7836 "unterminated string or character constant");
7842 /* If not traditional, then allow newlines inside strings. */
7845 if (multiline_string_line == 0) {
7847 pedwarn_with_line (line_for_error (start_line),
7848 "string constant runs past end of line");
7849 multiline_string_line = start_line;
7851 } else if (c == match)
7857 /* Place into DST a quoted string representing the string SRC.
7858 SRCLEN is the length of SRC; SRC may contain null bytes.
7859 Return the address of DST's terminating null. */
7862 quote_string (dst, src, srclen)
7867 char *srclim = src + srclen;
7870 while (src != srclim)
7871 switch ((c = *src++))
7878 sprintf (dst, "\\%03o", c);
7895 /* Skip across a group of balanced parens, starting from IP->bufp.
7896 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7898 This does not handle newlines, because it's used for the arg of #if,
7899 where there aren't any newlines. Also, backslash-newline can't appear. */
7902 skip_paren_group (ip)
7903 register FILE_BUF *ip;
7905 U_CHAR *limit = ip->buf + ip->length;
7906 U_CHAR *p = ip->bufp;
7908 int lines_dummy = 0;
7910 while (p != limit) {
7920 return ip->bufp = p;
7926 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7934 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7936 return ip->bufp = p;
7946 /* Write out a #line directive, for instance, after an #include file.
7947 If CONDITIONAL is nonzero, we can omit the #line if it would
7948 appear to be a no-op, and we can output a few newlines instead
7949 if we want to increase the line number by a small amount.
7950 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
7953 output_line_directive (ip, op, conditional, file_change)
7956 enum file_change_code file_change;
7959 char *line_directive_buf, *line_end;
7961 if (no_line_directives
7962 || ip->fname == NULL
7964 op->lineno = ip->lineno;
7969 if (ip->lineno == op->lineno)
7972 /* If the inherited line number is a little too small,
7973 output some newlines instead of a #line directive. */
7974 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7975 check_expand (op, 10);
7976 while (ip->lineno > op->lineno) {
7984 /* Output a positive line number if possible. */
7985 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
7986 && *ip->bufp == '\n') {
7991 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
7992 sprintf (line_directive_buf, "# %d ", ip->lineno);
7993 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7994 ip->nominal_fname, ip->nominal_fname_len);
7995 if (file_change != same_file) {
7997 *line_end++ = file_change == enter_file ? '1' : '2';
7999 /* Tell cc1 if following text comes from a system header file. */
8000 if (ip->system_header_p) {
8004 #ifndef NO_IMPLICIT_EXTERN_C
8005 /* Tell cc1plus if following text should be treated as C. */
8006 if (ip->system_header_p == 2 && cplusplus) {
8012 len = line_end - line_directive_buf;
8013 check_expand (op, len + 1);
8014 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8016 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8018 op->lineno = ip->lineno;
8021 /* This structure represents one parsed argument in a macro call.
8022 `raw' points to the argument text as written (`raw_length' is its length).
8023 `expanded' points to the argument's macro-expansion
8024 (its length is `expand_length').
8025 `stringified_length' is the length the argument would have
8027 `use_count' is the number of times this macro arg is substituted
8028 into the macro. If the actual use count exceeds 10,
8029 the value stored is 10.
8030 `free1' and `free2', if nonzero, point to blocks to be freed
8031 when the macro argument data is no longer needed. */
8034 U_CHAR *raw, *expanded;
8035 int raw_length, expand_length;
8036 int stringified_length;
8037 U_CHAR *free1, *free2;
8042 /* Expand a macro call.
8043 HP points to the symbol that is the macro being called.
8044 Put the result of expansion onto the input stack
8045 so that subsequent input by our caller will use it.
8047 If macro wants arguments, caller has already verified that
8048 an argument list follows; arguments come from the input stack. */
8051 macroexpand (hp, op)
8056 DEFINITION *defn = hp->value.defn;
8057 register U_CHAR *xbuf;
8059 int start_line = instack[indepth].lineno;
8060 int rest_args, rest_zero;
8062 CHECK_DEPTH (return;);
8064 /* it might not actually be a macro. */
8065 if (hp->type != T_MACRO) {
8066 special_symbol (hp, op);
8070 /* This macro is being used inside a #if, which means it must be */
8071 /* recorded as a precondition. */
8072 if (pcp_inside_if && pcp_outfile && defn->predefined)
8073 dump_single_macro (hp, pcp_outfile);
8075 nargs = defn->nargs;
8079 struct argdata *args;
8080 char *parse_error = 0;
8082 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8084 for (i = 0; i < nargs; i++) {
8085 args[i].raw = (U_CHAR *) "";
8086 args[i].expanded = 0;
8087 args[i].raw_length = args[i].expand_length
8088 = args[i].stringified_length = 0;
8089 args[i].free1 = args[i].free2 = 0;
8090 args[i].use_count = 0;
8093 /* Parse all the macro args that are supplied. I counts them.
8094 The first NARGS args are stored in ARGS.
8095 The rest are discarded.
8096 If rest_args is set then we assume macarg absorbed the rest of the args.
8101 /* Discard the open-parenthesis or comma before the next arg. */
8102 ++instack[indepth].bufp;
8105 if (i < nargs || (nargs == 0 && i == 0)) {
8106 /* If we are working on last arg which absorbs rest of args... */
8107 if (i == nargs - 1 && defn->rest_args)
8109 parse_error = macarg (&args[i], rest_args);
8112 parse_error = macarg (NULL_PTR, 0);
8114 error_with_line (line_for_error (start_line), parse_error);
8118 } while (*instack[indepth].bufp != ')');
8120 /* If we got one arg but it was just whitespace, call that 0 args. */
8122 register U_CHAR *bp = args[0].raw;
8123 register U_CHAR *lim = bp + args[0].raw_length;
8124 /* cpp.texi says for foo ( ) we provide one argument.
8125 However, if foo wants just 0 arguments, treat this as 0. */
8127 while (bp != lim && is_space[*bp]) bp++;
8132 /* Don't output an error message if we have already output one for
8133 a parse error above. */
8135 if (nargs == 0 && i > 0) {
8137 error ("arguments given to macro `%s'", hp->name);
8138 } else if (i < nargs) {
8139 /* traditional C allows foo() if foo wants one argument. */
8140 if (nargs == 1 && i == 0 && traditional)
8142 /* the rest args token is allowed to absorb 0 tokens */
8143 else if (i == nargs - 1 && defn->rest_args)
8145 else if (parse_error)
8148 error ("macro `%s' used without args", hp->name);
8150 error ("macro `%s' used with just one arg", hp->name);
8152 error ("macro `%s' used with only %d args", hp->name, i);
8153 } else if (i > nargs) {
8155 error ("macro `%s' used with too many (%d) args", hp->name, i);
8158 /* Swallow the closeparen. */
8159 ++instack[indepth].bufp;
8161 /* If macro wants zero args, we parsed the arglist for checking only.
8162 Read directly from the macro definition. */
8164 xbuf = defn->expansion;
8165 xbuf_len = defn->length;
8167 register U_CHAR *exp = defn->expansion;
8168 register int offset; /* offset in expansion,
8169 copied a piece at a time */
8170 register int totlen; /* total amount of exp buffer filled so far */
8172 register struct reflist *ap, *last_ap;
8174 /* Macro really takes args. Compute the expansion of this call. */
8176 /* Compute length in characters of the macro's expansion.
8177 Also count number of times each arg is used. */
8178 xbuf_len = defn->length;
8179 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8181 xbuf_len += args[ap->argno].stringified_length;
8182 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8183 /* Add 4 for two newline-space markers to prevent
8184 token concatenation. */
8185 xbuf_len += args[ap->argno].raw_length + 4;
8187 /* We have an ordinary (expanded) occurrence of the arg.
8188 So compute its expansion, if we have not already. */
8189 if (args[ap->argno].expanded == 0) {
8191 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8192 args[ap->argno].raw + args[ap->argno].raw_length,
8195 args[ap->argno].expanded = obuf.buf;
8196 args[ap->argno].expand_length = obuf.length;
8197 args[ap->argno].free2 = obuf.buf;
8200 /* Add 4 for two newline-space markers to prevent
8201 token concatenation. */
8202 xbuf_len += args[ap->argno].expand_length + 4;
8204 if (args[ap->argno].use_count < 10)
8205 args[ap->argno].use_count++;
8208 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8210 /* Generate in XBUF the complete expansion
8211 with arguments substituted in.
8212 TOTLEN is the total size generated so far.
8213 OFFSET is the index in the definition
8214 of where we are copying from. */
8215 offset = totlen = 0;
8216 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8217 last_ap = ap, ap = ap->next) {
8218 register struct argdata *arg = &args[ap->argno];
8219 int count_before = totlen;
8221 /* Add chars to XBUF. */
8222 for (i = 0; i < ap->nchars; i++, offset++)
8223 xbuf[totlen++] = exp[offset];
8225 /* If followed by an empty rest arg with concatenation,
8226 delete the last run of nonwhite chars. */
8227 if (rest_zero && totlen > count_before
8228 && ((ap->rest_args && ap->raw_before != 0)
8229 || (last_ap != NULL && last_ap->rest_args
8230 && last_ap->raw_after != 0))) {
8231 /* Delete final whitespace. */
8232 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8236 /* Delete the nonwhites before them. */
8237 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8242 if (ap->stringify != 0) {
8243 int arglen = arg->raw_length;
8249 && (c = arg->raw[i], is_space[c]))
8252 && (c = arg->raw[arglen - 1], is_space[c]))
8255 xbuf[totlen++] = '\"'; /* insert beginning quote */
8256 for (; i < arglen; i++) {
8260 /* Special markers Newline Space
8261 generate nothing for a stringified argument. */
8262 if (c == '\n' && arg->raw[i+1] != '\n') {
8267 /* Internal sequences of whitespace are replaced by one space
8268 except within an string or char token. */
8269 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8271 /* Note that Newline Space does occur within whitespace
8272 sequences; consider it part of the sequence. */
8273 if (c == '\n' && is_space[arg->raw[i+1]])
8275 else if (c != '\n' && is_space[c])
8293 } else if (c == '\"' || c == '\'')
8297 /* Escape these chars */
8298 if (c == '\"' || (in_string && c == '\\'))
8299 xbuf[totlen++] = '\\';
8300 /* We used to output e.g. \008 for control characters here,
8301 but this doesn't conform to the C Standard.
8302 Just output the characters as-is. */
8306 xbuf[totlen++] = '\"'; /* insert ending quote */
8307 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8308 U_CHAR *p1 = arg->raw;
8309 U_CHAR *l1 = p1 + arg->raw_length;
8310 if (ap->raw_before != 0) {
8311 while (p1 != l1 && is_space[*p1]) p1++;
8312 while (p1 != l1 && is_idchar[*p1])
8313 xbuf[totlen++] = *p1++;
8314 /* Delete any no-reexpansion marker that follows
8315 an identifier at the beginning of the argument
8316 if the argument is concatenated with what precedes it. */
8317 if (p1[0] == '\n' && p1[1] == '-')
8319 } else if (!traditional) {
8320 /* Ordinary expanded use of the argument.
8321 Put in newline-space markers to prevent token pasting. */
8322 xbuf[totlen++] = '\n';
8323 xbuf[totlen++] = ' ';
8325 if (ap->raw_after != 0) {
8326 /* Arg is concatenated after: delete trailing whitespace,
8327 whitespace markers, and no-reexpansion markers. */
8329 if (is_space[l1[-1]]) l1--;
8330 else if (l1[-1] == '-') {
8331 U_CHAR *p2 = l1 - 1;
8332 /* If a `-' is preceded by an odd number of newlines then it
8333 and the last newline are a no-reexpansion marker. */
8334 while (p2 != p1 && p2[-1] == '\n') p2--;
8335 if ((l1 - 1 - p2) & 1) {
8344 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8346 if (!traditional && ap->raw_after == 0) {
8347 /* Ordinary expanded use of the argument.
8348 Put in newline-space markers to prevent token pasting. */
8349 xbuf[totlen++] = '\n';
8350 xbuf[totlen++] = ' ';
8353 /* Ordinary expanded use of the argument.
8354 Put in newline-space markers to prevent token pasting. */
8356 xbuf[totlen++] = '\n';
8357 xbuf[totlen++] = ' ';
8359 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8360 arg->expand_length);
8361 totlen += arg->expand_length;
8363 xbuf[totlen++] = '\n';
8364 xbuf[totlen++] = ' ';
8366 /* If a macro argument with newlines is used multiple times,
8367 then only expand the newlines once. This avoids creating output
8368 lines which don't correspond to any input line, which confuses
8370 if (arg->use_count > 1 && arg->newlines > 0) {
8371 /* Don't bother doing change_newlines for subsequent
8375 = change_newlines (arg->expanded, arg->expand_length);
8379 if (totlen > xbuf_len)
8383 /* If there is anything left of the definition after handling
8384 the arg list, copy that in too. */
8386 for (i = offset; i < defn->length; i++) {
8387 /* if we've reached the end of the macro */
8390 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8391 && last_ap->raw_after != 0))
8392 xbuf[totlen++] = exp[i];
8398 for (i = 0; i < nargs; i++) {
8399 if (args[i].free1 != 0)
8400 free (args[i].free1);
8401 if (args[i].free2 != 0)
8402 free (args[i].free2);
8406 xbuf = defn->expansion;
8407 xbuf_len = defn->length;
8410 /* Now put the expansion on the input stack
8411 so our caller will commence reading from it. */
8413 register FILE_BUF *ip2;
8415 ip2 = &instack[++indepth];
8418 ip2->nominal_fname = 0;
8419 ip2->nominal_fname_len = 0;
8421 /* This may not be exactly correct, but will give much better error
8422 messages for nested macro calls than using a line number of zero. */
8423 ip2->lineno = start_line;
8425 ip2->length = xbuf_len;
8427 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8429 ip2->if_stack = if_stack;
8430 ip2->system_header_p = 0;
8432 /* Recursive macro use sometimes works traditionally.
8433 #define foo(x,y) bar (x (y,0), y)
8437 hp->type = T_DISABLED;
8441 /* Parse a macro argument and store the info on it into *ARGPTR.
8442 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8443 Return nonzero to indicate a syntax error. */
8446 macarg (argptr, rest_args)
8447 register struct argdata *argptr;
8450 FILE_BUF *ip = &instack[indepth];
8456 /* Try to parse as much of the argument as exists at this
8457 input stack level. */
8458 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8459 &paren, &newlines, &comments, rest_args);
8461 /* If we find the end of the argument at this level,
8462 set up *ARGPTR to point at it in the input stack. */
8463 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8464 && bp != ip->buf + ip->length) {
8466 argptr->raw = ip->bufp;
8467 argptr->raw_length = bp - ip->bufp;
8468 argptr->newlines = newlines;
8472 /* This input stack level ends before the macro argument does.
8473 We must pop levels and keep parsing.
8474 Therefore, we must allocate a temporary buffer and copy
8475 the macro argument into it. */
8476 int bufsize = bp - ip->bufp;
8477 int extra = newlines;
8478 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8479 int final_start = 0;
8481 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8483 ip->lineno += newlines;
8485 while (bp == ip->buf + ip->length) {
8486 if (instack[indepth].macro == 0) {
8487 result = "unterminated macro call";
8490 ip->macro->type = T_MACRO;
8492 free (ip->free_ptr);
8493 ip = &instack[--indepth];
8496 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8497 &newlines, &comments, rest_args);
8498 final_start = bufsize;
8499 bufsize += bp - ip->bufp;
8501 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8502 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8505 ip->lineno += newlines;
8508 /* Now, if arg is actually wanted, record its raw form,
8509 discarding comments and duplicating newlines in whatever
8510 part of it did not come from a macro expansion.
8511 EXTRA space has been preallocated for duplicating the newlines.
8512 FINAL_START is the index of the start of that part. */
8514 argptr->raw = buffer;
8515 argptr->raw_length = bufsize;
8516 argptr->free1 = buffer;
8517 argptr->newlines = newlines;
8518 if ((newlines || comments) && ip->fname != 0)
8521 discard_comments (argptr->raw + final_start,
8522 argptr->raw_length - final_start,
8524 argptr->raw[argptr->raw_length] = 0;
8525 if (argptr->raw_length > bufsize + extra)
8530 /* If we are not discarding this argument,
8531 macroexpand it and compute its length as stringified.
8532 All this info goes into *ARGPTR. */
8535 register U_CHAR *buf, *lim;
8536 register int totlen;
8539 lim = buf + argptr->raw_length;
8541 while (buf != lim && is_space[*buf])
8543 while (buf != lim && is_space[lim[-1]])
8545 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8546 while (buf != lim) {
8547 register U_CHAR c = *buf++;
8549 /* Internal sequences of whitespace are replaced by one space
8550 in most cases, but not always. So count all the whitespace
8551 in case we need to keep it all. */
8554 SKIP_ALL_WHITE_SPACE (buf);
8557 if (c == '\"' || c == '\\') /* escape these chars */
8560 argptr->stringified_length = totlen;
8565 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8566 taken from the expansion of MACRO,
8567 counting parens in *DEPTHPTR,
8568 and return if reach LIMIT
8569 or before a `)' that would make *DEPTHPTR negative
8570 or before a comma when *DEPTHPTR is zero.
8571 Single and double quotes are matched and termination
8572 is inhibited within them. Comments also inhibit it.
8573 Value returned is pointer to stopping place.
8575 Increment *NEWLINES each time a newline is passed.
8576 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8577 Set *COMMENTS to 1 if a comment is seen. */
8580 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8582 register U_CHAR *limit;
8583 struct hashnode *macro;
8584 int *depthptr, *newlines, *comments;
8587 register U_CHAR *bp = start;
8589 while (bp < limit) {
8595 if (--(*depthptr) < 0)
8599 /* Traditionally, backslash makes following char not special. */
8600 if (traditional && bp + 1 < limit && bp[1] != '\n')
8609 if (bp[1] == '\\' && bp[2] == '\n')
8610 newline_fix (bp + 1);
8613 for (bp += 2; bp < limit; bp++) {
8616 else if (*bp == '*') {
8617 if (bp[-1] == '/' && warn_comments)
8618 warning ("`/*' within comment");
8619 if (bp[1] == '\\' && bp[2] == '\n')
8620 newline_fix (bp + 1);
8627 } else if (bp[1] == '/' && cplusplus_comments) {
8629 for (bp += 2; bp < limit; bp++) {
8635 warning ("multiline `//' comment");
8644 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8650 while (*bp == '\\' && bp[1] == '\n') {
8655 } else if (*bp == '\n') {
8664 /* if we've returned to lowest level and we aren't absorbing all args */
8665 if ((*depthptr) == 0 && rest_args == 0)
8675 /* Discard comments and duplicate newlines
8676 in the string of length LENGTH at START,
8677 except inside of string constants.
8678 The string is copied into itself with its beginning staying fixed.
8680 NEWLINES is the number of newlines that must be duplicated.
8681 We assume that that much extra space is available past the end
8685 discard_comments (start, length, newlines)
8690 register U_CHAR *ibp;
8691 register U_CHAR *obp;
8692 register U_CHAR *limit;
8695 /* If we have newlines to duplicate, copy everything
8696 that many characters up. Then, in the second part,
8697 we will have room to insert the newlines
8699 NEWLINES may actually be too large, because it counts
8700 newlines in string constants, and we don't duplicate those.
8701 But that does no harm. */
8703 ibp = start + length;
8704 obp = ibp + newlines;
8706 while (limit != ibp)
8710 ibp = start + newlines;
8711 limit = start + length + newlines;
8714 while (ibp < limit) {
8715 *obp++ = c = *ibp++;
8718 /* Duplicate the newline. */
8730 if (*ibp == '\\' && ibp[1] == '\n')
8732 /* Delete any comment. */
8733 if (cplusplus_comments && ibp[0] == '/') {
8734 /* Comments are equivalent to spaces. */
8737 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8741 if (ibp[0] != '*' || ibp + 1 >= limit)
8743 /* Comments are equivalent to spaces.
8744 For -traditional, a comment is equivalent to nothing. */
8749 while (++ibp < limit) {
8750 if (ibp[0] == '*') {
8751 if (ibp[1] == '\\' && ibp[2] == '\n')
8752 newline_fix (ibp + 1);
8753 if (ibp[1] == '/') {
8763 /* Notice and skip strings, so that we don't
8764 think that comments start inside them,
8765 and so we don't duplicate newlines in them. */
8768 while (ibp < limit) {
8769 *obp++ = c = *ibp++;
8772 if (c == '\n' && quotec == '\'')
8775 if (ibp < limit && *ibp == '\n') {
8779 while (*ibp == '\\' && ibp[1] == '\n')
8794 /* Turn newlines to spaces in the string of length LENGTH at START,
8795 except inside of string constants.
8796 The string is copied into itself with its beginning staying fixed. */
8799 change_newlines (start, length)
8803 register U_CHAR *ibp;
8804 register U_CHAR *obp;
8805 register U_CHAR *limit;
8809 limit = start + length;
8812 while (ibp < limit) {
8813 *obp++ = c = *ibp++;
8816 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8817 string. Skip past the newline and its duplicate.
8818 Put a space in the output. */
8829 /* Notice and skip strings, so that we don't delete newlines in them. */
8832 while (ibp < limit) {
8833 *obp++ = c = *ibp++;
8834 if (c == quotec && ibp[-2] != '\\')
8836 if (c == '\n' && quotec == '\'')
8847 /* my_strerror - return the descriptive text associated with an
8851 my_strerror (errnum)
8857 #ifndef HAVE_STRERROR
8858 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8860 result = strerror (errnum);
8863 /* VAXCRTL's strerror() takes an optional second argument, which only
8864 matters when the first argument is EVMSERR. However, it's simplest
8865 just to pass it unconditionally. `vaxc$errno' is declared in
8866 <errno.h>, and maintained by the library in parallel with `errno'.
8867 We assume that caller's `errnum' either matches the last setting of
8868 `errno' by the library or else does not have the value `EVMSERR'. */
8870 result = strerror (errnum, vaxc$errno);
8874 result = "undocumented I/O error";
8879 /* error - print error message and increment count of errors. */
8882 error (PRINTF_ALIST (msg))
8887 VA_START (args, msg);
8898 FILE_BUF *ip = NULL;
8900 print_containing_files ();
8902 for (i = indepth; i >= 0; i--)
8903 if (instack[i].fname != NULL) {
8909 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8910 fprintf (stderr, ":%d: ", ip->lineno);
8912 vfprintf (stderr, msg, args);
8913 fprintf (stderr, "\n");
8917 /* Error including a message from `errno'. */
8920 error_from_errno (name)
8925 FILE_BUF *ip = NULL;
8927 print_containing_files ();
8929 for (i = indepth; i >= 0; i--)
8930 if (instack[i].fname != NULL) {
8936 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8937 fprintf (stderr, ":%d: ", ip->lineno);
8940 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
8945 /* Print error message but don't count it. */
8948 warning (PRINTF_ALIST (msg))
8953 VA_START (args, msg);
8954 vwarning (msg, args);
8959 vwarning (msg, args)
8964 FILE_BUF *ip = NULL;
8966 if (inhibit_warnings)
8969 if (warnings_are_errors)
8972 print_containing_files ();
8974 for (i = indepth; i >= 0; i--)
8975 if (instack[i].fname != NULL) {
8981 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8982 fprintf (stderr, ":%d: ", ip->lineno);
8984 fprintf (stderr, "warning: ");
8985 vfprintf (stderr, msg, args);
8986 fprintf (stderr, "\n");
8990 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8991 error_with_line (int line, PRINTF_ALIST (msg))
8993 error_with_line (line, PRINTF_ALIST (msg))
9000 VA_START (args, msg);
9001 verror_with_line (line, msg, args);
9006 verror_with_line (line, msg, args)
9012 FILE_BUF *ip = NULL;
9014 print_containing_files ();
9016 for (i = indepth; i >= 0; i--)
9017 if (instack[i].fname != NULL) {
9023 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9024 fprintf (stderr, ":%d: ", line);
9026 vfprintf (stderr, msg, args);
9027 fprintf (stderr, "\n");
9032 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9033 warning_with_line (int line, PRINTF_ALIST (msg))
9035 warning_with_line (line, PRINTF_ALIST (msg))
9042 VA_START (args, msg);
9043 vwarning_with_line (line, msg, args);
9048 vwarning_with_line (line, msg, args)
9054 FILE_BUF *ip = NULL;
9056 if (inhibit_warnings)
9059 if (warnings_are_errors)
9062 print_containing_files ();
9064 for (i = indepth; i >= 0; i--)
9065 if (instack[i].fname != NULL) {
9071 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9072 fprintf (stderr, line ? ":%d: " : ": ", line);
9074 fprintf (stderr, "warning: ");
9075 vfprintf (stderr, msg, args);
9076 fprintf (stderr, "\n");
9079 /* Print an error message and maybe count it. */
9082 pedwarn (PRINTF_ALIST (msg))
9087 VA_START (args, msg);
9088 if (pedantic_errors)
9091 vwarning (msg, args);
9096 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9097 pedwarn_with_line (int line, PRINTF_ALIST (msg))
9099 pedwarn_with_line (line, PRINTF_ALIST (msg))
9106 VA_START (args, msg);
9107 if (pedantic_errors)
9108 verror_with_line (line, msg, args);
9110 vwarning_with_line (line, msg, args);
9114 /* Report a warning (or an error if pedantic_errors)
9115 giving specified file name and line number, not current. */
9118 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9119 pedwarn_with_file_and_line (char *file, size_t file_len, int line,
9122 pedwarn_with_file_and_line (file, file_len, line, PRINTF_ALIST (msg))
9131 if (!pedantic_errors && inhibit_warnings)
9134 eprint_string (file, file_len);
9135 fprintf (stderr, ":%d: ", line);
9137 if (pedantic_errors)
9139 if (!pedantic_errors)
9140 fprintf (stderr, "warning: ");
9141 VA_START (args, msg);
9142 vfprintf (stderr, msg, args);
9144 fprintf (stderr, "\n");
9147 /* Print the file names and line numbers of the #include
9148 directives which led to the current file. */
9151 print_containing_files ()
9153 FILE_BUF *ip = NULL;
9157 /* If stack of files hasn't changed since we last printed
9158 this info, don't repeat it. */
9159 if (last_error_tick == input_file_stack_tick)
9162 for (i = indepth; i >= 0; i--)
9163 if (instack[i].fname != NULL) {
9168 /* Give up if we don't find a source file. */
9172 /* Find the other, outer source files. */
9173 for (i--; i >= 0; i--)
9174 if (instack[i].fname != NULL) {
9178 fprintf (stderr, "In file included");
9180 fprintf (stderr, ",\n ");
9183 fprintf (stderr, " from ");
9184 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9185 fprintf (stderr, ":%d", ip->lineno);
9188 fprintf (stderr, ":\n");
9190 /* Record we have printed the status as of this time. */
9191 last_error_tick = input_file_stack_tick;
9194 /* Return the line at which an error occurred.
9195 The error is not necessarily associated with the current spot
9196 in the input stack, so LINE says where. LINE will have been
9197 copied from ip->lineno for the current input level.
9198 If the current level is for a file, we return LINE.
9199 But if the current level is not for a file, LINE is meaningless.
9200 In that case, we return the lineno of the innermost file. */
9203 line_for_error (line)
9209 for (i = indepth; i >= 0; ) {
9210 if (instack[i].fname != 0)
9215 line1 = instack[i].lineno;
9223 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9225 * As things stand, nothing is ever placed in the output buffer to be
9226 * removed again except when it's KNOWN to be part of an identifier,
9227 * so flushing and moving down everything left, instead of expanding,
9231 /* You might think void was cleaner for the return type,
9232 but that would get type mismatch in check_expand in strict ANSI. */
9235 grow_outbuf (obuf, needed)
9236 register FILE_BUF *obuf;
9237 register int needed;
9242 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9245 /* Make it at least twice as big as it is now. */
9247 /* Make it have at least 150% of the free space we will need. */
9248 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9249 if (minsize > obuf->length)
9250 obuf->length = minsize;
9252 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9255 obuf->bufp = p + (obuf->bufp - obuf->buf);
9261 /* Symbol table for macro names and special symbols */
9264 * install a name in the main hash table, even if it is already there.
9265 * name stops with first non alphanumeric, except leading '#'.
9266 * caller must check against redefinition if that is desired.
9267 * delete_macro () removes things installed by install () in fifo order.
9268 * this is important because of the `defined' special symbol used
9269 * in #if, and also if pushdef/popdef directives are ever implemented.
9271 * If LEN is >= 0, it is the length of the name.
9272 * Otherwise, compute the length by scanning the entire name.
9274 * If HASH is >= 0, it is the precomputed hash code.
9275 * Otherwise, compute the hash code.
9279 install (name, len, type, value, hash)
9282 enum node_type type;
9286 register HASHNODE *hp;
9287 register int i, bucket;
9288 register U_CHAR *p, *q;
9292 while (is_idchar[*p])
9298 hash = hashf (name, len, HASHSIZE);
9300 i = sizeof (HASHNODE) + len + 1;
9301 hp = (HASHNODE *) xmalloc (i);
9303 hp->bucket_hdr = &hashtab[bucket];
9304 hp->next = hashtab[bucket];
9305 hashtab[bucket] = hp;
9307 if (hp->next != NULL)
9308 hp->next->prev = hp;
9311 hp->value.cpval = value;
9312 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9315 for (i = 0; i < len; i++)
9322 * find the most recent hash node for name name (ending with first
9323 * non-identifier char) installed by install
9325 * If LEN is >= 0, it is the length of the name.
9326 * Otherwise, compute the length by scanning the entire name.
9328 * If HASH is >= 0, it is the precomputed hash code.
9329 * Otherwise, compute the hash code.
9333 lookup (name, len, hash)
9338 register U_CHAR *bp;
9339 register HASHNODE *bucket;
9342 for (bp = name; is_idchar[*bp]; bp++) ;
9347 hash = hashf (name, len, HASHSIZE);
9349 bucket = hashtab[hash];
9351 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9353 bucket = bucket->next;
9359 * Delete a hash node. Some weirdness to free junk from macros.
9360 * More such weirdness will have to be added if you define more hash
9361 * types that need it.
9364 /* Note that the DEFINITION of a macro is removed from the hash table
9365 but its storage is not freed. This would be a storage leak
9366 except that it is not reasonable to keep undefining and redefining
9367 large numbers of macros many times.
9368 In any case, this is necessary, because a macro can be #undef'd
9369 in the middle of reading the arguments to a call to it.
9370 If #undef freed the DEFINITION, that would crash. */
9377 if (hp->prev != NULL)
9378 hp->prev->next = hp->next;
9379 if (hp->next != NULL)
9380 hp->next->prev = hp->prev;
9382 /* Make sure that the bucket chain header that the deleted guy was
9383 on points to the right thing afterwards. */
9384 if (hp == *hp->bucket_hdr)
9385 *hp->bucket_hdr = hp->next;
9388 if (hp->type == T_MACRO) {
9389 DEFINITION *d = hp->value.defn;
9390 struct reflist *ap, *nextap;
9392 for (ap = d->pattern; ap != NULL; ap = nextap) {
9403 * return hash function on name. must be compatible with the one
9404 * computed a step at a time, elsewhere
9408 hashf (name, len, hashsize)
9409 register U_CHAR *name;
9416 r = HASHSTEP (r, *name++);
9418 return MAKE_POS (r) % hashsize;
9422 /* Dump the definition of a single macro HP to OF. */
9425 dump_single_macro (hp, of)
9426 register HASHNODE *hp;
9429 register DEFINITION *defn = hp->value.defn;
9435 /* Print the definition of the macro HP. */
9437 fprintf (of, "#define %s", hp->name);
9439 if (defn->nargs >= 0) {
9443 for (i = 0; i < defn->nargs; i++) {
9444 dump_arg_n (defn, i, of);
9445 if (i + 1 < defn->nargs)
9455 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9456 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9457 offset += ap->nchars;
9459 if (ap->nchars != 0)
9461 if (ap->stringify) {
9462 switch (ap->stringify) {
9463 case SHARP_TOKEN: fprintf (of, "#"); break;
9464 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9465 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9466 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9470 if (ap->raw_before != 0) {
9472 switch (ap->raw_before) {
9473 case WHITE_SHARP_TOKEN:
9474 case WHITE_PERCENT_COLON_TOKEN:
9481 switch (ap->raw_before) {
9482 case SHARP_TOKEN: fprintf (of, "##"); break;
9483 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9484 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9485 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9492 dump_arg_n (defn, ap->argno, of);
9493 if (!traditional && ap->raw_after != 0) {
9494 switch (ap->raw_after) {
9495 case SHARP_TOKEN: fprintf (of, "##"); break;
9496 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9497 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9498 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9504 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9508 /* Dump all macro definitions as #defines to stdout. */
9515 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9516 register HASHNODE *hp;
9518 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9519 if (hp->type == T_MACRO)
9520 dump_single_macro (hp, stdout);
9525 /* Output to OF a substring of a macro definition.
9526 BASE is the beginning of the definition.
9527 Output characters START thru LENGTH.
9528 Unless traditional, discard newlines outside of strings, thus
9529 converting funny-space markers to ordinary spaces. */
9532 dump_defn_1 (base, start, length, of)
9538 U_CHAR *p = base + start;
9539 U_CHAR *limit = base + start + length;
9542 fwrite (p, sizeof (*p), length, of);
9545 if (*p == '\"' || *p =='\'') {
9546 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9547 NULL_PTR, NULL_PTR);
9548 fwrite (p, sizeof (*p), p1 - p, of);
9559 /* Print the name of argument number ARGNUM of macro definition DEFN
9561 Recall that DEFN->args.argnames contains all the arg names
9562 concatenated in reverse order with comma-space in between. */
9565 dump_arg_n (defn, argnum, of)
9570 register U_CHAR *p = defn->args.argnames;
9571 while (argnum + 1 < defn->nargs) {
9572 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9576 while (*p && *p != ',') {
9582 /* Initialize syntactic classifications of characters. */
9585 initialize_char_syntax ()
9590 * Set up is_idchar and is_idstart tables. These should be
9591 * faster than saying (is_alpha (c) || c == '_'), etc.
9592 * Set up these things before calling any routines tthat
9595 for (i = 'a'; i <= 'z'; i++) {
9596 is_idchar[i - 'a' + 'A'] = 1;
9598 is_idstart[i - 'a' + 'A'] = 1;
9601 for (i = '0'; i <= '9'; i++)
9604 is_idstart['_'] = 1;
9606 is_idstart['$'] = 1;
9608 /* horizontal space table */
9609 is_hor_space[' '] = 1;
9610 is_hor_space['\t'] = 1;
9611 is_hor_space['\v'] = 1;
9612 is_hor_space['\f'] = 1;
9613 is_hor_space['\r'] = 1;
9622 char_name['\v'] = "vertical tab";
9623 char_name['\f'] = "formfeed";
9624 char_name['\r'] = "carriage return";
9627 /* Initialize the built-in macros. */
9630 initialize_builtins (inp, outp)
9634 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9635 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9636 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9637 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9638 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9639 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9640 #ifndef NO_BUILTIN_SIZE_TYPE
9641 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9643 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9644 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9646 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9647 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9649 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9651 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9653 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9655 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9656 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9659 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9660 /* This is supplied using a -D by the compiler driver
9661 so that it is present only when truly compiling with GNU C. */
9662 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9663 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9667 char directive[2048];
9668 U_CHAR *udirective = (U_CHAR *) directive;
9669 register struct directive *dp = &directive_table[0];
9670 struct tm *timebuf = timestamp ();
9672 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9673 instack[0].nominal_fname);
9674 output_line_directive (inp, outp, 0, same_file);
9675 pass_thru_directive (udirective, &udirective[strlen (directive)],
9678 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9679 output_line_directive (inp, outp, 0, same_file);
9680 pass_thru_directive (udirective, &udirective[strlen (directive)],
9683 #ifndef NO_BUILTIN_SIZE_TYPE
9684 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9685 output_line_directive (inp, outp, 0, same_file);
9686 pass_thru_directive (udirective, &udirective[strlen (directive)],
9690 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9691 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9692 output_line_directive (inp, outp, 0, same_file);
9693 pass_thru_directive (udirective, &udirective[strlen (directive)],
9697 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9698 output_line_directive (inp, outp, 0, same_file);
9699 pass_thru_directive (udirective, &udirective[strlen (directive)],
9702 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9703 monthnames[timebuf->tm_mon],
9704 timebuf->tm_mday, timebuf->tm_year + 1900);
9705 output_line_directive (inp, outp, 0, same_file);
9706 pass_thru_directive (udirective, &udirective[strlen (directive)],
9709 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9710 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9711 output_line_directive (inp, outp, 0, same_file);
9712 pass_thru_directive (udirective, &udirective[strlen (directive)],
9717 sprintf (directive, " __STDC__ 1");
9718 output_line_directive (inp, outp, 0, same_file);
9719 pass_thru_directive (udirective, &udirective[strlen (directive)],
9724 sprintf (directive, " __OBJC__ 1");
9725 output_line_directive (inp, outp, 0, same_file);
9726 pass_thru_directive (udirective, &udirective[strlen (directive)],
9733 * process a given definition string, for initialization
9734 * If STR is just an identifier, define it with value 1.
9735 * If STR has anything after the identifier, then it should
9736 * be identifier=definition.
9740 make_definition (str, op)
9745 struct directive *kt;
9748 p = buf = (U_CHAR *) str;
9749 if (!is_idstart[*p]) {
9750 error ("malformed option `-D %s'", str);
9753 while (is_idchar[*++p])
9756 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9759 p = (U_CHAR *) str; /* Error */
9762 buf = (U_CHAR *) alloca (p - buf + 4);
9763 strcpy ((char *)buf, str);
9764 strcat ((char *)buf, " 1");
9765 } else if (*p != '=') {
9766 error ("malformed option `-D %s'", str);
9770 /* Copy the entire option so we can modify it. */
9771 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9772 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9773 /* Change the = to a space. */
9774 buf[p - (U_CHAR *) str] = ' ';
9775 /* Scan for any backslash-newline and remove it. */
9777 q = &buf[p - (U_CHAR *) str];
9779 if (*p == '\"' || *p == '\'') {
9780 int unterminated = 0;
9781 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9782 NULL_PTR, NULL_PTR, &unterminated);
9787 } else if (*p == '\\' && p[1] == '\n')
9789 /* Change newline chars into newline-markers. */
9790 else if (*p == '\n')
9802 ip = &instack[++indepth];
9803 ip->nominal_fname = ip->fname = "*Initialization*";
9804 ip->nominal_fname_len = strlen (ip->nominal_fname);
9806 ip->buf = ip->bufp = buf;
9807 ip->length = strlen ((char *) buf);
9811 ip->if_stack = if_stack;
9812 ip->system_header_p = 0;
9814 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9817 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9818 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9822 /* JF, this does the work for the -U option */
9825 make_undef (str, op)
9830 struct directive *kt;
9832 ip = &instack[++indepth];
9833 ip->nominal_fname = ip->fname = "*undef*";
9834 ip->nominal_fname_len = strlen (ip->nominal_fname);
9836 ip->buf = ip->bufp = (U_CHAR *) str;
9837 ip->length = strlen (str);
9841 ip->if_stack = if_stack;
9842 ip->system_header_p = 0;
9844 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9847 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9851 /* Process the string STR as if it appeared as the body of a #assert.
9852 OPTION is the option name for which STR was the argument. */
9855 make_assertion (option, str)
9860 struct directive *kt;
9861 U_CHAR *buf, *p, *q;
9863 /* Copy the entire option so we can modify it. */
9864 buf = (U_CHAR *) alloca (strlen (str) + 1);
9865 strcpy ((char *) buf, str);
9866 /* Scan for any backslash-newline and remove it. */
9869 if (*p == '\\' && p[1] == '\n')
9877 if (!is_idstart[*p]) {
9878 error ("malformed option `%s %s'", option, str);
9881 while (is_idchar[*++p])
9883 SKIP_WHITE_SPACE (p);
9884 if (! (*p == 0 || *p == '(')) {
9885 error ("malformed option `%s %s'", option, str);
9889 ip = &instack[++indepth];
9890 ip->nominal_fname = ip->fname = "*Initialization*";
9891 ip->nominal_fname_len = strlen (ip->nominal_fname);
9893 ip->buf = ip->bufp = buf;
9894 ip->length = strlen ((char *) buf);
9898 ip->if_stack = if_stack;
9899 ip->system_header_p = 0;
9901 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9904 /* Pass NULL as output ptr to do_define since we KNOW it never does
9906 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9910 #ifndef DIR_SEPARATOR
9911 #define DIR_SEPARATOR '/'
9914 /* The previous include prefix, if any, is PREV_FILE_NAME.
9915 Translate any pathnames with COMPONENT.
9916 Allocate a new include prefix whose name is the
9917 simplified concatenation of PREFIX and NAME,
9918 with a trailing / added if needed.
9919 But return 0 if the include prefix should be ignored,
9920 e.g. because it is a duplicate of PREV_FILE_NAME. */
9922 static struct file_name_list *
9923 new_include_prefix (prev_file_name, component, prefix, name)
9924 struct file_name_list *prev_file_name;
9930 fatal ("Directory name missing after command line option");
9933 /* Ignore the empty string. */
9936 prefix = update_path (prefix, component);
9937 name = update_path (name, component);
9940 struct file_name_list *dir
9941 = ((struct file_name_list *)
9942 xmalloc (sizeof (struct file_name_list)
9943 + strlen (prefix) + strlen (name) + 2));
9945 strcpy (dir->fname, prefix);
9946 strcat (dir->fname, name);
9947 len = simplify_filename (dir->fname);
9949 /* Convert directory name to a prefix. */
9950 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
9951 if (len == 1 && dir->fname[len - 1] == '.')
9954 dir->fname[len++] = DIR_SEPARATOR;
9955 dir->fname[len] = 0;
9958 /* Ignore a directory whose name matches the previous one. */
9959 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9960 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9961 if (!first_bracket_include)
9962 first_bracket_include = prev_file_name;
9968 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
9970 /* Add a trailing "." if there is a filename. This increases the number
9971 of systems that can stat directories. We remove it below. */
9974 dir->fname[len] = '.';
9975 dir->fname[len + 1] = 0;
9978 /* Ignore a nonexistent directory. */
9979 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9980 if (errno != ENOENT && errno != ENOTDIR)
9981 error_from_errno (dir->fname);
9987 dir->fname[len] = 0;
9989 /* Ignore a directory whose identity matches the previous one. */
9991 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9992 && prev_file_name->st.st_dev == dir->st.st_dev) {
9993 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9994 if (!first_bracket_include)
9995 first_bracket_include = prev_file_name;
10002 dir->c_system_include_path = 0;
10003 dir->got_name_map = 0;
10009 /* Append a chain of `struct file_name_list's
10010 to the end of the main include chain.
10011 FIRST is the beginning of the chain to append, and LAST is the end. */
10014 append_include_chain (first, last)
10015 struct file_name_list *first, *last;
10017 struct file_name_list *dir;
10019 if (!first || !last)
10025 last_include->next = first;
10027 if (first_bracket_include == 0)
10028 first_bracket_include = first;
10030 for (dir = first; ; dir = dir->next) {
10031 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10032 if (len > max_include_len)
10033 max_include_len = len;
10039 last_include = last;
10042 /* Place into DST a representation of the file named SRC that is suitable
10043 for `make'. Do not null-terminate DST. Return its length. */
10045 quote_string_for_make (dst, src)
10060 /* GNU make uses a weird quoting scheme for white space.
10061 A space or tab preceded by 2N+1 backslashes represents
10062 N backslashes followed by space; a space or tab
10063 preceded by 2N backslashes represents N backslashes at
10064 the end of a file name; and backslashes in other
10065 contexts should not be doubled. */
10067 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10079 goto ordinary_char;
10085 /* Fall through. This can mishandle things like "$(" but
10086 there's no easy fix. */
10089 /* This can mishandle characters in the string "\0\n%*?[\\~";
10090 exactly which chars are mishandled depends on the `make' version.
10091 We know of no portable solution for this;
10092 even GNU make 3.76.1 doesn't solve the problem entirely.
10093 (Also, '\0' is mishandled due to our calling conventions.) */
10103 /* Add output to `deps_buffer' for the -M switch.
10104 STRING points to the text to be output.
10105 SPACER is ':' for targets, ' ' for dependencies. */
10108 deps_output (string, spacer)
10112 int size = quote_string_for_make ((char *) 0, string);
10117 #ifndef MAX_OUTPUT_COLUMNS
10118 #define MAX_OUTPUT_COLUMNS 72
10120 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10121 && 1 < deps_column) {
10122 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10129 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10130 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10131 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10133 if (spacer == ' ') {
10134 deps_buffer[deps_size++] = ' ';
10137 quote_string_for_make (&deps_buffer[deps_size], string);
10139 deps_column += size;
10140 if (spacer == ':') {
10141 deps_buffer[deps_size++] = ':';
10144 deps_buffer[deps_size] = 0;
10148 fatal (PRINTF_ALIST (msg))
10153 fprintf (stderr, "%s: ", progname);
10154 VA_START (args, msg);
10155 vfprintf (stderr, msg, args);
10157 fprintf (stderr, "\n");
10158 exit (FATAL_EXIT_CODE);
10161 /* More 'friendly' abort that prints the line and file.
10162 config.h can #define abort fancy_abort if you like that sort of thing. */
10167 fatal ("Internal gcc abort.");
10171 perror_with_name (name)
10174 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10179 pfatal_with_name (name)
10182 perror_with_name (name);
10186 exit (FATAL_EXIT_CODE);
10190 /* Handler for SIGPIPE. */
10193 pipe_closed (signo)
10194 /* If this is missing, some compilers complain. */
10197 fatal ("output pipe has been closed");
10203 fatal ("Memory exhausted.");
10211 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10218 xrealloc (old, size)
10222 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10229 xcalloc (number, size)
10230 size_t number, size;
10232 register size_t total = number * size;
10233 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10236 bzero (ptr, total);
10244 size_t size = strlen (input);
10245 char *output = xmalloc (size + 1);
10246 strcpy (output, input);
10252 /* Under VMS we need to fix up the "include" specification filename so
10253 that everything following the 1st slash is changed into its correct
10254 VMS file specification. */
10257 hack_vms_include_specification (fname, vaxc_include)
10261 register char *cp, *cp1, *cp2;
10262 int f, check_filename_before_returning;
10265 check_filename_before_returning = 0;
10267 cp = base_name (fname);
10270 * Check if we have a vax-c style '#include filename'
10271 * and add the missing .h
10273 if (vaxc_include && !index (cp,'.'))
10276 cp2 = Local; /* initialize */
10278 /* We are trying to do a number of things here. First of all, we are
10279 trying to hammer the filenames into a standard format, such that later
10280 processing can handle them.
10282 If the file name contains something like [dir.], then it recognizes this
10283 as a root, and strips the ".]". Later processing will add whatever is
10284 needed to get things working properly.
10286 If no device is specified, then the first directory name is taken to be
10287 a device name (or a rooted logical). */
10289 /* See if we found that 1st slash */
10290 if (cp == 0) return; /* Nothing to do!!! */
10291 if (*cp != '/') return; /* Nothing to do!!! */
10292 /* Point to the UNIX filename part (which needs to be fixed!) */
10294 /* If the directory spec is not rooted, we can just copy
10295 the UNIX filename part and we are done */
10296 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10297 if (cp[-2] != '.') {
10299 * The VMS part ends in a `]', and the preceding character is not a `.'.
10300 * We strip the `]', and then splice the two parts of the name in the
10301 * usual way. Given the default locations for include files in cccp.c,
10302 * we will only use this code if the user specifies alternate locations
10303 * with the /include (-I) switch on the command line. */
10304 cp -= 1; /* Strip "]" */
10305 cp1--; /* backspace */
10308 * The VMS part has a ".]" at the end, and this will not do. Later
10309 * processing will add a second directory spec, and this would be a syntax
10310 * error. Thus we strip the ".]", and thus merge the directory specs.
10311 * We also backspace cp1, so that it points to a '/'. This inhibits the
10312 * generation of the 000000 root directory spec (which does not belong here
10315 cp -= 2; /* Strip ".]" */
10316 cp1--; }; /* backspace */
10319 /* We drop in here if there is no VMS style directory specification yet.
10320 * If there is no device specification either, we make the first dir a
10321 * device and try that. If we do not do this, then we will be essentially
10322 * searching the users default directory (as if they did a #include "asdf.h").
10324 * Then all we need to do is to push a '[' into the output string. Later
10325 * processing will fill this in, and close the bracket.
10327 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10328 *cp2++ = '['; /* Open the directory specification */
10331 /* at this point we assume that we have the device spec, and (at least
10332 the opening "[" for a directory specification. We may have directories
10333 specified already */
10335 /* If there are no other slashes then the filename will be
10336 in the "root" directory. Otherwise, we need to add
10337 directory specifications. */
10338 if (index (cp1, '/') == 0) {
10339 /* Just add "000000]" as the directory string */
10340 strcpy (cp2, "000000]");
10341 cp2 += strlen (cp2);
10342 check_filename_before_returning = 1; /* we might need to fool with this later */
10344 /* As long as there are still subdirectories to add, do them. */
10345 while (index (cp1, '/') != 0) {
10346 /* If this token is "." we can ignore it */
10347 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10351 /* Add a subdirectory spec. Do not duplicate "." */
10352 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10354 /* If this is ".." then the spec becomes "-" */
10355 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10356 /* Add "-" and skip the ".." */
10361 /* Copy the subdirectory */
10362 while (*cp1 != '/') *cp2++= *cp1++;
10363 cp1++; /* Skip the "/" */
10365 /* Close the directory specification */
10366 if (cp2[-1] == '.') /* no trailing periods */
10370 /* Now add the filename */
10371 while (*cp1) *cp2++ = *cp1++;
10373 /* Now append it to the original VMS spec. */
10374 strcpy (cp, Local);
10376 /* If we put a [000000] in the filename, try to open it first. If this fails,
10377 remove the [000000], and return that name. This provides flexibility
10378 to the user in that they can use both rooted and non-rooted logical names
10379 to point to the location of the file. */
10381 if (check_filename_before_returning) {
10382 f = open (fname, O_RDONLY, 0666);
10384 /* The file name is OK as it is, so return it as is. */
10388 /* The filename did not work. Try to remove the [000000] from the name,
10390 cp = index (fname, '[');
10391 cp2 = index (fname, ']') + 1;
10392 strcpy (cp, cp2); /* this gets rid of it */
10400 /* The following wrapper functions supply additional arguments to the VMS
10401 I/O routines to optimize performance with file handling. The arguments
10403 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10404 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10405 "fop=tef"- Truncate unused portions of file when closing file.
10406 "shr=nil"- Disallow file sharing while file is open. */
10409 VMS_freopen (fname, type, oldfile)
10414 #undef freopen /* Get back the real freopen routine. */
10415 if (strcmp (type, "w") == 0)
10416 return freopen (fname, type, oldfile,
10417 "mbc=16", "deq=64", "fop=tef", "shr=nil");
10418 return freopen (fname, type, oldfile, "mbc=16");
10422 VMS_fopen (fname, type)
10426 #undef fopen /* Get back the real fopen routine. */
10427 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10428 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10429 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10430 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10433 return (*vmslib_fopen) (fname, type, "mbc=32",
10434 "deq=64", "fop=tef", "shr=nil");
10436 return (*vmslib_fopen) (fname, type, "mbc=32");
10440 VMS_open (fname, flags, prot)
10445 #undef open /* Get back the real open routine. */
10446 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10449 /* more VMS hackery */
10453 extern unsigned long SYS$PARSE(), SYS$SEARCH();
10455 /* Work around another library bug. If a file is located via a searchlist,
10456 and if the device it's on is not the same device as the one specified
10457 in the first element of that searchlist, then both stat() and fstat()
10458 will fail to return info about it. `errno' will be set to EVMSERR, and
10459 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10460 We can get around this by fully parsing the filename and then passing
10461 that absolute name to stat().
10463 Without this fix, we can end up failing to find header files, which is
10464 bad enough, but then compounding the problem by reporting the reason for
10465 failure as "normal successful completion." */
10467 #undef fstat /* Get back to the library version. */
10470 VMS_fstat (fd, statbuf)
10472 struct stat *statbuf;
10474 int result = fstat (fd, statbuf);
10479 char nambuf[NAM$C_MAXRSS+1];
10481 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10482 result = VMS_stat (nambuf, statbuf);
10483 /* No fclose(fp) here; that would close(fd) as well. */
10490 VMS_stat (name, statbuf)
10492 struct stat *statbuf;
10494 int result = stat (name, statbuf);
10500 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
10501 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
10504 fab.fab$l_fna = (char *) name;
10505 fab.fab$b_fns = (unsigned char) strlen (name);
10506 fab.fab$l_nam = (void *) &nam;
10508 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10509 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10510 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10511 if (SYS$PARSE (&fab) & 1)
10513 if (SYS$SEARCH (&fab) & 1)
10515 res_nam[nam.nam$b_rsl] = '\0';
10516 result = stat (res_nam, statbuf);
10518 /* Clean up searchlist context cached by the system. */
10519 nam.nam$b_nop = NAM$M_SYNCHK;
10520 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10521 (void) SYS$PARSE (&fab);