Declare malloc, free, and atexit if inhibit_libc is defined.
[official-gcc.git] / gcc / cccp.c
blob003d7f08d316afccf3ec3a0ce47eb7c04d93c6e5
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-98, 1999 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "config.h"
23 #include "system.h"
24 #include <signal.h>
26 #ifdef HAVE_SYS_RESOURCE_H
27 # include <sys/resource.h>
28 #endif
30 typedef unsigned char U_CHAR;
32 #include "pcp.h"
33 #include "intl.h"
34 #include "prefix.h"
36 #ifdef MULTIBYTE_CHARS
37 #include "mbchar.h"
38 #include <locale.h>
39 #endif /* MULTIBYTE_CHARS */
41 #ifndef GET_ENV_PATH_LIST
42 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
43 #endif
45 #ifndef STANDARD_INCLUDE_DIR
46 # define STANDARD_INCLUDE_DIR "/usr/include"
47 #endif
49 /* By default, colon separates directories in a path. */
50 #ifndef PATH_SEPARATOR
51 # define PATH_SEPARATOR ':'
52 #endif
54 /* By default, a slash separates directory names. */
55 #ifndef DIR_SEPARATOR
56 # define DIR_SEPARATOR '/'
57 #endif
59 /* By default, the suffix for object files is ".o". */
60 #ifdef OBJECT_SUFFIX
61 # define HAVE_OBJECT_SUFFIX
62 #else
63 # define OBJECT_SUFFIX ".o"
64 #endif
66 /* VMS-specific definitions */
67 #ifdef VMS
68 #include <descrip.h>
69 #include <ssdef.h>
70 #include <syidef.h>
71 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
72 #define fopen(fname,mode) VMS_fopen (fname,mode)
73 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
74 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
75 #define fwrite(ptr,size,nitems,stream) VMS_fwrite (ptr,size,nitems,stream)
76 static int VMS_fstat (), VMS_stat ();
77 static int VMS_open ();
78 static FILE *VMS_fopen ();
79 static FILE *VMS_freopen ();
80 static size_t VMS_fwrite ();
81 static void hack_vms_include_specification ();
82 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
83 #define INO_T_HASH(a) 0
84 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
85 #endif /* VMS */
87 /* Windows does not natively support inodes, and neither does MSDOS. */
88 #if (defined (_WIN32) && ! defined (__CYGWIN__) && ! defined (_UWIN)) \
89 || defined (__MSDOS__)
90 #define INO_T_EQ(a, b) 0
91 #endif
93 #ifndef INO_T_EQ
94 #define INO_T_EQ(a, b) ((a) == (b))
95 #endif
97 #ifndef INO_T_HASH
98 #define INO_T_HASH(a) (a)
99 #endif
101 #ifndef INCLUDE_LEN_FUDGE
102 #define INCLUDE_LEN_FUDGE 0
103 #endif
105 /* External declarations. */
107 extern char *version_string;
108 HOST_WIDEST_INT parse_escape PROTO((char **, HOST_WIDEST_INT));
109 HOST_WIDEST_INT parse_c_expression PROTO((char *, int));
111 /* Name under which this program was invoked. */
113 static char *progname;
115 /* Nonzero means use extra default include directories for C++. */
117 static int cplusplus;
119 /* Nonzero means handle cplusplus style comments */
121 static int cplusplus_comments;
123 /* Nonzero means handle #import, for objective C. */
125 static int objc;
127 /* Nonzero means this is an assembly file, and allow
128 unknown directives, which could be comments. */
130 static int lang_asm;
132 /* Current maximum length of directory names in the search path
133 for include files. (Altered as we get more of them.) */
135 static int max_include_len;
137 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
139 static int for_lint = 0;
141 /* Nonzero means copy comments into the output file. */
143 static int put_out_comments = 0;
145 /* Nonzero means don't process the ANSI trigraph sequences. */
147 static int no_trigraphs = 0;
149 /* Nonzero means print the names of included files rather than
150 the preprocessed output. 1 means just the #include "...",
151 2 means #include <...> as well. */
153 static int print_deps = 0;
155 /* Nonzero if missing .h files in -M output are assumed to be generated
156 files and not errors. */
158 static int print_deps_missing_files = 0;
160 /* Nonzero means print names of header files (-H). */
162 static int print_include_names = 0;
164 /* Nonzero means don't output line number information. */
166 static int no_line_directives;
168 /* Nonzero means output the text in failing conditionals,
169 inside #failed ... #endfailed. */
171 static int output_conditionals;
173 /* dump_only means inhibit output of the preprocessed text
174 and instead output the definitions of all user-defined
175 macros in a form suitable for use as input to cccp.
176 dump_names means pass #define and the macro name through to output.
177 dump_definitions means pass the whole definition (plus #define) through
180 static enum {dump_none, dump_only, dump_names, dump_definitions}
181 dump_macros = dump_none;
183 /* Nonzero means pass all #define and #undef directives which we actually
184 process through to the output stream. This feature is used primarily
185 to allow cc1 to record the #defines and #undefs for the sake of
186 debuggers which understand about preprocessor macros, but it may
187 also be useful with -E to figure out how symbols are defined, and
188 where they are defined. */
189 static int debug_output = 0;
191 /* Nonzero means pass #include lines through to the output,
192 even if they are ifdefed out. */
193 static int dump_includes;
195 /* Nonzero indicates special processing used by the pcp program. The
196 special effects of this mode are:
198 Inhibit all macro expansion, except those inside #if directives.
200 Process #define directives normally, and output their contents
201 to the output file.
203 Output preconditions to pcp_outfile indicating all the relevant
204 preconditions for use of this file in a later cpp run.
206 static FILE *pcp_outfile;
208 /* Nonzero means we are inside an IF during a -pcp run. In this mode
209 macro expansion is done, and preconditions are output for all macro
210 uses requiring them. */
211 static int pcp_inside_if;
213 /* Nonzero means never to include precompiled files.
214 This is 1 since there's no way now to make precompiled files,
215 so it's not worth testing for them. */
216 static int no_precomp = 1;
218 /* Nonzero means give all the error messages the ANSI standard requires. */
220 int pedantic;
222 /* Nonzero means try to make failure to fit ANSI C an error. */
224 static int pedantic_errors;
226 /* Nonzero means don't print warning messages. -w. */
228 static int inhibit_warnings = 0;
230 /* Nonzero means warn if slash-star appears in a slash-star comment,
231 or if newline-backslash appears in a slash-slash comment. */
233 static int warn_comments;
235 /* Nonzero means warn if a macro argument is (or would be)
236 stringified with -traditional. */
238 static int warn_stringify;
240 /* Nonzero means warn if there are any trigraphs. */
242 static int warn_trigraphs;
244 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
246 static int warn_undef;
248 /* Nonzero means warn if we find white space where it doesn't belong. */
250 static int warn_white_space;
252 /* Nonzero means warn if #import is used. */
254 static int warn_import = 1;
256 /* Nonzero means turn warnings into errors. */
258 static int warnings_are_errors;
260 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
262 int traditional;
264 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
266 int c89;
268 /* Nonzero for the 199x C Standard. */
270 int c9x;
272 /* Nonzero causes output not to be done,
273 but directives such as #define that have side effects
274 are still obeyed. */
276 static int no_output;
278 /* Nonzero means we should look for header.gcc files that remap file names. */
279 static int remap;
281 /* Nonzero means this file was included with a -imacros or -include
282 command line and should not be recorded as an include file. */
284 static int no_record_file;
286 /* Nonzero means that we have finished processing the command line options.
287 This flag is used to decide whether or not to issue certain errors
288 and/or warnings. */
290 static int done_initializing = 0;
292 /* Line where a newline was first seen in a string constant. */
294 static int multiline_string_line = 0;
296 /* I/O buffer structure.
297 The `fname' field is nonzero for source files and #include files
298 and for the dummy text used for -D and -U.
299 It is zero for rescanning results of macro expansion
300 and for expanding macro arguments. */
301 #define INPUT_STACK_MAX 400
302 static struct file_buf {
303 char *fname;
304 /* Filename specified with #line directive. */
305 char *nominal_fname;
306 /* The length of nominal_fname, which may contain embedded NULs. */
307 size_t nominal_fname_len;
308 /* Include file description. */
309 struct include_file *inc;
310 /* Record where in the search path this file was found.
311 For #include_next. */
312 struct file_name_list *dir;
313 int lineno;
314 int length;
315 U_CHAR *buf;
316 U_CHAR *bufp;
317 /* Macro that this level is the expansion of.
318 Included so that we can reenable the macro
319 at the end of this level. */
320 struct hashnode *macro;
321 /* Value of if_stack at start of this file.
322 Used to prohibit unmatched #endif (etc) in an include file. */
323 struct if_stack *if_stack;
324 /* Object to be freed at end of input at this level. */
325 U_CHAR *free_ptr;
326 /* True if this is a system header file; see is_system_include. */
327 char system_header_p;
328 } instack[INPUT_STACK_MAX];
330 static int last_error_tick; /* Incremented each time we print it. */
331 static int input_file_stack_tick; /* Incremented when the status changes. */
333 /* Current nesting level of input sources.
334 `instack[indepth]' is the level currently being read. */
335 static int indepth = -1;
336 #define CHECK_DEPTH(code) \
337 if (indepth >= (INPUT_STACK_MAX - 1)) \
339 error_with_line (line_for_error (instack[indepth].lineno), \
340 "macro or `#include' recursion too deep"); \
341 code; \
344 /* Current depth in #include directives that use <...>. */
345 static int system_include_depth = 0;
347 typedef struct file_buf FILE_BUF;
349 /* The output buffer. Its LENGTH field is the amount of room allocated
350 for the buffer, not the number of chars actually present. To get
351 that, subtract outbuf.buf from outbuf.bufp. */
353 #define OUTBUF_SIZE 10 /* initial size of output buffer */
354 static FILE_BUF outbuf;
356 /* Grow output buffer OBUF points at
357 so it can hold at least NEEDED more chars. */
359 #define check_expand(OBUF, NEEDED) \
360 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
361 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
363 struct file_name_list
365 struct file_name_list *next;
366 /* If the following is 1, it is a C-language system include
367 directory. */
368 int c_system_include_path;
369 /* Mapping of file names for this directory. */
370 struct file_name_map *name_map;
371 /* Non-zero if name_map is valid. */
372 int got_name_map;
373 /* The include directory status. */
374 struct stat st;
375 /* The include prefix: "" denotes the working directory,
376 otherwise fname must end in '/'.
377 The actual size is dynamically allocated. */
378 char fname[1];
381 /* #include "file" looks in source file dir, then stack. */
382 /* #include <file> just looks in the stack. */
383 /* -I directories are added to the end, then the defaults are added. */
384 /* The */
385 static struct default_include {
386 char *fname; /* The name of the directory. */
387 char *component; /* The component containing the directory */
388 int cplusplus; /* Only look here if we're compiling C++. */
389 int cxx_aware; /* Includes in this directory don't need to
390 be wrapped in extern "C" when compiling
391 C++. */
392 int included; /* Set if the directory is acceptable. */
393 } include_defaults_array[]
394 #ifdef INCLUDE_DEFAULTS
395 = INCLUDE_DEFAULTS;
396 #else
398 /* Pick up GNU C++ specific include files. */
399 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1, 0 },
400 #ifdef CROSS_COMPILE
401 /* This is the dir for fixincludes. Put it just before
402 the files that we fix. */
403 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
404 /* For cross-compilation, this dir name is generated
405 automatically in Makefile.in. */
406 { CROSS_INCLUDE_DIR, "GCC", 0, 0, 0 },
407 #ifdef TOOL_INCLUDE_DIR
408 /* This is another place that the target system's headers might be. */
409 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
410 #endif
411 #else /* not CROSS_COMPILE */
412 #ifdef LOCAL_INCLUDE_DIR
413 /* This should be /usr/local/include and should come before
414 the fixincludes-fixed header files. */
415 { LOCAL_INCLUDE_DIR, 0, 0, 1, 0 },
416 #endif
417 #ifdef TOOL_INCLUDE_DIR
418 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
419 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
420 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
421 #endif
422 /* This is the dir for fixincludes. Put it just before
423 the files that we fix. */
424 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
425 /* Some systems have an extra dir of include files. */
426 #ifdef SYSTEM_INCLUDE_DIR
427 { SYSTEM_INCLUDE_DIR, 0, 0, 0, 0 },
428 #endif
429 #ifndef STANDARD_INCLUDE_COMPONENT
430 #define STANDARD_INCLUDE_COMPONENT 0
431 #endif
432 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0, 0 },
433 #endif /* not CROSS_COMPILE */
434 { 0, 0, 0, 0, 0 }
436 #endif /* no INCLUDE_DEFAULTS */
438 /* The code looks at the defaults through this pointer, rather than through
439 the constant structure above. This pointer gets changed if an environment
440 variable specifies other defaults. */
441 static struct default_include *include_defaults = include_defaults_array;
443 static struct file_name_list *include = 0; /* First dir to search */
444 /* First dir to search for <file> */
445 /* This is the first element to use for #include <...>.
446 If it is 0, use the entire chain for such includes. */
447 static struct file_name_list *first_bracket_include = 0;
448 /* This is the first element in the chain that corresponds to
449 a directory of system header files. */
450 static struct file_name_list *first_system_include = 0;
451 static struct file_name_list *last_include = 0; /* Last in chain */
453 /* Chain of include directories to put at the end of the other chain. */
454 static struct file_name_list *after_include = 0;
455 static struct file_name_list *last_after_include = 0; /* Last in chain */
457 /* Chain to put at the start of the system include files. */
458 static struct file_name_list *before_system = 0;
459 static struct file_name_list *last_before_system = 0; /* Last in chain */
461 /* Directory prefix that should replace `/usr' in the standard
462 include file directories. */
463 static char *include_prefix;
465 /* Maintain and search list of included files. */
467 struct include_file {
468 struct include_file *next; /* for include_hashtab */
469 struct include_file *next_ino; /* for include_ino_hashtab */
470 char *fname;
471 /* If the following is the empty string, it means #pragma once
472 was seen in this include file, or #import was applied to the file.
473 Otherwise, if it is nonzero, it is a macro name.
474 Don't include the file again if that macro is defined. */
475 U_CHAR *control_macro;
476 /* Nonzero if the dependency on this include file has been output. */
477 int deps_output;
478 struct stat st;
481 /* Hash tables of files already included with #include or #import.
482 include_hashtab is by full name; include_ino_hashtab is by inode number. */
484 #define INCLUDE_HASHSIZE 61
485 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
486 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
488 /* Global list of strings read in from precompiled files. This list
489 is kept in the order the strings are read in, with new strings being
490 added at the end through stringlist_tailp. We use this list to output
491 the strings at the end of the run.
493 static STRINGDEF *stringlist;
494 static STRINGDEF **stringlist_tailp = &stringlist;
497 /* Structure returned by create_definition */
498 typedef struct macrodef MACRODEF;
499 struct macrodef
501 struct definition *defn;
502 U_CHAR *symnam;
503 int symlen;
506 enum sharp_token_type {
507 NO_SHARP_TOKEN = 0, /* token not present */
509 SHARP_TOKEN = '#', /* token spelled with # only */
510 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
512 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
513 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
516 /* Structure allocated for every #define. For a simple replacement
517 such as
518 #define foo bar ,
519 nargs = -1, the `pattern' list is null, and the expansion is just
520 the replacement text. Nargs = 0 means a functionlike macro with no args,
521 e.g.,
522 #define getchar() getc (stdin) .
523 When there are args, the expansion is the replacement text with the
524 args squashed out, and the reflist is a list describing how to
525 build the output from the input: e.g., "3 chars, then the 1st arg,
526 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
527 The chars here come from the expansion. Whatever is left of the
528 expansion after the last arg-occurrence is copied after that arg.
529 Note that the reflist can be arbitrarily long---
530 its length depends on the number of times the arguments appear in
531 the replacement text, not how many args there are. Example:
532 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
533 pattern list
534 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
535 where (x, y) means (nchars, argno). */
537 typedef struct definition DEFINITION;
538 struct definition {
539 int nargs;
540 int length; /* length of expansion string */
541 int predefined; /* True if the macro was builtin or */
542 /* came from the command line */
543 U_CHAR *expansion;
544 int line; /* Line number of definition */
545 char *file; /* File of definition */
546 size_t file_len; /* Length of file (which can contain NULs) */
547 char rest_args; /* Nonzero if last arg. absorbs the rest */
548 struct reflist {
549 struct reflist *next;
551 enum sharp_token_type stringify; /* set if a # operator before arg */
552 enum sharp_token_type raw_before; /* set if a ## operator before arg */
553 enum sharp_token_type raw_after; /* set if a ## operator after arg */
555 char rest_args; /* Nonzero if this arg. absorbs the rest */
556 int nchars; /* Number of literal chars to copy before
557 this arg occurrence. */
558 int argno; /* Number of arg to substitute (origin-0) */
559 } *pattern;
560 union {
561 /* Names of macro args, concatenated in reverse order
562 with comma-space between them.
563 The only use of this is that we warn on redefinition
564 if this differs between the old and new definitions. */
565 U_CHAR *argnames;
566 } args;
569 /* different kinds of things that can appear in the value field
570 of a hash node. Actually, this may be useless now. */
571 union hashval {
572 char *cpval;
573 DEFINITION *defn;
574 KEYDEF *keydef;
578 * special extension string that can be added to the last macro argument to
579 * allow it to absorb the "rest" of the arguments when expanded. Ex:
580 * #define wow(a, b...) process (b, a, b)
581 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
582 * { wow (one, two); } -> { process (two, one, two); }
583 * if this "rest_arg" is used with the concat token '##' and if it is not
584 * supplied then the token attached to with ## will not be outputted. Ex:
585 * #define wow (a, b...) process (b ## , a, ## b)
586 * { wow (1, 2); } -> { process (2, 1, 2); }
587 * { wow (one); } -> { process (one); {
589 static char rest_extension[] = "...";
590 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
592 /* This is the implicit parameter name when using variable number of
593 parameters for macros using the ISO C 9x extension. */
594 static char va_args_name[] = "__VA_ARGS__";
595 #define VA_ARGS_NAME_LENGTH (sizeof (va_args_name) - 1)
597 /* The structure of a node in the hash table. The hash table
598 has entries for all tokens defined by #define directives (type T_MACRO),
599 plus some special tokens like __LINE__ (these each have their own
600 type, and the appropriate code is run when that type of node is seen.
601 It does not contain control words like "#define", which are recognized
602 by a separate piece of code. */
604 /* different flavors of hash nodes --- also used in keyword table */
605 enum node_type {
606 T_DEFINE = 1, /* the `#define' keyword */
607 T_INCLUDE, /* the `#include' keyword */
608 T_INCLUDE_NEXT, /* the `#include_next' keyword */
609 T_IMPORT, /* the `#import' keyword */
610 T_IFDEF, /* the `#ifdef' keyword */
611 T_IFNDEF, /* the `#ifndef' keyword */
612 T_IF, /* the `#if' keyword */
613 T_ELSE, /* `#else' */
614 T_PRAGMA, /* `#pragma' */
615 T_ELIF, /* `#elif' */
616 T_UNDEF, /* `#undef' */
617 T_LINE, /* `#line' */
618 T_ERROR, /* `#error' */
619 T_WARNING, /* `#warning' */
620 T_ENDIF, /* `#endif' */
621 T_SCCS, /* `#sccs', used on system V. */
622 T_IDENT, /* `#ident', used on system V. */
623 T_ASSERT, /* `#assert', taken from system V. */
624 T_UNASSERT, /* `#unassert', taken from system V. */
625 T_SPECLINE, /* special symbol `__LINE__' */
626 T_DATE, /* `__DATE__' */
627 T_FILE, /* `__FILE__' */
628 T_BASE_FILE, /* `__BASE_FILE__' */
629 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
630 T_VERSION, /* `__VERSION__' */
631 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
632 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
633 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
634 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
635 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
636 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
637 T_TIME, /* `__TIME__' */
638 T_CONST, /* Constant value, used by `__STDC__' */
639 T_MACRO, /* macro defined by `#define' */
640 T_DISABLED, /* macro temporarily turned off for rescan */
641 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
642 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
643 T_POISON, /* defined with `#pragma poison' */
644 T_UNUSED /* Used for something not defined. */
647 struct hashnode {
648 struct hashnode *next; /* double links for easy deletion */
649 struct hashnode *prev;
650 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
651 chain is kept, in case the node is the head
652 of the chain and gets deleted. */
653 enum node_type type; /* type of special token */
654 int length; /* length of token, for quick comparison */
655 U_CHAR *name; /* the actual name */
656 union hashval value; /* pointer to expansion, or whatever */
659 typedef struct hashnode HASHNODE;
661 /* Some definitions for the hash table. The hash function MUST be
662 computed as shown in hashf () below. That is because the rescan
663 loop computes the hash value `on the fly' for most tokens,
664 in order to avoid the overhead of a lot of procedure calls to
665 the hashf () function. Hashf () only exists for the sake of
666 politeness, for use when speed isn't so important. */
668 #define HASHSIZE 1403
669 static HASHNODE *hashtab[HASHSIZE];
670 #define HASHSTEP(old, c) ((old << 2) + c)
671 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
674 /* We let tm.h override the types used here, to handle trivial differences
675 such as the choice of unsigned int or long unsigned int for size_t.
676 When machines start needing nontrivial differences in the size type,
677 it would be best to do something here to figure out automatically
678 from other information what type to use. */
680 /* The string value for __SIZE_TYPE__. */
682 #ifndef SIZE_TYPE
683 #define SIZE_TYPE "long unsigned int"
684 #endif
686 /* The string value for __PTRDIFF_TYPE__. */
688 #ifndef PTRDIFF_TYPE
689 #define PTRDIFF_TYPE "long int"
690 #endif
692 /* The string value for __WCHAR_TYPE__. */
694 #ifndef WCHAR_TYPE
695 #define WCHAR_TYPE "int"
696 #endif
697 char * wchar_type = WCHAR_TYPE;
698 #undef WCHAR_TYPE
700 /* The string value for __USER_LABEL_PREFIX__ */
702 #ifndef USER_LABEL_PREFIX
703 #define USER_LABEL_PREFIX ""
704 #endif
705 char * user_label_prefix = USER_LABEL_PREFIX;
706 #undef USER_LABEL_PREFIX
708 /* The string value for __REGISTER_PREFIX__ */
710 #ifndef REGISTER_PREFIX
711 #define REGISTER_PREFIX ""
712 #endif
714 /* The string value for __IMMEDIATE_PREFIX__ */
716 #ifndef IMMEDIATE_PREFIX
717 #define IMMEDIATE_PREFIX ""
718 #endif
720 /* In the definition of a #assert name, this structure forms
721 a list of the individual values asserted.
722 Each value is itself a list of "tokens".
723 These are strings that are compared by name. */
725 struct tokenlist_list {
726 struct tokenlist_list *next;
727 struct arglist *tokens;
730 struct assertion_hashnode {
731 struct assertion_hashnode *next; /* double links for easy deletion */
732 struct assertion_hashnode *prev;
733 /* also, a back pointer to this node's hash
734 chain is kept, in case the node is the head
735 of the chain and gets deleted. */
736 struct assertion_hashnode **bucket_hdr;
737 int length; /* length of token, for quick comparison */
738 U_CHAR *name; /* the actual name */
739 /* List of token-sequences. */
740 struct tokenlist_list *value;
743 typedef struct assertion_hashnode ASSERTION_HASHNODE;
745 /* Some definitions for the hash table. The hash function MUST be
746 computed as shown in hashf below. That is because the rescan
747 loop computes the hash value `on the fly' for most tokens,
748 in order to avoid the overhead of a lot of procedure calls to
749 the hashf function. hashf only exists for the sake of
750 politeness, for use when speed isn't so important. */
752 #define ASSERTION_HASHSIZE 37
753 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
755 /* Nonzero means inhibit macroexpansion of what seem to be
756 assertion tests, in rescan. For #if. */
757 static int assertions_flag;
759 /* `struct directive' defines one #-directive, including how to handle it. */
761 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
763 struct directive {
764 int length; /* Length of name */
765 int (*func) DO_PROTO; /* Function to handle directive */
766 char *name; /* Name of directive */
767 enum node_type type; /* Code which describes which directive. */
770 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
771 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
773 /* These functions are declared to return int instead of void since they
774 are going to be placed in the table and some old compilers have trouble with
775 pointers to functions returning void. */
777 static int do_assert DO_PROTO;
778 static int do_define DO_PROTO;
779 static int do_elif DO_PROTO;
780 static int do_else DO_PROTO;
781 static int do_endif DO_PROTO;
782 static int do_error DO_PROTO;
783 static int do_ident DO_PROTO;
784 static int do_if DO_PROTO;
785 static int do_include DO_PROTO;
786 static int do_line DO_PROTO;
787 static int do_pragma DO_PROTO;
788 #ifdef SCCS_DIRECTIVE
789 static int do_sccs DO_PROTO;
790 #endif
791 static int do_unassert DO_PROTO;
792 static int do_undef DO_PROTO;
793 static int do_xifdef DO_PROTO;
795 /* Here is the actual list of #-directives, most-often-used first. */
797 static struct directive directive_table[] = {
798 { 6, do_define, "define", T_DEFINE},
799 { 2, do_if, "if", T_IF},
800 { 5, do_xifdef, "ifdef", T_IFDEF},
801 { 6, do_xifdef, "ifndef", T_IFNDEF},
802 { 5, do_endif, "endif", T_ENDIF},
803 { 4, do_else, "else", T_ELSE},
804 { 4, do_elif, "elif", T_ELIF},
805 { 4, do_line, "line", T_LINE},
806 { 7, do_include, "include", T_INCLUDE},
807 { 12, do_include, "include_next", T_INCLUDE_NEXT},
808 { 6, do_include, "import", T_IMPORT},
809 { 5, do_undef, "undef", T_UNDEF},
810 { 5, do_error, "error", T_ERROR},
811 { 7, do_error, "warning", T_WARNING},
812 #ifdef SCCS_DIRECTIVE
813 { 4, do_sccs, "sccs", T_SCCS},
814 #endif
815 { 6, do_pragma, "pragma", T_PRAGMA},
816 { 5, do_ident, "ident", T_IDENT},
817 { 6, do_assert, "assert", T_ASSERT},
818 { 8, do_unassert, "unassert", T_UNASSERT},
819 { -1, 0, "", T_UNUSED},
822 /* When a directive handler is called,
823 this points to the # (or the : of the %:) that started the directive. */
824 U_CHAR *directive_start;
826 /* table to tell if char can be part of a C identifier. */
827 U_CHAR is_idchar[256];
828 /* table to tell if char can be first char of a c identifier. */
829 U_CHAR is_idstart[256];
830 /* table to tell if c is horizontal space. */
831 static U_CHAR is_hor_space[256];
832 /* table to tell if c is horizontal or vertical space. */
833 U_CHAR is_space[256];
835 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
836 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
838 static int errors = 0; /* Error counter for exit code */
840 /* Name of output file, for error messages. */
841 static char *out_fname;
843 /* Nonzero to ignore \ in string constants. Use to treat #line 1 "A:\file.h
844 as a non-form feed. If you want it to be a form feed, you must use
845 # 1 "\f". */
846 static int ignore_escape_flag = 1;
848 /* Stack of conditionals currently in progress
849 (including both successful and failing conditionals). */
851 struct if_stack {
852 struct if_stack *next; /* for chaining to the next stack frame */
853 char *fname; /* copied from input when frame is made */
854 size_t fname_len; /* similarly */
855 int lineno; /* similarly */
856 int if_succeeded; /* true if a leg of this if-group
857 has been passed through rescan */
858 U_CHAR *control_macro; /* For #ifndef at start of file,
859 this is the macro name tested. */
860 enum node_type type; /* type of last directive seen in this group */
862 typedef struct if_stack IF_STACK_FRAME;
863 static IF_STACK_FRAME *if_stack = NULL;
865 /* Buffer of -M output. */
866 static char *deps_buffer;
868 /* Number of bytes allocated in above. */
869 static int deps_allocated_size;
871 /* Number of bytes used. */
872 static int deps_size;
874 /* Number of bytes since the last newline. */
875 static int deps_column;
877 /* Nonzero means -I- has been seen,
878 so don't look for #include "foo" the source-file directory. */
879 static int ignore_srcdir;
881 static int safe_read PROTO((int, char *, int));
882 static void safe_write PROTO((int, char *, int));
884 int main PROTO((int, char **));
886 static void path_include PROTO((char *));
888 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
890 static void trigraph_pcp PROTO((FILE_BUF *));
891 static void check_white_space PROTO((FILE_BUF *));
893 static void newline_fix PROTO((U_CHAR *));
894 static void name_newline_fix PROTO((U_CHAR *));
896 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
898 static void rescan PROTO((FILE_BUF *, int));
900 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
902 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
904 static struct tm *timestamp PROTO((void));
905 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
907 static int is_system_include PROTO((char *));
908 static char *base_name PROTO((char *));
909 static int absolute_filename PROTO((char *));
910 static size_t simplify_filename PROTO((char *));
912 static char *read_filename_string PROTO((int, FILE *));
913 static struct file_name_map *read_name_map PROTO((char *));
914 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
915 static char *remap_include_file PROTO((char *, struct file_name_list *));
916 static int lookup_ino_include PROTO((struct include_file *));
918 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
919 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
921 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
922 static int check_preconditions PROTO((char *));
923 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
924 static void pcstring_used PROTO((HASHNODE *));
925 static void write_output PROTO((void));
926 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
928 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
930 static int check_macro_name PROTO((U_CHAR *, int));
931 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
932 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
934 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
936 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
937 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
939 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
940 static void free_token_list PROTO((struct arglist *));
942 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
943 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
944 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
946 static void do_once PROTO((void));
948 static HOST_WIDEST_INT eval_if_expression PROTO((U_CHAR *, int));
949 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
950 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
951 static void validate_else PROTO((U_CHAR *, U_CHAR *));
953 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
954 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
955 static char *quote_string PROTO((char *, char *, size_t));
956 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
958 /* Last arg to output_line_directive. */
959 enum file_change_code {same_file, enter_file, leave_file};
960 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
962 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
964 struct argdata;
965 static int macarg PROTO((struct argdata *, int));
967 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
969 static int discard_comments PROTO((U_CHAR *, int, int));
971 static void change_newlines PROTO((struct argdata *));
973 static void notice PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
974 static void vnotice PROTO((const char *, va_list));
975 void error PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
976 void verror PROTO((const char *, va_list));
977 static void error_from_errno PROTO((char *));
978 void warning PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
979 static void vwarning PROTO((const char *, va_list));
980 static void error_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
981 static void verror_with_line PROTO((int, const char *, va_list));
982 static void vwarning_with_line PROTO((int, const char *, va_list));
983 static void warning_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
984 void pedwarn PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
985 void pedwarn_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
986 static void pedwarn_with_file_and_line PVPROTO((const char *, size_t, int, const char *, ...)) ATTRIBUTE_PRINTF_4;
987 static void pedwarn_strange_white_space PROTO((int));
989 static void print_containing_files PROTO((void));
991 static int line_for_error PROTO((int));
992 static int grow_outbuf PROTO((FILE_BUF *, int));
994 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
995 HASHNODE *lookup PROTO((U_CHAR *, int, int));
996 static void delete_macro PROTO((HASHNODE *));
997 static int hashf PROTO((U_CHAR *, int, int));
999 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1000 static void dump_all_macros PROTO((void));
1001 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1002 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1004 static void initialize_char_syntax PROTO((void));
1005 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1007 static void make_definition PROTO((char *));
1008 static void make_undef PROTO((char *, FILE_BUF *));
1010 static void make_assertion PROTO((const char *, const char *));
1012 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, const char *, const char *, const char *));
1013 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1015 static int quote_string_for_make PROTO((char *, const char *));
1016 static void deps_output PROTO((const char *, int));
1018 void fatal PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
1019 void fancy_abort PROTO((void)) ATTRIBUTE_NORETURN;
1020 static void perror_with_name PROTO((char *));
1021 static void pfatal_with_name PROTO((char *)) ATTRIBUTE_NORETURN;
1022 static void pipe_closed PROTO((int)) ATTRIBUTE_NORETURN;
1024 static void memory_full PROTO((void)) ATTRIBUTE_NORETURN;
1025 static void print_help PROTO((void));
1027 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1028 retrying if necessary. If MAX_READ_LEN is defined, read at most
1029 that bytes at a time. Return a negative value if an error occurs,
1030 otherwise return the actual number of bytes read,
1031 which must be LEN unless end-of-file was reached. */
1033 static int
1034 safe_read (desc, ptr, len)
1035 int desc;
1036 char *ptr;
1037 int len;
1039 int left, rcount, nchars;
1041 left = len;
1042 while (left > 0) {
1043 rcount = left;
1044 #ifdef MAX_READ_LEN
1045 if (rcount > MAX_READ_LEN)
1046 rcount = MAX_READ_LEN;
1047 #endif
1048 nchars = read (desc, ptr, rcount);
1049 if (nchars < 0)
1051 #ifdef EINTR
1052 if (errno == EINTR)
1053 continue;
1054 #endif
1055 return nchars;
1057 if (nchars == 0)
1058 break;
1059 ptr += nchars;
1060 left -= nchars;
1062 return len - left;
1065 /* Write LEN bytes at PTR to descriptor DESC,
1066 retrying if necessary, and treating any real error as fatal.
1067 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1069 static void
1070 safe_write (desc, ptr, len)
1071 int desc;
1072 char *ptr;
1073 int len;
1075 int wcount, written;
1077 while (len > 0) {
1078 wcount = len;
1079 #ifdef MAX_WRITE_LEN
1080 if (wcount > MAX_WRITE_LEN)
1081 wcount = MAX_WRITE_LEN;
1082 #endif
1083 written = write (desc, ptr, wcount);
1084 if (written < 0)
1086 #ifdef EINTR
1087 if (errno == EINTR)
1088 continue;
1089 #endif
1090 pfatal_with_name (out_fname);
1092 ptr += written;
1093 len -= written;
1098 static void
1099 print_help ()
1101 printf ("Usage: %s [switches] input output\n", progname);
1102 printf ("Switches:\n");
1103 printf (" -include <file> Include the contents of <file> before other files\n");
1104 printf (" -imacros <file> Accept definition of macros in <file>\n");
1105 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
1106 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
1107 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
1108 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
1109 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
1110 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
1111 printf (" -nostdinc Do not search the system include directories\n");
1112 printf (" -nostdinc++ Do not search the system include directories for C++\n");
1113 printf (" -o <file> Put output into <file>\n");
1114 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
1115 printf (" -traditional Follow K&R pre-processor behaviour\n");
1116 printf (" -trigraphs Support ANSI C trigraphs\n");
1117 printf (" -lang-c Assume that the input sources are in C\n");
1118 printf (" -lang-c89 Assume that the input is C89; depricated\n");
1119 printf (" -lang-c++ Assume that the input sources are in C++\n");
1120 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
1121 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
1122 printf (" -lang-asm Assume that the input sources are in assembler\n");
1123 printf (" -lang-chill Assume that the input sources are in Chill\n");
1124 printf (" -std=<std name> Specify the conformance standard; one of:\n");
1125 printf (" gnu89, gnu9x, c89, c9x, iso9899:1990,\n");
1126 printf (" iso9899:199409, iso9899:199x\n");
1127 printf (" -+ Allow parsing of C++ style features\n");
1128 printf (" -w Inhibit warning messages\n");
1129 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
1130 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
1131 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
1132 printf (" -Wno-comment{s} Do not warn about comments\n");
1133 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
1134 printf (" a string if -traditional is specified\n");
1135 printf (" -Wno-traditional Do not warn about stringification\n");
1136 printf (" -Wundef Warn if an undefined macro is used by #if\n");
1137 printf (" -Wno-undef Do not warn about testing undefined macros\n");
1138 printf (" -Wimport Warn about the use of the #import directive\n");
1139 printf (" -Wno-import Do not warn about the use of #import\n");
1140 printf (" -Werror Treat all warnings as errors\n");
1141 printf (" -Wno-error Do not treat warnings as errors\n");
1142 printf (" -Wall Enable all preprocessor warnings\n");
1143 printf (" -M Generate make dependencies\n");
1144 printf (" -MM As -M, but ignore system header files\n");
1145 printf (" -MD As -M, but put output in a .d file\n");
1146 printf (" -MMD As -MD, but ignore system header files\n");
1147 printf (" -MG Treat missing header file as generated files\n");
1148 printf (" -g Include #define and #undef directives in the output\n");
1149 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
1150 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
1151 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
1152 printf (" -U<macro> Undefine <macro> \n");
1153 printf (" -u or -undef Do not predefine any macros\n");
1154 printf (" -v Display the version number\n");
1155 printf (" -H Print the name of header files as they are used\n");
1156 printf (" -C Do not discard comments\n");
1157 printf (" -dM Display a list of macro definitions active at end\n");
1158 printf (" -dD Preserve macro definitions in output\n");
1159 printf (" -dN As -dD except that only the names are preserved\n");
1160 printf (" -dI Include #include directives in the output\n");
1161 printf (" -ifoutput Describe skipped code blocks in output \n");
1162 printf (" -P Do not generate #line directives\n");
1163 printf (" -$ Do not include '$' in identifiers\n");
1164 printf (" -remap Remap file names when including files.\n");
1165 printf (" -h or --help Display this information\n");
1169 main (argc, argv)
1170 int argc;
1171 char **argv;
1173 struct stat st;
1174 char *in_fname;
1175 char *cp;
1176 int f, i;
1177 FILE_BUF *fp;
1179 char **pend_files;
1180 char **pend_defs;
1181 char **pend_undefs;
1182 char **pend_assertions;
1183 char **pend_includes;
1185 /* Record the option used with each element of pend_assertions.
1186 This is preparation for supporting more than one option for making
1187 an assertion. */
1188 char **pend_assertion_options;
1189 int no_standard_includes = 0;
1190 int no_standard_cplusplus_includes = 0;
1191 int missing_newline = 0;
1193 /* Non-0 means don't output the preprocessed program. */
1194 int inhibit_output = 0;
1195 /* Non-0 means -v, so print the full set of include dirs. */
1196 int verbose = 0;
1198 /* File name which deps are being written to.
1199 This is 0 if deps are being written to stdout. */
1200 char *deps_file = 0;
1201 /* Fopen file mode to open deps_file with. */
1202 char *deps_mode = "a";
1203 /* Stream on which to print the dependency information. */
1204 FILE *deps_stream = 0;
1205 /* Target-name to write with the dependency information. */
1206 char *deps_target = 0;
1208 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1209 /* Get rid of any avoidable limit on stack size. */
1211 struct rlimit rlim;
1213 /* Set the stack limit huge so that alloca (particularly stringtab
1214 in dbxread.c) does not fail. */
1215 getrlimit (RLIMIT_STACK, &rlim);
1216 rlim.rlim_cur = rlim.rlim_max;
1217 setrlimit (RLIMIT_STACK, &rlim);
1219 #endif
1221 #ifdef SIGPIPE
1222 signal (SIGPIPE, pipe_closed);
1223 #endif
1225 #ifdef HAVE_LC_MESSAGES
1226 setlocale (LC_MESSAGES, "");
1227 #endif
1228 (void) bindtextdomain (PACKAGE, localedir);
1229 (void) textdomain (PACKAGE);
1231 progname = base_name (argv[0]);
1233 #ifdef VMS
1235 /* Remove extension from PROGNAME. */
1236 char *p;
1237 char *s = progname = xstrdup (progname);
1239 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1240 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1241 && (p[1] == 'e' || p[1] == 'E')
1242 && (p[2] == 'x' || p[2] == 'X')
1243 && (p[3] == 'e' || p[3] == 'E')
1244 && !p[4])
1245 *p = '\0';
1247 #endif
1249 /* Do not invoke xmalloc before this point, since locale and
1250 progname need to be set first, in case a diagnostic is issued. */
1252 pend_files = (char **) xmalloc (argc * sizeof (char *));
1253 pend_defs = (char **) xmalloc (argc * sizeof (char *));
1254 pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1255 pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1256 pend_includes = (char **) xmalloc (argc * sizeof (char *));
1257 pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1259 in_fname = NULL;
1260 out_fname = NULL;
1262 /* Initialize is_idchar. */
1263 initialize_char_syntax ();
1265 no_line_directives = 0;
1266 no_trigraphs = 1;
1267 dump_macros = dump_none;
1268 no_output = 0;
1269 cplusplus = 0;
1270 cplusplus_comments = 1;
1272 bzero ((char *) pend_files, argc * sizeof (char *));
1273 bzero ((char *) pend_defs, argc * sizeof (char *));
1274 bzero ((char *) pend_undefs, argc * sizeof (char *));
1275 bzero ((char *) pend_assertions, argc * sizeof (char *));
1276 bzero ((char *) pend_includes, argc * sizeof (char *));
1278 #ifdef MULTIBYTE_CHARS
1279 /* Change to the native locale for multibyte conversions. */
1280 setlocale (LC_CTYPE, "");
1281 literal_codeset = getenv ("LANG");
1282 #endif
1284 /* Process switches and find input file name. */
1286 for (i = 1; i < argc; i++) {
1287 if (argv[i][0] != '-') {
1288 if (out_fname != NULL)
1290 print_help ();
1291 fatal ("Too many arguments");
1293 else if (in_fname != NULL)
1294 out_fname = argv[i];
1295 else
1296 in_fname = argv[i];
1297 } else {
1298 switch (argv[i][1]) {
1300 case 'i':
1301 if (!strcmp (argv[i], "-include")) {
1302 if (i + 1 == argc)
1303 fatal ("Filename missing after `-include' option");
1304 else {
1305 i++;
1306 simplify_filename (pend_includes[i] = argv[i]);
1309 if (!strcmp (argv[i], "-imacros")) {
1310 if (i + 1 == argc)
1311 fatal ("Filename missing after `-imacros' option");
1312 else {
1313 i++;
1314 simplify_filename (pend_files[i] = argv[i]);
1317 if (!strcmp (argv[i], "-iprefix")) {
1318 if (i + 1 == argc)
1319 fatal ("Filename missing after `-iprefix' option");
1320 else
1321 include_prefix = argv[++i];
1323 if (!strcmp (argv[i], "-ifoutput")) {
1324 output_conditionals = 1;
1326 if (!strcmp (argv[i], "-isystem")) {
1327 struct file_name_list *dirtmp;
1329 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1330 "", argv[++i])))
1331 break;
1332 dirtmp->c_system_include_path = 1;
1334 if (before_system == 0)
1335 before_system = dirtmp;
1336 else
1337 last_before_system->next = dirtmp;
1338 last_before_system = dirtmp; /* Tail follows the last one */
1340 /* Add directory to end of path for includes,
1341 with the default prefix at the front of its name. */
1342 if (!strcmp (argv[i], "-iwithprefix")) {
1343 struct file_name_list *dirtmp;
1344 char *prefix;
1346 if (include_prefix != 0)
1347 prefix = include_prefix;
1348 else {
1349 prefix = xstrdup (GCC_INCLUDE_DIR);
1350 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1351 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1352 prefix[strlen (prefix) - 7] = 0;
1355 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1356 prefix, argv[++i])))
1357 break;
1359 if (after_include == 0)
1360 after_include = dirtmp;
1361 else
1362 last_after_include->next = dirtmp;
1363 last_after_include = dirtmp; /* Tail follows the last one */
1365 /* Add directory to main path for includes,
1366 with the default prefix at the front of its name. */
1367 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1368 struct file_name_list *dirtmp;
1369 char *prefix;
1371 if (include_prefix != 0)
1372 prefix = include_prefix;
1373 else {
1374 prefix = xstrdup (GCC_INCLUDE_DIR);
1375 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1376 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1377 prefix[strlen (prefix) - 7] = 0;
1380 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1381 append_include_chain (dirtmp, dirtmp);
1383 /* Add directory to end of path for includes. */
1384 if (!strcmp (argv[i], "-idirafter")) {
1385 struct file_name_list *dirtmp;
1387 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1388 "", argv[++i])))
1389 break;
1391 if (after_include == 0)
1392 after_include = dirtmp;
1393 else
1394 last_after_include->next = dirtmp;
1395 last_after_include = dirtmp; /* Tail follows the last one */
1397 break;
1399 case 'o':
1400 if (out_fname != NULL)
1401 fatal ("Output filename specified twice");
1402 if (i + 1 == argc)
1403 fatal ("Filename missing after -o option");
1404 out_fname = argv[++i];
1405 if (!strcmp (out_fname, "-"))
1406 out_fname = "";
1407 break;
1409 case 'p':
1410 if (!strcmp (argv[i], "-pedantic"))
1411 pedantic = 1;
1412 else if (!strcmp (argv[i], "-pedantic-errors")) {
1413 pedantic = 1;
1414 pedantic_errors = 1;
1415 } else if (!strcmp (argv[i], "-pcp")) {
1416 char *pcp_fname;
1417 if (i + 1 == argc)
1418 fatal ("Filename missing after -pcp option");
1419 pcp_fname = argv[++i];
1420 pcp_outfile
1421 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1422 ? fopen (pcp_fname, "w")
1423 : stdout);
1424 if (pcp_outfile == 0)
1425 pfatal_with_name (pcp_fname);
1426 no_precomp = 1;
1428 break;
1430 case 't':
1431 if (!strcmp (argv[i], "-traditional")) {
1432 traditional = 1;
1433 cplusplus_comments = 0;
1434 } else if (!strcmp (argv[i], "-trigraphs")) {
1435 no_trigraphs = 0;
1437 break;
1439 case 'l':
1440 if (! strcmp (argv[i], "-lang-c"))
1441 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1442 else if (! strcmp (argv[i], "-lang-c89"))
1443 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1444 else if (! strcmp (argv[i], "-lang-c++"))
1445 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 0;
1446 else if (! strcmp (argv[i], "-lang-objc"))
1447 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1448 else if (! strcmp (argv[i], "-lang-objc++"))
1449 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1450 else if (! strcmp (argv[i], "-lang-asm"))
1451 lang_asm = 1;
1452 else if (! strcmp (argv[i], "-lint"))
1453 for_lint = 1;
1454 break;
1456 case '+':
1457 cplusplus = 1, cplusplus_comments = 1;
1458 break;
1460 case 's':
1461 if (!strcmp (argv[i], "-std=iso9899:1990")
1462 || !strcmp (argv[i], "-std=iso9899:199409")
1463 || !strcmp (argv[i], "-std=c89")
1464 || !strcmp (argv[i], "-std=gnu89"))
1465 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1466 else if (!strcmp (argv[i], "-std=iso9899:199x")
1467 || !strcmp (argv[i], "-std=c9x")
1468 || !strcmp (argv[i], "-std=gnu9x"))
1469 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1470 break;
1472 case 'w':
1473 inhibit_warnings = 1;
1474 break;
1476 case 'W':
1477 if (!strcmp (argv[i], "-Wtrigraphs"))
1478 warn_trigraphs = 1;
1479 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1480 warn_trigraphs = 0;
1481 else if (!strcmp (argv[i], "-Wcomment"))
1482 warn_comments = 1;
1483 else if (!strcmp (argv[i], "-Wno-comment"))
1484 warn_comments = 0;
1485 else if (!strcmp (argv[i], "-Wcomments"))
1486 warn_comments = 1;
1487 else if (!strcmp (argv[i], "-Wno-comments"))
1488 warn_comments = 0;
1489 else if (!strcmp (argv[i], "-Wtraditional"))
1490 warn_stringify = 1;
1491 else if (!strcmp (argv[i], "-Wno-traditional"))
1492 warn_stringify = 0;
1493 else if (!strcmp (argv[i], "-Wwhite-space"))
1494 warn_white_space = 1;
1495 else if (!strcmp (argv[i], "-Wno-white-space"))
1496 warn_white_space = 0;
1497 else if (!strcmp (argv[i], "-Wundef"))
1498 warn_undef = 1;
1499 else if (!strcmp (argv[i], "-Wno-undef"))
1500 warn_undef = 0;
1501 else if (!strcmp (argv[i], "-Wimport"))
1502 warn_import = 1;
1503 else if (!strcmp (argv[i], "-Wno-import"))
1504 warn_import = 0;
1505 else if (!strcmp (argv[i], "-Werror"))
1506 warnings_are_errors = 1;
1507 else if (!strcmp (argv[i], "-Wno-error"))
1508 warnings_are_errors = 0;
1509 else if (!strcmp (argv[i], "-Wall"))
1511 warn_trigraphs = 1;
1512 warn_comments = 1;
1513 warn_white_space = 1;
1515 break;
1517 case 'f':
1518 if (!strcmp (argv[i], "-fleading-underscore"))
1519 user_label_prefix = "_";
1520 else if (!strcmp (argv[i], "-fno-leading-underscore"))
1521 user_label_prefix = "";
1522 break;
1524 case 'M':
1525 /* The style of the choices here is a bit mixed.
1526 The chosen scheme is a hybrid of keeping all options in one string
1527 and specifying each option in a separate argument:
1528 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1529 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1530 -M[M][G][D file]. This is awkward to handle in specs, and is not
1531 as extensible. */
1532 /* ??? -MG must be specified in addition to one of -M or -MM.
1533 This can be relaxed in the future without breaking anything.
1534 The converse isn't true. */
1536 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1537 if (!strcmp (argv[i], "-MG"))
1539 print_deps_missing_files = 1;
1540 break;
1542 if (!strcmp (argv[i], "-M"))
1543 print_deps = 2;
1544 else if (!strcmp (argv[i], "-MM"))
1545 print_deps = 1;
1546 else if (!strcmp (argv[i], "-MD"))
1547 print_deps = 2;
1548 else if (!strcmp (argv[i], "-MMD"))
1549 print_deps = 1;
1550 /* For -MD and -MMD options, write deps on file named by next arg. */
1551 if (!strcmp (argv[i], "-MD")
1552 || !strcmp (argv[i], "-MMD")) {
1553 if (i + 1 == argc)
1554 fatal ("Filename missing after %s option", argv[i]);
1555 i++;
1556 deps_file = argv[i];
1557 deps_mode = "w";
1558 } else {
1559 /* For -M and -MM, write deps on standard output
1560 and suppress the usual output. */
1561 deps_stream = stdout;
1562 inhibit_output = 1;
1564 break;
1566 case 'd':
1568 char *p = argv[i] + 2;
1569 char c;
1570 while ((c = *p++)) {
1571 /* Arg to -d specifies what parts of macros to dump */
1572 switch (c) {
1573 case 'M':
1574 dump_macros = dump_only;
1575 no_output = 1;
1576 break;
1577 case 'N':
1578 dump_macros = dump_names;
1579 break;
1580 case 'D':
1581 dump_macros = dump_definitions;
1582 break;
1583 case 'I':
1584 dump_includes = 1;
1585 break;
1589 break;
1591 case 'g':
1592 if (argv[i][2] == '3')
1593 debug_output = 1;
1594 break;
1596 case '-':
1597 if (strcmp (argv[i], "--help") != 0)
1598 return i;
1599 print_help ();
1600 exit (0);
1601 break;
1603 case 'v':
1604 notice ("GNU CPP version %s", version_string);
1605 #ifdef TARGET_VERSION
1606 TARGET_VERSION;
1607 #endif
1608 fprintf (stderr, "\n");
1609 verbose = 1;
1610 break;
1612 case 'H':
1613 print_include_names = 1;
1614 break;
1616 case 'D':
1617 if (argv[i][2] != 0)
1618 pend_defs[i] = argv[i] + 2;
1619 else if (i + 1 == argc)
1620 fatal ("Macro name missing after -D option");
1621 else
1622 i++, pend_defs[i] = argv[i];
1623 break;
1625 case 'A':
1627 char *p;
1629 if (argv[i][2] != 0)
1630 p = argv[i] + 2;
1631 else if (i + 1 == argc)
1632 fatal ("Assertion missing after -A option");
1633 else
1634 p = argv[++i];
1636 if (!strcmp (p, "-")) {
1637 /* -A- eliminates all predefined macros and assertions.
1638 Let's include also any that were specified earlier
1639 on the command line. That way we can get rid of any
1640 that were passed automatically in from GCC. */
1641 int j;
1642 for (j = 0; j < i; j++)
1643 pend_defs[j] = pend_assertions[j] = 0;
1644 } else {
1645 pend_assertions[i] = p;
1646 pend_assertion_options[i] = "-A";
1649 break;
1651 case 'U': /* JF #undef something */
1652 if (argv[i][2] != 0)
1653 pend_undefs[i] = argv[i] + 2;
1654 else if (i + 1 == argc)
1655 fatal ("Macro name missing after -U option");
1656 else
1657 pend_undefs[i] = argv[i+1], i++;
1658 break;
1660 case 'C':
1661 put_out_comments = 1;
1662 break;
1664 case 'E': /* -E comes from cc -E; ignore it. */
1665 break;
1667 case 'P':
1668 no_line_directives = 1;
1669 break;
1671 case '$': /* Don't include $ in identifiers. */
1672 is_idchar['$'] = is_idstart['$'] = 0;
1673 break;
1675 case 'I': /* Add directory to path for includes. */
1677 struct file_name_list *dirtmp;
1678 char *dir = argv[i][2] ? argv[i] + 2 : argv[++i];
1680 if (! ignore_srcdir && !strcmp (dir, "-")) {
1681 ignore_srcdir = 1;
1682 /* Don't use any preceding -I directories for #include <...>. */
1683 first_bracket_include = 0;
1685 else {
1686 dirtmp = new_include_prefix (last_include, NULL_PTR, "", dir);
1687 append_include_chain (dirtmp, dirtmp);
1690 break;
1692 case 'n':
1693 if (!strcmp (argv[i], "-nostdinc"))
1694 /* -nostdinc causes no default include directories.
1695 You must specify all include-file directories with -I. */
1696 no_standard_includes = 1;
1697 else if (!strcmp (argv[i], "-nostdinc++"))
1698 /* -nostdinc++ causes no default C++-specific include directories. */
1699 no_standard_cplusplus_includes = 1;
1700 else if (!strcmp (argv[i], "-noprecomp"))
1701 no_precomp = 1;
1702 break;
1704 case 'r':
1705 if (!strcmp (argv[i], "-remap"))
1706 remap = 1;
1707 break;
1709 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1710 if (in_fname == NULL) {
1711 in_fname = "";
1712 break;
1713 } else if (out_fname == NULL) {
1714 out_fname = "";
1715 break;
1716 } /* else fall through into error */
1718 default:
1719 fatal ("Invalid option `%s'", argv[i]);
1724 /* Add dirs from CPATH after dirs from -I. */
1725 /* There seems to be confusion about what CPATH should do,
1726 so for the moment it is not documented. */
1727 /* Some people say that CPATH should replace the standard include dirs,
1728 but that seems pointless: it comes before them, so it overrides them
1729 anyway. */
1730 GET_ENV_PATH_LIST (cp, "CPATH");
1731 if (cp && ! no_standard_includes)
1732 path_include (cp);
1734 /* Initialize output buffer */
1736 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1737 outbuf.bufp = outbuf.buf;
1738 outbuf.length = OUTBUF_SIZE;
1740 /* Do partial setup of input buffer for the sake of generating
1741 early #line directives (when -g is in effect). */
1743 fp = &instack[++indepth];
1744 if (in_fname == NULL)
1745 in_fname = "";
1746 fp->nominal_fname = fp->fname = in_fname;
1747 fp->nominal_fname_len = strlen (in_fname);
1748 fp->lineno = 0;
1750 /* In C++, wchar_t is a distinct basic type, and we can expect
1751 __wchar_t to be defined by cc1plus. */
1752 if (cplusplus)
1753 wchar_type = "__wchar_t";
1755 /* Install __LINE__, etc. Must follow initialize_char_syntax
1756 and option processing. */
1757 initialize_builtins (fp, &outbuf);
1759 /* Now handle the command line options. */
1761 /* Do -U's, -D's and -A's in the order they were seen. */
1762 for (i = 1; i < argc; i++) {
1763 if (pend_undefs[i]) {
1764 if (debug_output)
1765 output_line_directive (fp, &outbuf, 0, same_file);
1766 make_undef (pend_undefs[i], &outbuf);
1768 if (pend_defs[i]) {
1769 if (debug_output)
1770 output_line_directive (fp, &outbuf, 0, same_file);
1771 make_definition (pend_defs[i]);
1773 if (pend_assertions[i])
1774 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1777 done_initializing = 1;
1779 { /* Read the appropriate environment variable and if it exists
1780 replace include_defaults with the listed path. */
1781 char *epath = 0;
1782 switch ((objc << 1) + cplusplus)
1784 case 0:
1785 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
1786 break;
1787 case 1:
1788 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
1789 break;
1790 case 2:
1791 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
1792 break;
1793 case 3:
1794 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
1795 break;
1797 /* If the environment var for this language is set,
1798 add to the default list of include directories. */
1799 if (epath) {
1800 int num_dirs;
1801 char *startp, *endp;
1803 for (num_dirs = 1, startp = epath; *startp; startp++)
1804 if (*startp == PATH_SEPARATOR)
1805 num_dirs++;
1806 include_defaults
1807 = (struct default_include *) xmalloc ((num_dirs
1808 * sizeof (struct default_include))
1809 + sizeof (include_defaults_array));
1810 startp = endp = epath;
1811 num_dirs = 0;
1812 while (1) {
1813 char c = *endp++;
1814 if (c == PATH_SEPARATOR || !c) {
1815 endp[-1] = 0;
1816 include_defaults[num_dirs].fname
1817 = startp == endp ? "." : xstrdup (startp);
1818 endp[-1] = c;
1819 include_defaults[num_dirs].component = 0;
1820 include_defaults[num_dirs].cplusplus = cplusplus;
1821 include_defaults[num_dirs].cxx_aware = 1;
1822 num_dirs++;
1823 if (!c)
1824 break;
1825 startp = endp;
1828 /* Put the usual defaults back in at the end. */
1829 bcopy ((char *) include_defaults_array,
1830 (char *) &include_defaults[num_dirs],
1831 sizeof (include_defaults_array));
1835 append_include_chain (before_system, last_before_system);
1836 first_system_include = before_system;
1838 /* Unless -fnostdinc,
1839 tack on the standard include file dirs to the specified list */
1840 if (!no_standard_includes) {
1841 struct default_include *p = include_defaults;
1842 char *specd_prefix = include_prefix;
1843 char *default_prefix = xstrdup (GCC_INCLUDE_DIR);
1844 int default_len = 0;
1845 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1846 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1847 default_len = strlen (default_prefix) - 7;
1848 default_prefix[default_len] = 0;
1850 /* Search "translated" versions of GNU directories.
1851 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1852 if (specd_prefix != 0 && default_len != 0)
1853 for (p = include_defaults; p->fname; p++) {
1854 /* Some standard dirs are only for C++. */
1855 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1856 /* Does this dir start with the prefix? */
1857 if (!strncmp (p->fname, default_prefix, default_len)) {
1858 /* Yes; change prefix and add to search list. */
1859 struct file_name_list *new
1860 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1861 p->fname + default_len);
1862 if (new) {
1863 new->c_system_include_path = !p->cxx_aware;
1864 append_include_chain (new, new);
1865 if (first_system_include == 0)
1866 first_system_include = new;
1867 p->included = 1;
1872 /* Search ordinary names for GNU include directories. */
1873 for (p = include_defaults; p->fname; p++) {
1874 /* Some standard dirs are only for C++. */
1875 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1876 struct file_name_list *new
1877 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1878 if (new) {
1879 new->c_system_include_path = !p->cxx_aware;
1880 append_include_chain (new, new);
1881 if (first_system_include == 0)
1882 first_system_include = new;
1883 p->included = 1;
1889 /* Tack the after_include chain at the end of the include chain. */
1890 append_include_chain (after_include, last_after_include);
1891 if (first_system_include == 0)
1892 first_system_include = after_include;
1894 /* With -v, print the list of dirs to search. */
1895 if (verbose) {
1896 struct file_name_list *p;
1897 notice ("#include \"...\" search starts here:\n");
1898 for (p = include; p; p = p->next) {
1899 if (p == first_bracket_include)
1900 notice ("#include <...> search starts here:\n");
1901 if (!p->fname[0])
1902 fprintf (stderr, " .\n");
1903 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1904 fprintf (stderr, " %s\n", p->fname);
1905 else
1906 /* Omit trailing '/'. */
1907 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1909 notice ("End of search list.\n");
1911 struct default_include * d;
1912 notice ("The following default directories have been omitted from the search path:\n");
1913 for (d = include_defaults; d->fname; d++)
1914 if (! d->included)
1915 fprintf (stderr, " %s\n", d->fname);
1916 notice ("End of omitted list.\n");
1920 /* -MG doesn't select the form of output and must be specified with one of
1921 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1922 inhibit compilation. */
1923 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1924 fatal ("-MG must be specified with one of -M or -MM");
1926 /* Either of two environment variables can specify output of deps.
1927 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1928 where OUTPUT_FILE is the file to write deps info to
1929 and DEPS_TARGET is the target to mention in the deps. */
1931 if (print_deps == 0
1932 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1933 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1934 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1935 char *s;
1936 char *output_file;
1938 if (spec == 0) {
1939 spec = getenv ("SUNPRO_DEPENDENCIES");
1940 print_deps = 2;
1942 else
1943 print_deps = 1;
1945 /* Find the space before the DEPS_TARGET, if there is one. */
1946 s = index (spec, ' ');
1947 if (s) {
1948 deps_target = s + 1;
1949 output_file = xmalloc (s - spec + 1);
1950 bcopy (spec, output_file, s - spec);
1951 output_file[s - spec] = 0;
1952 } else {
1953 deps_target = 0;
1954 output_file = spec;
1957 deps_file = output_file;
1958 deps_mode = "a";
1961 /* For -M, print the expected object file name
1962 as the target of this Make-rule. */
1963 if (print_deps) {
1964 deps_allocated_size = 200;
1965 deps_buffer = xmalloc (deps_allocated_size);
1966 deps_buffer[0] = 0;
1967 deps_size = 0;
1968 deps_column = 0;
1970 if (deps_target) {
1971 deps_output (deps_target, ':');
1972 } else if (*in_fname == 0) {
1973 deps_output ("-", ':');
1974 } else {
1975 char *p, *q;
1976 int len;
1978 q = base_name (in_fname);
1980 /* Copy remainder to mungable area. */
1981 p = (char *) alloca (strlen(q) + 8);
1982 strcpy (p, q);
1984 /* Output P, but remove known suffixes. */
1985 len = strlen (p);
1986 q = p + len;
1987 if (len >= 2
1988 && p[len - 2] == '.'
1989 && index("cCsSm", p[len - 1]))
1990 q = p + (len - 2);
1991 else if (len >= 3
1992 && p[len - 3] == '.'
1993 && p[len - 2] == 'c'
1994 && p[len - 1] == 'c')
1995 q = p + (len - 3);
1996 else if (len >= 4
1997 && p[len - 4] == '.'
1998 && p[len - 3] == 'c'
1999 && p[len - 2] == 'x'
2000 && p[len - 1] == 'x')
2001 q = p + (len - 4);
2002 else if (len >= 4
2003 && p[len - 4] == '.'
2004 && p[len - 3] == 'c'
2005 && p[len - 2] == 'p'
2006 && p[len - 1] == 'p')
2007 q = p + (len - 4);
2009 /* Supply our own suffix. */
2010 strcpy (q, OBJECT_SUFFIX);
2012 deps_output (p, ':');
2015 deps_output (in_fname, ' ');
2018 /* Scan the -imacros files before the main input.
2019 Much like #including them, but with no_output set
2020 so that only their macro definitions matter. */
2022 no_output++; no_record_file++;
2023 for (i = 1; i < argc; i++)
2024 if (pend_files[i]) {
2025 struct include_file *inc;
2026 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2027 if (fd < 0) {
2028 perror_with_name (pend_files[i]);
2029 return FATAL_EXIT_CODE;
2031 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2033 no_output--; no_record_file--;
2035 /* Copy the entire contents of the main input file into
2036 the stacked input buffer previously allocated for it. */
2038 /* JF check for stdin */
2039 if (in_fname == NULL || *in_fname == 0) {
2040 in_fname = "";
2041 f = 0;
2042 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2043 goto perror;
2045 if (fstat (f, &st) != 0)
2046 pfatal_with_name (in_fname);
2047 fp->nominal_fname = fp->fname = in_fname;
2048 fp->nominal_fname_len = strlen (in_fname);
2049 fp->lineno = 1;
2050 fp->system_header_p = 0;
2051 /* JF all this is mine about reading pipes and ttys */
2052 if (! S_ISREG (st.st_mode)) {
2053 /* Read input from a file that is not a normal disk file.
2054 We cannot preallocate a buffer with the correct size,
2055 so we must read in the file a piece at the time and make it bigger. */
2056 int size;
2057 int bsize;
2058 int cnt;
2060 if (S_ISDIR (st.st_mode))
2061 fatal ("Input file `%s' is a directory", in_fname);
2063 bsize = 2000;
2064 size = 0;
2065 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2066 for (;;) {
2067 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2068 if (cnt < 0) goto perror; /* error! */
2069 size += cnt;
2070 if (size != bsize) break; /* End of file */
2071 bsize *= 2;
2072 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2074 fp->length = size;
2075 } else {
2076 /* Read a file whose size we can determine in advance.
2077 For the sake of VMS, st.st_size is just an upper bound. */
2078 size_t s = (size_t) st.st_size;
2079 if (s != st.st_size || s + 2 < s)
2080 memory_full ();
2081 fp->buf = (U_CHAR *) xmalloc (s + 2);
2082 fp->length = safe_read (f, (char *) fp->buf, s);
2083 if (fp->length < 0) goto perror;
2085 fp->bufp = fp->buf;
2086 fp->if_stack = if_stack;
2088 /* Make sure data ends with a newline. And put a null after it. */
2090 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2091 /* Backslash-newline at end is not good enough. */
2092 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2093 fp->buf[fp->length++] = '\n';
2094 missing_newline = 1;
2096 fp->buf[fp->length] = '\0';
2098 /* Unless inhibited, convert trigraphs in the input. */
2100 if (!no_trigraphs)
2101 trigraph_pcp (fp);
2103 if (warn_white_space)
2104 check_white_space (fp);
2106 /* Now that we know the input file is valid, open the output. */
2108 if (!out_fname || !strcmp (out_fname, ""))
2109 out_fname = "stdout";
2110 else if (! freopen (out_fname, "w", stdout))
2111 pfatal_with_name (out_fname);
2113 output_line_directive (fp, &outbuf, 0, same_file);
2115 /* Scan the -include files before the main input. */
2117 no_record_file++;
2118 for (i = 1; i < argc; i++)
2119 if (pend_includes[i]) {
2120 struct include_file *inc;
2121 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2122 if (fd < 0) {
2123 perror_with_name (pend_includes[i]);
2124 return FATAL_EXIT_CODE;
2126 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2128 no_record_file--;
2130 /* Scan the input, processing macros and directives. */
2132 rescan (&outbuf, 0);
2134 if (missing_newline)
2135 fp->lineno--;
2137 if (pedantic && missing_newline)
2138 pedwarn ("file does not end in newline");
2140 /* Now we have processed the entire input
2141 Write whichever kind of output has been requested. */
2143 if (dump_macros == dump_only)
2144 dump_all_macros ();
2145 else if (! inhibit_output) {
2146 write_output ();
2149 if (print_deps) {
2150 /* Don't actually write the deps file if compilation has failed. */
2151 if (errors == 0) {
2152 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2153 pfatal_with_name (deps_file);
2154 fputs (deps_buffer, deps_stream);
2155 putc ('\n', deps_stream);
2156 if (deps_file) {
2157 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2158 fatal ("I/O error on output");
2163 if (pcp_outfile && pcp_outfile != stdout
2164 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2165 fatal ("I/O error on `-pcp' output");
2167 if (ferror (stdout) || fclose (stdout) != 0)
2168 fatal ("I/O error on output");
2170 if (errors)
2171 exit (FATAL_EXIT_CODE);
2172 exit (SUCCESS_EXIT_CODE);
2174 perror:
2175 pfatal_with_name (in_fname);
2176 return 0;
2179 /* Given a colon-separated list of file names PATH,
2180 add all the names to the search path for include files. */
2182 static void
2183 path_include (path)
2184 char *path;
2186 char *p;
2188 p = path;
2190 if (*p)
2191 while (1) {
2192 char *q = p;
2193 char c;
2194 struct file_name_list *dirtmp;
2196 /* Find the end of this name. */
2197 while ((c = *q++) != PATH_SEPARATOR && c)
2198 continue;
2200 q[-1] = 0;
2201 dirtmp = new_include_prefix (last_include, NULL_PTR,
2202 "", p == q ? "." : p);
2203 q[-1] = c;
2204 append_include_chain (dirtmp, dirtmp);
2206 /* Advance past this name. */
2207 p = q;
2208 if (! c)
2209 break;
2213 /* Return the address of the first character in S that equals C.
2214 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2215 Return 0 if there is no such character. Assume that C itself is not '\0'.
2216 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2217 but unfortunately memchr isn't autoconfigured yet. */
2219 static U_CHAR *
2220 index0 (s, c, n)
2221 U_CHAR *s;
2222 int c;
2223 size_t n;
2225 char *p = (char *) s;
2226 for (;;) {
2227 char *q = index (p, c);
2228 if (q)
2229 return (U_CHAR *) q;
2230 else {
2231 size_t l = strlen (p);
2232 if (l == n)
2233 return 0;
2234 l++;
2235 p += l;
2236 n -= l;
2241 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2242 before main CCCP processing. Name `pcp' is also in honor of the
2243 drugs the trigraph designers must have been on.
2245 Using an extra pass through the buffer takes a little extra time,
2246 but is infinitely less hairy than trying to handle trigraphs inside
2247 strings, etc. everywhere, and also makes sure that trigraphs are
2248 only translated in the top level of processing. */
2250 static void
2251 trigraph_pcp (buf)
2252 FILE_BUF *buf;
2254 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2255 int len;
2257 fptr = bptr = sptr = buf->buf;
2258 lptr = fptr + buf->length;
2259 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2260 if (*++sptr != '?')
2261 continue;
2262 switch (*++sptr) {
2263 case '=':
2264 c = '#';
2265 break;
2266 case '(':
2267 c = '[';
2268 break;
2269 case '/':
2270 c = '\\';
2271 break;
2272 case ')':
2273 c = ']';
2274 break;
2275 case '\'':
2276 c = '^';
2277 break;
2278 case '<':
2279 c = '{';
2280 break;
2281 case '!':
2282 c = '|';
2283 break;
2284 case '>':
2285 c = '}';
2286 break;
2287 case '-':
2288 c = '~';
2289 break;
2290 case '?':
2291 sptr--;
2292 continue;
2293 default:
2294 continue;
2296 len = sptr - fptr - 2;
2298 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2299 C, this will be memmove (). */
2300 if (bptr != fptr && len > 0)
2301 bcopy ((char *) fptr, (char *) bptr, len);
2303 bptr += len;
2304 *bptr++ = c;
2305 fptr = ++sptr;
2307 len = buf->length - (fptr - buf->buf);
2308 if (bptr != fptr && len > 0)
2309 bcopy ((char *) fptr, (char *) bptr, len);
2310 buf->length -= fptr - bptr;
2311 buf->buf[buf->length] = '\0';
2312 if (warn_trigraphs && fptr != bptr)
2313 warning_with_line (0, "%lu trigraph(s) encountered",
2314 (unsigned long) (fptr - bptr) / 2);
2317 /* Warn about white space between backslash and end of line. */
2319 static void
2320 check_white_space (buf)
2321 FILE_BUF *buf;
2323 register U_CHAR *sptr = buf->buf;
2324 register U_CHAR *lptr = sptr + buf->length;
2325 register U_CHAR *nptr;
2326 int line = 0;
2328 nptr = sptr = buf->buf;
2329 lptr = sptr + buf->length;
2330 for (nptr = sptr;
2331 (nptr = index0 (nptr, '\n', (size_t) (lptr - nptr))) != NULL;
2332 nptr ++) {
2333 register U_CHAR *p = nptr;
2334 line++;
2335 for (p = nptr; sptr < p; p--) {
2336 if (! is_hor_space[p[-1]]) {
2337 if (p[-1] == '\\' && p != nptr)
2338 warning_with_line (line,
2339 "`\\' followed by white space at end of line");
2340 break;
2346 /* Move all backslash-newline pairs out of embarrassing places.
2347 Exchange all such pairs following BP
2348 with any potentially-embarrassing characters that follow them.
2349 Potentially-embarrassing characters are / and *
2350 (because a backslash-newline inside a comment delimiter
2351 would cause it not to be recognized).
2352 We assume that *BP == '\\'. */
2354 static void
2355 newline_fix (bp)
2356 U_CHAR *bp;
2358 register U_CHAR *p = bp;
2360 /* First count the backslash-newline pairs here. */
2361 do {
2362 if (p[1] != '\n')
2363 break;
2364 p += 2;
2365 } while (*p == '\\');
2367 /* What follows the backslash-newlines is not embarrassing. */
2369 if (*p != '/' && *p != '*')
2370 /* What follows the backslash-newlines is not embarrassing. */
2371 return;
2373 /* Copy all potentially embarrassing characters
2374 that follow the backslash-newline pairs
2375 down to where the pairs originally started. */
2377 *bp++ = *p++;
2378 while (*p == '*' || *p == '/');
2380 /* Now write the same number of pairs after the embarrassing chars. */
2381 while (bp < p) {
2382 *bp++ = '\\';
2383 *bp++ = '\n';
2387 /* Like newline_fix but for use within a directive-name.
2388 Move any backslash-newlines up past any following symbol constituents. */
2390 static void
2391 name_newline_fix (bp)
2392 U_CHAR *bp;
2394 register U_CHAR *p = bp;
2396 /* First count the backslash-newline pairs here. */
2397 do {
2398 if (p[1] != '\n')
2399 break;
2400 p += 2;
2401 } while (*p == '\\');
2403 /* What follows the backslash-newlines is not embarrassing. */
2405 if (!is_idchar[*p])
2406 /* What follows the backslash-newlines is not embarrassing. */
2407 return;
2409 /* Copy all potentially embarrassing characters
2410 that follow the backslash-newline pairs
2411 down to where the pairs originally started. */
2413 *bp++ = *p++;
2414 while (is_idchar[*p]);
2416 /* Now write the same number of pairs after the embarrassing chars. */
2417 while (bp < p) {
2418 *bp++ = '\\';
2419 *bp++ = '\n';
2423 /* Look for lint commands in comments.
2425 When we come in here, ibp points into a comment. Limit is as one expects.
2426 scan within the comment -- it should start, after lwsp, with a lint command.
2427 If so that command is returned as a (constant) string.
2429 Upon return, any arg will be pointed to with argstart and will be
2430 arglen long. Note that we don't parse that arg since it will just
2431 be printed out again. */
2433 static char *
2434 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2435 register U_CHAR *ibp;
2436 register U_CHAR *limit;
2437 U_CHAR **argstart; /* point to command arg */
2438 int *arglen, *cmdlen; /* how long they are */
2440 HOST_WIDEST_INT linsize;
2441 register U_CHAR *numptr; /* temp for arg parsing */
2443 *arglen = 0;
2445 SKIP_WHITE_SPACE (ibp);
2447 if (ibp >= limit) return NULL;
2449 linsize = limit - ibp;
2451 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2452 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2453 *cmdlen = 10;
2454 return "NOTREACHED";
2456 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2457 *cmdlen = 8;
2458 return "ARGSUSED";
2460 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2461 *cmdlen = 11;
2462 return "LINTLIBRARY";
2464 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2465 *cmdlen = 7;
2466 ibp += 7; linsize -= 7;
2467 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2469 /* OK, read a number */
2470 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2471 numptr++);
2472 *arglen = numptr - *argstart;
2473 return "VARARGS";
2475 return NULL;
2479 * The main loop of the program.
2481 * Read characters from the input stack, transferring them to the
2482 * output buffer OP.
2484 * Macros are expanded and push levels on the input stack.
2485 * At the end of such a level it is popped off and we keep reading.
2486 * At the end of any other kind of level, we return.
2487 * #-directives are handled, except within macros.
2489 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2490 * and insert them when appropriate. This is set while scanning macro
2491 * arguments before substitution. It is zero when scanning for final output.
2492 * There are two types of Newline markers:
2493 * * Newline - follows a macro name that was not expanded
2494 * because it appeared inside an expansion of the same macro.
2495 * This marker prevents future expansion of that identifier.
2496 * When the input is rescanned into the final output, these are deleted.
2497 * These are also deleted by ## concatenation.
2498 * * Newline Space (or Newline and any other whitespace character)
2499 * stands for a place that tokens must be separated or whitespace
2500 * is otherwise desirable, but where the ANSI standard specifies there
2501 * is no whitespace. This marker turns into a Space (or whichever other
2502 * whitespace char appears in the marker) in the final output,
2503 * but it turns into nothing in an argument that is stringified with #.
2504 * Such stringified arguments are the only place where the ANSI standard
2505 * specifies with precision that whitespace may not appear.
2507 * During this function, IP->bufp is kept cached in IBP for speed of access.
2508 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2509 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2510 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2511 * explicitly, and before RECACHE, since RECACHE uses OBP.
2514 static void
2515 rescan (op, output_marks)
2516 FILE_BUF *op;
2517 int output_marks;
2519 /* Character being scanned in main loop. */
2520 register U_CHAR c;
2522 /* Length of pending accumulated identifier. */
2523 register int ident_length = 0;
2525 /* Hash code of pending accumulated identifier. */
2526 register int hash = 0;
2528 /* Current input level (&instack[indepth]). */
2529 FILE_BUF *ip;
2531 /* Pointer for scanning input. */
2532 register U_CHAR *ibp;
2534 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2535 register U_CHAR *limit;
2537 /* Pointer for storing output. */
2538 register U_CHAR *obp;
2540 /* REDO_CHAR is nonzero if we are processing an identifier
2541 after backing up over the terminating character.
2542 Sometimes we process an identifier without backing up over
2543 the terminating character, if the terminating character
2544 is not special. Backing up is done so that the terminating character
2545 will be dispatched on again once the identifier is dealt with. */
2546 int redo_char = 0;
2548 /* 1 if within an identifier inside of which a concatenation
2549 marker (Newline -) has been seen. */
2550 int concatenated = 0;
2552 /* While scanning a comment or a string constant,
2553 this records the line it started on, for error messages. */
2554 int start_line;
2556 /* Record position of last `real' newline. */
2557 U_CHAR *beg_of_line;
2559 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2561 #define POPMACRO \
2562 do { ip->macro->type = T_MACRO; \
2563 if (ip->free_ptr) free (ip->free_ptr); \
2564 --indepth; } while (0)
2566 /* Reload `rescan's local variables that describe the current
2567 level of the input stack. */
2569 #define RECACHE \
2570 do { ip = &instack[indepth]; \
2571 ibp = ip->bufp; \
2572 limit = ip->buf + ip->length; \
2573 op->bufp = obp; \
2574 check_expand (op, limit - ibp); \
2575 beg_of_line = 0; \
2576 obp = op->bufp; } while (0)
2578 if (no_output && instack[indepth].fname != 0)
2579 skip_if_group (&instack[indepth], 1, NULL);
2581 obp = op->bufp;
2582 RECACHE;
2584 beg_of_line = ibp;
2586 /* Our caller must always put a null after the end of
2587 the input at each input stack level. */
2588 if (*limit != 0)
2589 abort ();
2591 while (1) {
2592 c = *ibp++;
2593 *obp++ = c;
2595 switch (c) {
2596 case '\\':
2597 if (*ibp == '\n' && !ip->macro) {
2598 /* At the top level, always merge lines ending with backslash-newline,
2599 even in middle of identifier. But do not merge lines in a macro,
2600 since backslash might be followed by a newline-space marker. */
2601 ++ibp;
2602 ++ip->lineno;
2603 --obp; /* remove backslash from obuf */
2604 break;
2606 /* If ANSI, backslash is just another character outside a string. */
2607 if (!traditional)
2608 goto randomchar;
2609 /* Otherwise, backslash suppresses specialness of following char,
2610 so copy it here to prevent the switch from seeing it.
2611 But first get any pending identifier processed. */
2612 if (ident_length > 0)
2613 goto specialchar;
2614 if (ibp < limit)
2615 *obp++ = *ibp++;
2616 break;
2618 case '%':
2619 if (ident_length || ip->macro || traditional)
2620 goto randomchar;
2621 while (*ibp == '\\' && ibp[1] == '\n') {
2622 ibp += 2;
2623 ++ip->lineno;
2625 if (*ibp != ':')
2626 break;
2627 /* Treat this %: digraph as if it were #. */
2628 /* Fall through. */
2630 case '#':
2631 if (assertions_flag) {
2632 if (ident_length)
2633 goto specialchar;
2634 /* Copy #foo (bar lose) without macro expansion. */
2635 obp[-1] = '#'; /* In case it was '%'. */
2636 SKIP_WHITE_SPACE (ibp);
2637 while (is_idchar[*ibp])
2638 *obp++ = *ibp++;
2639 SKIP_WHITE_SPACE (ibp);
2640 if (*ibp == '(') {
2641 ip->bufp = ibp;
2642 skip_paren_group (ip);
2643 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2644 obp += ip->bufp - ibp;
2645 ibp = ip->bufp;
2647 break;
2650 /* If this is expanding a macro definition, don't recognize
2651 preprocessing directives. */
2652 if (ip->macro != 0)
2653 goto randomchar;
2654 /* If this is expand_into_temp_buffer,
2655 don't recognize them either. Warn about them
2656 only after an actual newline at this level,
2657 not at the beginning of the input level. */
2658 if (! ip->fname) {
2659 if (ip->buf != beg_of_line)
2660 warning ("preprocessing directive not recognized within macro arg");
2661 goto randomchar;
2663 if (ident_length)
2664 goto specialchar;
2667 /* # keyword: a # must be first nonblank char on the line */
2668 if (beg_of_line == 0)
2669 goto randomchar;
2671 U_CHAR *bp;
2673 /* Scan from start of line, skipping whitespace, comments
2674 and backslash-newlines, and see if we reach this #.
2675 If not, this # is not special. */
2676 bp = beg_of_line;
2677 /* If -traditional, require # to be at beginning of line. */
2678 if (!traditional) {
2679 while (1) {
2680 if (is_hor_space[*bp])
2681 bp++;
2682 else if (*bp == '\\' && bp[1] == '\n')
2683 bp += 2;
2684 else if (*bp == '/' && bp[1] == '*') {
2685 bp += 2;
2686 while (1)
2688 if (*bp == '*')
2690 if (bp[1] == '/')
2692 bp += 2;
2693 break;
2696 else
2698 #ifdef MULTIBYTE_CHARS
2699 int length;
2700 length = local_mblen (bp, limit - bp);
2701 if (length > 1)
2702 bp += (length - 1);
2703 #endif
2705 bp++;
2708 /* There is no point in trying to deal with C++ // comments here,
2709 because if there is one, then this # must be part of the
2710 comment and we would never reach here. */
2711 else break;
2713 if (c == '%') {
2714 if (bp[0] != '%')
2715 break;
2716 while (bp[1] == '\\' && bp[2] == '\n')
2717 bp += 2;
2718 if (bp + 1 != ibp)
2719 break;
2720 /* %: appears at start of line; skip past the ':' too. */
2721 bp++;
2722 ibp++;
2725 if (bp + 1 != ibp)
2726 goto randomchar;
2729 /* This # can start a directive. */
2731 --obp; /* Don't copy the '#' */
2733 ip->bufp = ibp;
2734 op->bufp = obp;
2735 if (! handle_directive (ip, op)) {
2736 #ifdef USE_C_ALLOCA
2737 alloca (0);
2738 #endif
2739 /* Not a known directive: treat it as ordinary text.
2740 IP, OP, IBP, etc. have not been changed. */
2741 if (no_output && instack[indepth].fname) {
2742 /* If not generating expanded output,
2743 what we do with ordinary text is skip it.
2744 Discard everything until next # directive. */
2745 skip_if_group (&instack[indepth], 1, 0);
2746 RECACHE;
2747 beg_of_line = ibp;
2748 break;
2750 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2751 /* Don't expand an identifier that could be a macro directive.
2752 (Section 3.8.3 of the ANSI C standard) */
2753 SKIP_WHITE_SPACE (ibp);
2754 if (is_idstart[*ibp])
2756 *obp++ = *ibp++;
2757 while (is_idchar[*ibp])
2758 *obp++ = *ibp++;
2760 goto randomchar;
2762 #ifdef USE_C_ALLOCA
2763 alloca (0);
2764 #endif
2765 /* A # directive has been successfully processed. */
2766 /* If not generating expanded output, ignore everything until
2767 next # directive. */
2768 if (no_output && instack[indepth].fname)
2769 skip_if_group (&instack[indepth], 1, 0);
2770 obp = op->bufp;
2771 RECACHE;
2772 beg_of_line = ibp;
2773 break;
2775 case '\"': /* skip quoted string */
2776 case '\'':
2777 /* A single quoted string is treated like a double -- some
2778 programs (e.g., troff) are perverse this way */
2780 /* Handle any pending identifier;
2781 but the L in L'...' or L"..." is not an identifier. */
2782 if (ident_length) {
2783 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2784 goto specialchar;
2785 ident_length = hash = 0;
2788 start_line = ip->lineno;
2790 /* Skip ahead to a matching quote. */
2792 while (1) {
2793 if (ibp >= limit) {
2794 if (ip->macro != 0) {
2795 /* try harder: this string crosses a macro expansion boundary.
2796 This can happen naturally if -traditional.
2797 Otherwise, only -D can make a macro with an unmatched quote. */
2798 POPMACRO;
2799 RECACHE;
2800 continue;
2802 if (!traditional) {
2803 error_with_line (line_for_error (start_line),
2804 "unterminated string or character constant");
2805 if (multiline_string_line) {
2806 error_with_line (multiline_string_line,
2807 "possible real start of unterminated constant");
2808 multiline_string_line = 0;
2811 break;
2813 *obp++ = *ibp;
2814 switch (*ibp++) {
2815 case '\n':
2816 if (warn_white_space && ip->fname && is_hor_space[ibp[-2]])
2817 warning ("white space at end of line in string");
2818 ++ip->lineno;
2819 ++op->lineno;
2820 /* Traditionally, end of line ends a string constant with no error.
2821 So exit the loop and record the new line. */
2822 if (traditional) {
2823 beg_of_line = ibp;
2824 goto while2end;
2826 if (c == '\'') {
2827 error_with_line (line_for_error (start_line),
2828 "unterminated character constant");
2829 goto while2end;
2831 if (multiline_string_line == 0) {
2832 if (pedantic)
2833 pedwarn_with_line (line_for_error (start_line),
2834 "string constant runs past end of line");
2835 multiline_string_line = ip->lineno - 1;
2837 break;
2839 case '\\':
2840 if (*ibp == '\n') {
2841 /* Backslash newline is replaced by nothing at all, but
2842 keep the line counts correct. But if we are reading
2843 from a macro, keep the backslash newline, since backslash
2844 newlines have already been processed. */
2845 if (ip->macro) {
2846 *obp++ = '\n';
2847 ++op->lineno;
2848 } else
2849 --obp;
2850 ++ibp;
2851 ++ip->lineno;
2852 } else {
2853 /* ANSI stupidly requires that in \\ the second \
2854 is *not* prevented from combining with a newline. */
2855 if (!ip->macro) {
2856 while (*ibp == '\\' && ibp[1] == '\n') {
2857 *obp++ = *ibp++;
2858 *obp++ = *ibp++;
2859 ++ip->lineno;
2860 ++op->lineno;
2863 *obp++ = *ibp++;
2865 break;
2867 case '\"':
2868 case '\'':
2869 if (ibp[-1] == c)
2870 goto while2end;
2871 break;
2872 #ifdef MULTIBYTE_CHARS
2873 default:
2875 int length;
2876 --ibp;
2877 length = local_mblen (ibp, limit - ibp);
2878 if (length > 0)
2880 --obp;
2881 bcopy (ibp, obp, length);
2882 obp += length;
2883 ibp += length;
2885 else
2886 ++ibp;
2888 break;
2889 #endif
2892 while2end:
2893 break;
2895 case '/':
2896 if (ip->macro != 0)
2897 goto randomchar;
2898 if (*ibp == '\\')
2899 newline_fix (ibp);
2900 if (*ibp != '*'
2901 && !(cplusplus_comments && *ibp == '/'))
2902 goto randomchar;
2903 if (ident_length)
2904 goto specialchar;
2906 if (*ibp == '/') {
2907 /* C++ style comment... */
2908 start_line = ip->lineno;
2910 /* Comments are equivalent to spaces. */
2911 if (! put_out_comments)
2912 obp[-1] = ' ';
2915 U_CHAR *before_bp = ibp;
2917 while (++ibp < limit) {
2918 if (*ibp == '\n')
2920 if (put_out_comments) {
2921 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2922 obp += ibp - before_bp;
2924 break;
2926 if (*ibp == '\\')
2928 if (ibp + 1 < limit && ibp[1] == '\n')
2930 if (warn_comments)
2931 warning ("multiline `//' comment");
2932 ++ip->lineno;
2933 /* Copy the newline into the output buffer, in order to
2934 avoid the pain of a #line every time a multiline comment
2935 is seen. */
2936 if (!put_out_comments)
2937 *obp++ = '\n';
2938 ++op->lineno;
2939 ++ibp;
2942 else
2944 #ifdef MULTIBYTE_CHARS
2945 int length;
2946 length = local_mblen (ibp, limit - ibp);
2947 if (length > 1)
2948 ibp += (length - 1);
2949 #endif
2952 break;
2956 /* Ordinary C comment. Skip it, optionally copying it to output. */
2958 start_line = ip->lineno;
2960 ++ibp; /* Skip the star. */
2962 /* If this cpp is for lint, we peek inside the comments: */
2963 if (for_lint) {
2964 U_CHAR *argbp;
2965 int cmdlen, arglen;
2966 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2968 if (lintcmd != NULL) {
2969 op->bufp = obp;
2970 check_expand (op, cmdlen + arglen + 14);
2971 obp = op->bufp;
2972 /* I believe it is always safe to emit this newline: */
2973 obp[-1] = '\n';
2974 bcopy ("#pragma lint ", (char *) obp, 13);
2975 obp += 13;
2976 bcopy (lintcmd, (char *) obp, cmdlen);
2977 obp += cmdlen;
2979 if (arglen != 0) {
2980 *(obp++) = ' ';
2981 bcopy (argbp, (char *) obp, arglen);
2982 obp += arglen;
2985 /* OK, now bring us back to the state we were in before we entered
2986 this branch. We need #line because the #pragma's newline always
2987 messes up the line count. */
2988 op->bufp = obp;
2989 output_line_directive (ip, op, 0, same_file);
2990 check_expand (op, limit - ibp + 2);
2991 obp = op->bufp;
2992 *(obp++) = '/';
2996 /* Comments are equivalent to spaces.
2997 Note that we already output the slash; we might not want it.
2998 For -traditional, a comment is equivalent to nothing. */
2999 if (! put_out_comments) {
3000 if (traditional)
3001 obp--;
3002 else
3003 obp[-1] = ' ';
3005 else
3006 *obp++ = '*';
3009 U_CHAR *before_bp = ibp;
3011 for (;;) {
3012 switch (*ibp++) {
3013 case '*':
3014 if (ibp[-2] == '/' && warn_comments)
3015 warning ("`/*' within comment");
3016 if (*ibp == '\\')
3017 newline_fix (ibp);
3018 if (*ibp == '/')
3019 goto comment_end;
3020 break;
3022 case '\n':
3023 ++ip->lineno;
3024 /* Copy the newline into the output buffer, in order to
3025 avoid the pain of a #line every time a multiline comment
3026 is seen. */
3027 if (!put_out_comments)
3028 *obp++ = '\n';
3029 ++op->lineno;
3030 break;
3032 case 0:
3033 if (limit < ibp) {
3034 error_with_line (line_for_error (start_line),
3035 "unterminated comment");
3036 goto limit_reached;
3038 break;
3039 #ifdef MULTIBYTE_CHARS
3040 default:
3042 int length;
3043 length = local_mblen (ibp, limit - ibp);
3044 if (length > 1)
3045 ibp += (length - 1);
3047 break;
3048 #endif
3051 comment_end:
3053 ibp++;
3054 if (put_out_comments) {
3055 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3056 obp += ibp - before_bp;
3059 break;
3061 case '$':
3062 if (! is_idchar['$'])
3063 goto randomchar;
3064 if (pedantic)
3065 pedwarn ("`$' in identifier");
3066 goto letter;
3068 case '0': case '1': case '2': case '3': case '4':
3069 case '5': case '6': case '7': case '8': case '9':
3070 /* If digit is not part of identifier, it starts a number,
3071 which means that following letters are not an identifier.
3072 "0x5" does not refer to an identifier "x5".
3073 So copy all alphanumerics that follow without accumulating
3074 as an identifier. Periods also, for sake of "3.e7". */
3076 if (ident_length == 0) {
3077 for (;;) {
3078 if (!ip->macro) {
3079 while (ibp[0] == '\\' && ibp[1] == '\n') {
3080 ++ip->lineno;
3081 ibp += 2;
3084 c = *ibp++;
3085 if (!is_idchar[c] && c != '.') {
3086 --ibp;
3087 break;
3089 *obp++ = c;
3090 /* A sign can be part of a preprocessing number
3091 if it follows an `e' or `p'. */
3092 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3093 if (!ip->macro) {
3094 while (ibp[0] == '\\' && ibp[1] == '\n') {
3095 ++ip->lineno;
3096 ibp += 2;
3099 if (*ibp == '+' || *ibp == '-') {
3100 *obp++ = *ibp++;
3101 /* But traditional C does not let the token go past the sign,
3102 and C89 does not allow `p'. */
3103 if (traditional || (c89 && (c == 'p' || c == 'P')))
3104 break;
3108 break;
3110 /* fall through */
3112 case '_':
3113 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3114 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3115 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3116 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3117 case 'y': case 'z':
3118 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3119 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3120 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3121 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3122 case 'Y': case 'Z':
3123 letter:
3124 ident_length++;
3125 /* Compute step of hash function, to avoid a proc call on every token */
3126 hash = HASHSTEP (hash, c);
3127 break;
3129 case '\n':
3130 if (ip->fname == 0 && *ibp == '-') {
3131 /* Newline - inhibits expansion of preceding token.
3132 If expanding a macro arg, we keep the newline -.
3133 In final output, it is deleted.
3134 We recognize Newline - in macro bodies and macro args. */
3135 if (! concatenated) {
3136 ident_length = 0;
3137 hash = 0;
3139 ibp++;
3140 if (!output_marks) {
3141 obp--;
3142 } else {
3143 /* If expanding a macro arg, keep the newline -. */
3144 *obp++ = '-';
3146 break;
3149 /* If reprocessing a macro expansion, newline is a special marker. */
3150 else if (ip->macro != 0) {
3151 /* Newline White is a "funny space" to separate tokens that are
3152 supposed to be separate but without space between.
3153 Here White means any whitespace character.
3154 Newline - marks a recursive macro use that is not
3155 supposed to be expandable. */
3157 if (is_space[*ibp]) {
3158 /* Newline Space does not prevent expansion of preceding token
3159 so expand the preceding token and then come back. */
3160 if (ident_length > 0)
3161 goto specialchar;
3163 /* If generating final output, newline space makes a space. */
3164 if (!output_marks) {
3165 obp[-1] = *ibp++;
3166 /* And Newline Newline makes a newline, so count it. */
3167 if (obp[-1] == '\n')
3168 op->lineno++;
3169 } else {
3170 /* If expanding a macro arg, keep the newline space.
3171 If the arg gets stringified, newline space makes nothing. */
3172 *obp++ = *ibp++;
3174 } else abort (); /* Newline followed by something random? */
3175 break;
3178 /* If there is a pending identifier, handle it and come back here. */
3179 if (ident_length > 0)
3180 goto specialchar;
3182 beg_of_line = ibp;
3184 /* Update the line counts and output a #line if necessary. */
3185 ++ip->lineno;
3186 ++op->lineno;
3187 if (ip->lineno != op->lineno) {
3188 op->bufp = obp;
3189 output_line_directive (ip, op, 1, same_file);
3190 check_expand (op, limit - ibp);
3191 obp = op->bufp;
3193 break;
3195 /* Come here either after (1) a null character that is part of the input
3196 or (2) at the end of the input, because there is a null there. */
3197 case 0:
3198 if (ibp <= limit)
3199 /* Our input really contains a null character. */
3200 goto randomchar;
3202 limit_reached:
3203 /* At end of a macro-expansion level, pop it and read next level. */
3204 if (ip->macro != 0) {
3205 obp--;
3206 ibp--;
3207 /* If traditional, and we have an identifier that ends here,
3208 process it now, so we get the right error for recursion. */
3209 if (traditional && ident_length
3210 && ! is_idchar[*instack[indepth - 1].bufp]) {
3211 redo_char = 1;
3212 goto randomchar;
3214 POPMACRO;
3215 RECACHE;
3216 break;
3219 /* If we don't have a pending identifier,
3220 return at end of input. */
3221 if (ident_length == 0) {
3222 obp--;
3223 ibp--;
3224 op->bufp = obp;
3225 ip->bufp = ibp;
3226 goto ending;
3229 /* If we do have a pending identifier, just consider this null
3230 a special character and arrange to dispatch on it again.
3231 The second time, IDENT_LENGTH will be zero so we will return. */
3233 /* Fall through */
3235 specialchar:
3237 /* Handle the case of a character such as /, ', " or null
3238 seen following an identifier. Back over it so that
3239 after the identifier is processed the special char
3240 will be dispatched on again. */
3242 ibp--;
3243 obp--;
3244 redo_char = 1;
3246 default:
3248 randomchar:
3250 if (ident_length > 0) {
3251 register HASHNODE *hp;
3253 /* We have just seen an identifier end. If it's a macro, expand it.
3255 IDENT_LENGTH is the length of the identifier
3256 and HASH is its hash code.
3258 The identifier has already been copied to the output,
3259 so if it is a macro we must remove it.
3261 If REDO_CHAR is 0, the char that terminated the identifier
3262 has been skipped in the output and the input.
3263 OBP-IDENT_LENGTH-1 points to the identifier.
3264 If the identifier is a macro, we must back over the terminator.
3266 If REDO_CHAR is 1, the terminating char has already been
3267 backed over. OBP-IDENT_LENGTH points to the identifier. */
3269 if (!pcp_outfile || pcp_inside_if) {
3270 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3271 hp = hp->next) {
3273 if (hp->length == ident_length) {
3274 int obufp_before_macroname;
3275 int op_lineno_before_macroname;
3276 register int i = ident_length;
3277 register U_CHAR *p = hp->name;
3278 register U_CHAR *q = obp - i;
3279 int disabled;
3281 if (! redo_char)
3282 q--;
3284 do { /* All this to avoid a strncmp () */
3285 if (*p++ != *q++)
3286 goto hashcollision;
3287 } while (--i);
3289 /* We found a use of a macro name.
3290 see if the context shows it is a macro call. */
3292 /* Back up over terminating character if not already done. */
3293 if (! redo_char) {
3294 ibp--;
3295 obp--;
3298 /* Save this as a displacement from the beginning of the output
3299 buffer. We can not save this as a position in the output
3300 buffer, because it may get realloc'ed by RECACHE. */
3301 obufp_before_macroname = (obp - op->buf) - ident_length;
3302 op_lineno_before_macroname = op->lineno;
3304 if (hp->type == T_PCSTRING) {
3305 pcstring_used (hp); /* Mark the definition of this key
3306 as needed, ensuring that it
3307 will be output. */
3308 break; /* Exit loop, since the key cannot have a
3309 definition any longer. */
3312 /* Record whether the macro is disabled. */
3313 disabled = hp->type == T_DISABLED;
3315 /* This looks like a macro ref, but if the macro was disabled,
3316 just copy its name and put in a marker if requested. */
3318 if (disabled) {
3319 #if 0
3320 /* This error check caught useful cases such as
3321 #define foo(x,y) bar (x (y,0), y)
3322 foo (foo, baz) */
3323 if (traditional)
3324 error ("recursive use of macro `%s'", hp->name);
3325 #endif
3327 if (output_marks) {
3328 check_expand (op, limit - ibp + 2);
3329 *obp++ = '\n';
3330 *obp++ = '-';
3332 break;
3335 /* If macro wants an arglist, verify that a '(' follows.
3336 first skip all whitespace, copying it to the output
3337 after the macro name. Then, if there is no '(',
3338 decide this is not a macro call and leave things that way. */
3339 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3340 && hp->value.defn->nargs >= 0)
3342 U_CHAR *old_ibp = ibp;
3343 U_CHAR *old_obp = obp;
3344 int old_iln = ip->lineno;
3345 int old_oln = op->lineno;
3347 while (1) {
3348 /* Scan forward over whitespace, copying it to the output. */
3349 if (ibp == limit && ip->macro != 0) {
3350 POPMACRO;
3351 RECACHE;
3352 old_ibp = ibp;
3353 old_obp = obp;
3354 old_iln = ip->lineno;
3355 old_oln = op->lineno;
3357 else if (is_space[*ibp]) {
3358 *obp++ = *ibp++;
3359 if (ibp[-1] == '\n') {
3360 if (ip->macro == 0) {
3361 /* Newline in a file. Count it. */
3362 ++ip->lineno;
3363 ++op->lineno;
3364 } else if (!output_marks) {
3365 /* A newline mark, and we don't want marks
3366 in the output. If it is newline-hyphen,
3367 discard it entirely. Otherwise, it is
3368 newline-whitechar, so keep the whitechar. */
3369 obp--;
3370 if (*ibp == '-')
3371 ibp++;
3372 else {
3373 if (*ibp == '\n')
3374 ++op->lineno;
3375 *obp++ = *ibp++;
3377 } else {
3378 /* A newline mark; copy both chars to the output. */
3379 *obp++ = *ibp++;
3383 else if (ip->macro)
3384 break;
3385 else if (*ibp == '/') {
3386 /* If a comment, copy it unchanged or discard it. */
3387 if (ibp[1] == '\\')
3388 newline_fix (ibp + 1);
3389 if (ibp[1] == '*') {
3390 if (put_out_comments) {
3391 *obp++ = '/';
3392 *obp++ = '*';
3393 } else if (! traditional) {
3394 *obp++ = ' ';
3396 for (ibp += 2; ibp < limit; ibp++) {
3397 /* We need not worry about newline-marks,
3398 since they are never found in comments. */
3399 if (ibp[0] == '*') {
3400 if (ibp[1] == '\\')
3401 newline_fix (ibp + 1);
3402 if (ibp[1] == '/') {
3403 ibp += 2;
3404 if (put_out_comments) {
3405 *obp++ = '*';
3406 *obp++ = '/';
3408 break;
3411 else if (*ibp == '\n') {
3412 /* Newline in a file. Count it. */
3413 ++ip->lineno;
3414 ++op->lineno;
3416 else
3418 #ifdef MULTIBYTE_CHARS
3419 int length;
3420 length = local_mblen (ibp, limit - ibp);
3421 if (length > 1)
3423 if (put_out_comments)
3425 bcopy (ibp, obp, length - 1);
3426 obp += length - 1;
3428 ibp += (length - 1);
3430 #endif
3432 if (put_out_comments)
3433 *obp++ = *ibp;
3435 } else if (ibp[1] == '/' && cplusplus_comments) {
3436 if (put_out_comments) {
3437 *obp++ = '/';
3438 *obp++ = '/';
3439 } else if (! traditional) {
3440 *obp++ = ' ';
3442 for (ibp += 2; ; ibp++)
3444 if (*ibp == '\n')
3445 break;
3446 if (*ibp == '\\' && ibp[1] == '\n')
3448 if (put_out_comments)
3449 *obp++ = *ibp++;
3451 else
3453 #ifdef MULTIBYTE_CHARS
3454 int length;
3455 length = local_mblen (ibp, limit - ibp);
3456 if (length > 1)
3458 if (put_out_comments)
3460 bcopy (ibp, obp, length - 1);
3461 obp += length - 1;
3463 ibp += (length - 1);
3465 #endif
3467 if (put_out_comments)
3468 *obp++ = *ibp;
3470 } else
3471 break;
3473 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3474 ibp += 2;
3475 ++ip->lineno;
3477 else break;
3479 if (*ibp != '(') {
3480 /* It isn't a macro call.
3481 Put back the space that we just skipped. */
3482 ibp = old_ibp;
3483 obp = old_obp;
3484 ip->lineno = old_iln;
3485 op->lineno = old_oln;
3486 /* Exit the for loop. */
3487 break;
3491 /* This is now known to be a macro call.
3492 Discard the macro name from the output,
3493 along with any following whitespace just copied,
3494 but preserve newlines if not outputting marks since this
3495 is more likely to do the right thing with line numbers. */
3496 obp = op->buf + obufp_before_macroname;
3497 if (output_marks)
3498 op->lineno = op_lineno_before_macroname;
3499 else {
3500 int newlines = op->lineno - op_lineno_before_macroname;
3501 while (0 < newlines--)
3502 *obp++ = '\n';
3505 /* Prevent accidental token-pasting with a character
3506 before the macro call. */
3507 if (!traditional && obp != op->buf) {
3508 switch (obp[-1]) {
3509 case '!': case '%': case '&': case '*':
3510 case '+': case '-': case '.': case '/':
3511 case ':': case '<': case '=': case '>':
3512 case '^': case '|':
3513 /* If we are expanding a macro arg, make a newline marker
3514 to separate the tokens. If we are making real output,
3515 a plain space will do. */
3516 if (output_marks)
3517 *obp++ = '\n';
3518 *obp++ = ' ';
3522 /* Expand the macro, reading arguments as needed,
3523 and push the expansion on the input stack. */
3524 ip->bufp = ibp;
3525 op->bufp = obp;
3526 macroexpand (hp, op);
3528 /* Reexamine input stack, since macroexpand has pushed
3529 a new level on it. */
3530 obp = op->bufp;
3531 RECACHE;
3532 break;
3534 hashcollision:
3536 } /* End hash-table-search loop */
3538 ident_length = hash = 0; /* Stop collecting identifier */
3539 redo_char = 0;
3540 concatenated = 0;
3541 } /* End if (ident_length > 0) */
3542 } /* End switch */
3543 } /* End per-char loop */
3545 /* Come here to return -- but first give an error message
3546 if there was an unterminated successful conditional. */
3547 ending:
3548 if (if_stack != ip->if_stack)
3550 char *str;
3552 switch (if_stack->type)
3554 case T_IF:
3555 str = "if";
3556 break;
3557 case T_IFDEF:
3558 str = "ifdef";
3559 break;
3560 case T_IFNDEF:
3561 str = "ifndef";
3562 break;
3563 case T_ELSE:
3564 str = "else";
3565 break;
3566 case T_ELIF:
3567 str = "elif";
3568 break;
3569 default:
3570 abort ();
3573 error_with_line (line_for_error (if_stack->lineno),
3574 "unterminated `#%s' conditional", str);
3576 if_stack = ip->if_stack;
3580 * Rescan a string into a temporary buffer and return the result
3581 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3583 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3584 * and insert such markers when appropriate. See `rescan' for details.
3585 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3586 * before substitution; it is 0 for other uses.
3588 static FILE_BUF
3589 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3590 U_CHAR *buf, *limit;
3591 int output_marks, assertions;
3593 register FILE_BUF *ip;
3594 FILE_BUF obuf;
3595 int length = limit - buf;
3596 U_CHAR *buf1;
3597 int odepth = indepth;
3598 int save_assertions_flag = assertions_flag;
3600 assertions_flag = assertions;
3602 if (length < 0)
3603 abort ();
3605 /* Set up the input on the input stack. */
3607 buf1 = (U_CHAR *) alloca (length + 1);
3609 register U_CHAR *p1 = buf;
3610 register U_CHAR *p2 = buf1;
3612 while (p1 != limit)
3613 *p2++ = *p1++;
3615 buf1[length] = 0;
3617 /* Set up to receive the output. */
3619 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3620 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3621 obuf.nominal_fname = 0;
3622 obuf.inc = 0;
3623 obuf.dir = 0;
3624 obuf.fname = 0;
3625 obuf.macro = 0;
3626 obuf.if_stack = 0;
3627 obuf.free_ptr = 0;
3628 obuf.system_header_p = 0;
3630 CHECK_DEPTH ({return obuf;});
3632 ++indepth;
3634 ip = &instack[indepth];
3635 ip->fname = 0;
3636 ip->nominal_fname = 0;
3637 ip->nominal_fname_len = 0;
3638 ip->inc = 0;
3639 ip->system_header_p = 0;
3640 ip->macro = 0;
3641 ip->free_ptr = 0;
3642 ip->length = length;
3643 ip->buf = ip->bufp = buf1;
3644 ip->if_stack = if_stack;
3646 ip->lineno = obuf.lineno = 1;
3648 /* Scan the input, create the output. */
3649 rescan (&obuf, output_marks);
3651 /* Pop input stack to original state. */
3652 --indepth;
3654 if (indepth != odepth)
3655 abort ();
3657 assertions_flag = save_assertions_flag;
3658 return obuf;
3662 * Process a # directive. Expects IP->bufp to point after the '#', as in
3663 * `#define foo bar'. Passes to the directive handler
3664 * (do_define, do_include, etc.): the addresses of the 1st and
3665 * last chars of the directive (starting immediately after the #
3666 * keyword), plus op and the keyword table pointer. If the directive
3667 * contains comments it is copied into a temporary buffer sans comments
3668 * and the temporary buffer is passed to the directive handler instead.
3669 * Likewise for backslash-newlines.
3671 * Returns nonzero if this was a known # directive.
3672 * Otherwise, returns zero, without advancing the input pointer.
3675 static int
3676 handle_directive (ip, op)
3677 FILE_BUF *ip, *op;
3679 register U_CHAR *bp, *cp;
3680 register struct directive *kt;
3681 register int ident_length;
3682 U_CHAR *resume_p;
3684 /* Nonzero means we must copy the entire directive
3685 to get rid of comments or backslash-newlines. */
3686 int copy_directive = 0;
3688 U_CHAR *ident, *after_ident;
3690 bp = ip->bufp;
3692 /* Record where the directive started. do_xifdef needs this. */
3693 directive_start = bp - 1;
3695 ignore_escape_flag = 1;
3697 /* Skip whitespace and \-newline. */
3698 while (1) {
3699 if (is_hor_space[*bp]) {
3700 if (*bp != ' ' && *bp != '\t' && pedantic)
3701 pedwarn_strange_white_space (*bp);
3702 bp++;
3703 } else if (*bp == '/') {
3704 if (bp[1] == '\\')
3705 newline_fix (bp + 1);
3706 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3707 break;
3708 ip->bufp = bp + 2;
3709 skip_to_end_of_comment (ip, &ip->lineno, 0);
3710 bp = ip->bufp;
3711 } else if (*bp == '\\' && bp[1] == '\n') {
3712 bp += 2; ip->lineno++;
3713 } else break;
3716 /* Now find end of directive name.
3717 If we encounter a backslash-newline, exchange it with any following
3718 symbol-constituents so that we end up with a contiguous name. */
3720 cp = bp;
3721 while (1) {
3722 if (is_idchar[*cp])
3723 cp++;
3724 else {
3725 if (*cp == '\\')
3726 name_newline_fix (cp);
3727 if (is_idchar[*cp])
3728 cp++;
3729 else break;
3732 ident_length = cp - bp;
3733 ident = bp;
3734 after_ident = cp;
3736 /* A line of just `#' becomes blank. */
3738 if (ident_length == 0 && *after_ident == '\n') {
3739 ip->bufp = after_ident;
3740 return 1;
3743 if (ident_length == 0 || !is_idstart[*ident]) {
3744 U_CHAR *p = ident;
3745 while (is_idchar[*p]) {
3746 if (*p < '0' || *p > '9')
3747 break;
3748 p++;
3750 /* Handle # followed by a line number. */
3751 if (p != ident && !is_idchar[*p]) {
3752 static struct directive line_directive_table[] = {
3753 { 4, do_line, "line", T_LINE},
3755 if (pedantic)
3756 pedwarn ("`#' followed by integer");
3757 after_ident = ident;
3758 kt = line_directive_table;
3759 ignore_escape_flag = 0;
3760 goto old_linenum;
3763 /* Avoid error for `###' and similar cases unless -pedantic. */
3764 if (p == ident) {
3765 while (*p == '#' || is_hor_space[*p]) p++;
3766 if (*p == '\n') {
3767 if (pedantic && !lang_asm)
3768 warning ("invalid preprocessing directive");
3769 return 0;
3773 if (!lang_asm)
3774 error ("invalid preprocessing directive name");
3776 return 0;
3780 * Decode the keyword and call the appropriate expansion
3781 * routine, after moving the input pointer up to the next line.
3783 for (kt = directive_table; kt->length > 0; kt++) {
3784 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3785 register U_CHAR *buf;
3786 register U_CHAR *limit;
3787 int unterminated;
3788 int junk;
3789 int *already_output;
3791 /* Nonzero means do not delete comments within the directive.
3792 #define needs this when -traditional. */
3793 int keep_comments;
3795 old_linenum:
3797 limit = ip->buf + ip->length;
3798 unterminated = 0;
3799 already_output = 0;
3800 keep_comments = traditional && kt->type == T_DEFINE;
3801 /* #import is defined only in Objective C, or when on the NeXT. */
3802 if (kt->type == T_IMPORT
3803 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3804 break;
3806 /* Find the end of this directive (first newline not backslashed
3807 and not in a string or comment).
3808 Set COPY_DIRECTIVE if the directive must be copied
3809 (it contains a backslash-newline or a comment). */
3811 buf = bp = after_ident;
3812 while (bp < limit) {
3813 register U_CHAR c = *bp++;
3814 switch (c) {
3815 case '\\':
3816 if (*bp == '\n') {
3817 ip->lineno++;
3818 copy_directive = 1;
3819 bp++;
3820 } else if (traditional && bp < limit)
3821 bp++;
3822 break;
3824 case '"':
3825 /* "..." is special for #include. */
3826 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3827 while (bp < limit && *bp != '\n') {
3828 if (*bp == '"') {
3829 bp++;
3830 break;
3832 if (*bp == '\\' && bp[1] == '\n') {
3833 ip->lineno++;
3834 copy_directive = 1;
3835 bp++;
3837 bp++;
3839 break;
3841 /* Fall through. */
3842 case '\'':
3843 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3844 /* Don't bother calling the directive if we already got an error
3845 message due to unterminated string. Skip everything and pretend
3846 we called the directive. */
3847 if (unterminated) {
3848 if (traditional) {
3849 /* Traditional preprocessing permits unterminated strings. */
3850 ip->bufp = bp;
3851 goto endloop1;
3853 ip->bufp = bp;
3854 return 1;
3856 break;
3858 /* <...> is special for #include. */
3859 case '<':
3860 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3861 break;
3862 while (bp < limit && *bp != '>' && *bp != '\n') {
3863 if (*bp == '\\' && bp[1] == '\n') {
3864 ip->lineno++;
3865 copy_directive = 1;
3866 bp++;
3868 bp++;
3870 break;
3872 case '/':
3873 if (*bp == '\\')
3874 newline_fix (bp);
3875 if (*bp == '*'
3876 || (cplusplus_comments && *bp == '/')) {
3877 U_CHAR *obp = bp - 1;
3878 ip->bufp = bp + 1;
3879 skip_to_end_of_comment (ip, &ip->lineno, 0);
3880 bp = ip->bufp;
3881 /* No need to copy the directive because of a comment at the end;
3882 just don't include the comment in the directive. */
3883 if (!put_out_comments) {
3884 U_CHAR *p;
3885 for (p = bp; *p == ' ' || *p == '\t'; p++)
3886 continue;
3887 if (*p == '\n') {
3888 bp = obp;
3889 goto endloop1;
3892 /* Don't remove the comments if -traditional. */
3893 if (! keep_comments)
3894 copy_directive++;
3896 break;
3898 case '\f':
3899 case '\r':
3900 case '\v':
3901 if (pedantic)
3902 pedwarn_strange_white_space (c);
3903 break;
3905 case '\n':
3906 --bp; /* Point to the newline */
3907 ip->bufp = bp;
3908 goto endloop1;
3911 ip->bufp = bp;
3913 endloop1:
3914 resume_p = ip->bufp;
3915 /* BP is the end of the directive.
3916 RESUME_P is the next interesting data after the directive.
3917 A comment may come between. */
3919 /* If a directive should be copied through, and -C was given,
3920 pass it through before removing comments. */
3921 if (!no_output && put_out_comments
3922 && ((kt->type == T_DEFINE || kt->type == T_UNDEF)
3923 ? dump_macros == dump_definitions
3924 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3925 : kt->type == T_PRAGMA)) {
3926 int len;
3928 /* Output directive name. */
3929 check_expand (op, kt->length + 2);
3930 /* Make sure # is at the start of a line */
3931 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3932 op->lineno++;
3933 *op->bufp++ = '\n';
3935 *op->bufp++ = '#';
3936 bcopy (kt->name, op->bufp, kt->length);
3937 op->bufp += kt->length;
3939 /* Output arguments. */
3940 len = (bp - buf);
3941 check_expand (op, len);
3942 bcopy (buf, (char *) op->bufp, len);
3943 op->bufp += len;
3944 /* Take account of any (escaped) newlines just output. */
3945 while (--len >= 0)
3946 if (buf[len] == '\n')
3947 op->lineno++;
3949 already_output = &junk;
3950 } /* Don't we need a newline or #line? */
3952 if (copy_directive) {
3953 register U_CHAR *xp = buf;
3954 /* Need to copy entire directive into temp buffer before dispatching */
3956 /* room for directive plus some slop */
3957 cp = (U_CHAR *) alloca (2 * (bp - buf) + 5);
3958 buf = cp;
3960 /* Copy to the new buffer, deleting comments
3961 and backslash-newlines (and whitespace surrounding the latter
3962 if outside of char and string constants). */
3964 while (xp < bp) {
3965 register U_CHAR c = *xp++;
3966 *cp++ = c;
3968 switch (c) {
3969 case '\n':
3970 abort (); /* A bare newline should never part of the line. */
3971 break;
3973 /* <...> is special for #include. */
3974 case '<':
3975 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3976 break;
3977 while (xp < bp && c != '>') {
3978 c = *xp++;
3979 if (c == '\\' && xp < bp && *xp == '\n')
3980 xp++;
3981 else
3982 *cp++ = c;
3984 break;
3986 case '\\':
3987 if (*xp == '\n') {
3988 xp++;
3989 cp--;
3990 if (cp != buf && is_hor_space[cp[-1]]) {
3991 while (cp - 1 != buf && is_hor_space[cp[-2]])
3992 cp--;
3993 SKIP_WHITE_SPACE (xp);
3994 } else if (is_hor_space[*xp]) {
3995 *cp++ = *xp++;
3996 SKIP_WHITE_SPACE (xp);
3998 } else if (traditional && xp < bp) {
3999 *cp++ = *xp++;
4001 break;
4003 case '\'':
4004 case '\"':
4006 int backslash_newlines_p;
4008 register U_CHAR *bp1
4009 = skip_quoted_string (xp - 1, bp, ip->lineno,
4010 NULL_PTR, &backslash_newlines_p,
4011 NULL_PTR);
4012 if (backslash_newlines_p)
4013 while (xp != bp1)
4015 /* With something like:
4017 #define X "a\
4020 we should still remove the backslash-newline
4021 pair as part of phase two. */
4022 if (xp[0] == '\\' && xp[1] == '\n')
4023 xp += 2;
4024 else
4025 *cp++ = *xp++;
4027 else
4028 /* This is the same as the loop above, but taking
4029 advantage of the fact that we know there are no
4030 backslash-newline pairs. */
4031 while (xp != bp1)
4032 *cp++ = *xp++;
4034 break;
4036 case '/':
4037 if (*xp == '*'
4038 || (cplusplus_comments && *xp == '/')) {
4039 ip->bufp = xp + 1;
4040 /* If we already copied the directive through,
4041 already_output != 0 prevents outputting comment now. */
4042 skip_to_end_of_comment (ip, already_output, 0);
4043 if (keep_comments)
4044 while (xp != ip->bufp)
4045 *cp++ = *xp++;
4046 /* Delete or replace the slash. */
4047 else if (traditional)
4048 cp--;
4049 else
4050 cp[-1] = ' ';
4051 xp = ip->bufp;
4056 /* Null-terminate the copy. */
4058 *cp = 0;
4059 } else
4060 cp = bp;
4062 ip->bufp = resume_p;
4064 /* Some directives should be written out for cc1 to process,
4065 just as if they were not defined. And sometimes we're copying
4066 directives through. */
4068 if (!no_output && already_output == 0
4069 && ((kt->type == T_DEFINE || kt->type == T_UNDEF)
4070 ? (int) dump_names <= (int) dump_macros
4071 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4072 : kt->type == T_PRAGMA)) {
4073 int len;
4075 /* Output directive name. */
4076 check_expand (op, kt->length + 1);
4077 *op->bufp++ = '#';
4078 bcopy (kt->name, (char *) op->bufp, kt->length);
4079 op->bufp += kt->length;
4081 if (kt->type == T_DEFINE && dump_macros == dump_names) {
4082 /* Output `#define name' only. */
4083 U_CHAR *xp = buf;
4084 U_CHAR *yp;
4085 SKIP_WHITE_SPACE (xp);
4086 yp = xp;
4087 while (is_idchar[*xp]) xp++;
4088 len = (xp - yp);
4089 check_expand (op, len + 1);
4090 *op->bufp++ = ' ';
4091 bcopy (yp, (char *) op->bufp, len);
4092 } else {
4093 /* Output entire directive. */
4094 len = (cp - buf);
4095 check_expand (op, len);
4096 bcopy (buf, (char *) op->bufp, len);
4098 op->bufp += len;
4101 /* Call the appropriate directive handler. buf now points to
4102 either the appropriate place in the input buffer, or to
4103 the temp buffer if it was necessary to make one. cp
4104 points to the first char after the contents of the (possibly
4105 copied) directive, in either case. */
4106 (*kt->func) (buf, cp, op, kt);
4107 check_expand (op, ip->length - (ip->bufp - ip->buf));
4109 return 1;
4113 /* It is deliberate that we don't warn about undefined directives.
4114 That is the responsibility of cc1. */
4115 return 0;
4118 static struct tm *
4119 timestamp ()
4121 static struct tm tmbuf;
4122 if (! tmbuf.tm_mday) {
4123 time_t t = time ((time_t *) 0);
4124 struct tm *tm = localtime (&t);
4125 if (tm)
4126 tmbuf = *tm;
4127 else {
4128 /* Use 0000-01-01 00:00:00 if local time is not available. */
4129 tmbuf.tm_year = -1900;
4130 tmbuf.tm_mday = 1;
4133 return &tmbuf;
4136 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4137 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4141 * expand things like __FILE__. Place the expansion into the output
4142 * buffer *without* rescanning.
4145 static void
4146 special_symbol (hp, op)
4147 HASHNODE *hp;
4148 FILE_BUF *op;
4150 char *buf;
4151 int i, len;
4152 int true_indepth;
4153 FILE_BUF *ip = NULL;
4154 struct tm *timebuf;
4156 int paren = 0; /* For special `defined' keyword */
4158 if (pcp_outfile && pcp_inside_if
4159 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4160 error ("Predefined macro `%s' used inside `#if' during precompilation",
4161 hp->name);
4163 for (i = indepth; i >= 0; i--)
4164 if (instack[i].fname != NULL) {
4165 ip = &instack[i];
4166 break;
4168 if (ip == NULL) {
4169 error ("cccp error: not in any file?!");
4170 return; /* the show must go on */
4173 switch (hp->type) {
4174 case T_FILE:
4175 case T_BASE_FILE:
4177 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4178 char *string = p->nominal_fname;
4180 if (string)
4182 size_t string_len = p->nominal_fname_len;
4183 buf = (char *) alloca (3 + 4 * string_len);
4184 quote_string (buf, string, string_len);
4186 else
4187 buf = "\"\"";
4189 break;
4192 case T_INCLUDE_LEVEL:
4193 true_indepth = 0;
4194 for (i = indepth; i >= 0; i--)
4195 if (instack[i].fname != NULL)
4196 true_indepth++;
4198 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4199 sprintf (buf, "%d", true_indepth - 1);
4200 break;
4202 case T_VERSION:
4203 buf = (char *) alloca (3 + strlen (version_string));
4204 sprintf (buf, "\"%s\"", version_string);
4205 break;
4207 #ifndef NO_BUILTIN_SIZE_TYPE
4208 case T_SIZE_TYPE:
4209 buf = SIZE_TYPE;
4210 break;
4211 #endif
4213 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4214 case T_PTRDIFF_TYPE:
4215 buf = PTRDIFF_TYPE;
4216 break;
4217 #endif
4219 case T_WCHAR_TYPE:
4220 buf = wchar_type;
4221 break;
4223 case T_USER_LABEL_PREFIX_TYPE:
4224 buf = user_label_prefix;
4225 break;
4227 case T_REGISTER_PREFIX_TYPE:
4228 buf = REGISTER_PREFIX;
4229 break;
4231 case T_IMMEDIATE_PREFIX_TYPE:
4232 buf = IMMEDIATE_PREFIX;
4233 break;
4235 case T_CONST:
4236 buf = hp->value.cpval;
4237 #ifdef STDC_0_IN_SYSTEM_HEADERS
4238 if (ip->system_header_p
4239 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4240 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4241 buf = "0";
4242 #endif
4243 if (pcp_inside_if && pcp_outfile)
4244 /* Output a precondition for this macro use */
4245 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4246 break;
4248 case T_SPECLINE:
4249 buf = (char *) alloca (10);
4250 sprintf (buf, "%d", ip->lineno);
4251 break;
4253 case T_DATE:
4254 case T_TIME:
4255 buf = (char *) alloca (20);
4256 timebuf = timestamp ();
4257 if (hp->type == T_DATE)
4258 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4259 timebuf->tm_mday, timebuf->tm_year + 1900);
4260 else
4261 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4262 timebuf->tm_sec);
4263 break;
4265 case T_SPEC_DEFINED:
4266 buf = " 0 "; /* Assume symbol is not defined */
4267 ip = &instack[indepth];
4268 SKIP_WHITE_SPACE (ip->bufp);
4269 if (*ip->bufp == '(') {
4270 paren++;
4271 ip->bufp++; /* Skip over the paren */
4272 SKIP_WHITE_SPACE (ip->bufp);
4275 if (!is_idstart[*ip->bufp])
4276 goto oops;
4277 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4278 goto oops;
4279 if ((hp = lookup (ip->bufp, -1, -1))) {
4280 if (pcp_outfile && pcp_inside_if
4281 && (hp->type == T_CONST
4282 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4283 /* Output a precondition for this macro use. */
4284 fprintf (pcp_outfile, "#define %s\n", hp->name);
4285 if (hp->type == T_POISON) {
4286 error("attempt to use poisoned `%s'.", hp->name);
4287 buf = " 0 ";
4288 } else {
4289 buf = " 1 ";
4292 else
4293 if (pcp_outfile && pcp_inside_if) {
4294 /* Output a precondition for this macro use */
4295 U_CHAR *cp = ip->bufp;
4296 fprintf (pcp_outfile, "#undef ");
4297 while (is_idchar[*cp]) /* Ick! */
4298 fputc (*cp++, pcp_outfile);
4299 putc ('\n', pcp_outfile);
4301 while (is_idchar[*ip->bufp])
4302 ++ip->bufp;
4303 SKIP_WHITE_SPACE (ip->bufp);
4304 if (paren) {
4305 if (*ip->bufp != ')')
4306 goto oops;
4307 ++ip->bufp;
4309 break;
4311 case T_POISON:
4312 error("attempt to use poisoned `%s'.", hp->name);
4313 buf = " 0 "; /* Consider poisoned symbol to not be defined */
4314 break;
4316 oops:
4318 error ("`defined' without an identifier");
4319 break;
4321 default:
4322 error ("cccp error: invalid special hash type"); /* time for gdb */
4323 abort ();
4325 len = strlen (buf);
4326 check_expand (op, len);
4327 bcopy (buf, (char *) op->bufp, len);
4328 op->bufp += len;
4330 return;
4334 /* Routines to handle #directives */
4336 /* Handle #include and #import.
4337 This function expects to see "fname" or <fname> on the input. */
4339 static int
4340 do_include (buf, limit, op, keyword)
4341 U_CHAR *buf, *limit;
4342 FILE_BUF *op;
4343 struct directive *keyword;
4345 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4346 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4347 static int import_warning = 0;
4348 char *fname; /* Dynamically allocated fname buffer */
4349 char *pcftry;
4350 char *pcfname;
4351 char *fbeg, *fend; /* Beginning and end of fname */
4352 U_CHAR *fin;
4354 struct file_name_list *search_start = include; /* Chain of dirs to search */
4355 struct file_name_list *dsp; /* First in chain, if #include "..." */
4356 struct file_name_list *searchptr = 0;
4357 size_t flen;
4359 int f = -3; /* file number */
4360 struct include_file *inc = 0;
4362 int retried = 0; /* Have already tried macro
4363 expanding the include line*/
4364 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4365 #ifdef VMS
4366 int vaxc_include = 0; /* 1 for token without punctuation */
4367 #endif
4368 int pcf = -1;
4369 char *pcfbuf;
4370 char *pcfbuflimit;
4371 int pcfnum;
4373 if (pedantic && !instack[indepth].system_header_p)
4375 if (importing)
4376 pedwarn ("ANSI C does not allow `#import'");
4377 if (skip_dirs)
4378 pedwarn ("ANSI C does not allow `#include_next'");
4381 if (importing && warn_import && !inhibit_warnings
4382 && !instack[indepth].system_header_p && !import_warning) {
4383 import_warning = 1;
4384 warning ("using `#import' is not recommended");
4385 notice ("The fact that a certain header file need not be processed more than once\n\
4386 should be indicated in the header file, not where it is used.\n\
4387 The best way to do this is with a conditional of this form:\n\
4389 #ifndef _FOO_H_INCLUDED\n\
4390 #define _FOO_H_INCLUDED\n\
4391 ... <real contents of file> ...\n\
4392 #endif /* Not _FOO_H_INCLUDED */\n\
4394 Then users can use `#include' any number of times.\n\
4395 GNU C automatically avoids processing the file more than once\n\
4396 when it is equipped with such a conditional.\n");
4399 get_filename:
4401 fin = buf;
4402 SKIP_WHITE_SPACE (fin);
4403 /* Discard trailing whitespace so we can easily see
4404 if we have parsed all the significant chars we were given. */
4405 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4406 fbeg = fend = (char *) alloca (limit - fin);
4408 switch (*fin++) {
4409 case '\"':
4411 FILE_BUF *fp;
4412 /* Copy the operand text, concatenating the strings. */
4414 for (;;) {
4415 for (;;) {
4416 if (fin == limit)
4417 goto invalid_include_file_name;
4418 *fend = *fin++;
4419 if (*fend == '"')
4420 break;
4421 fend++;
4423 if (fin == limit)
4424 break;
4425 /* If not at the end, there had better be another string. */
4426 /* Skip just horiz space, and don't go past limit. */
4427 while (fin != limit && is_hor_space[*fin]) fin++;
4428 if (fin != limit && *fin == '\"')
4429 fin++;
4430 else
4431 goto fail;
4435 /* We have "filename". Figure out directory this source
4436 file is coming from and put it on the front of the list. */
4438 /* If -I- was specified, don't search current dir, only spec'd ones. */
4439 if (ignore_srcdir) break;
4441 for (fp = &instack[indepth]; fp >= instack; fp--)
4443 int n;
4444 char *nam;
4446 if ((nam = fp->nominal_fname) != NULL) {
4447 /* Found a named file. Figure out dir of the file,
4448 and put it in front of the search list. */
4449 dsp = ((struct file_name_list *)
4450 alloca (sizeof (struct file_name_list)
4451 + fp->nominal_fname_len));
4452 strcpy (dsp->fname, nam);
4453 simplify_filename (dsp->fname);
4454 nam = base_name (dsp->fname);
4455 *nam = 0;
4456 #ifdef VMS
4457 /* for hack_vms_include_specification(), a local
4458 dir specification must start with "./" on VMS. */
4459 if (nam == dsp->fname)
4461 *nam++ = '.';
4462 *nam++ = '/';
4463 *nam = 0;
4465 #endif
4466 /* But for efficiency's sake, do not insert the dir
4467 if it matches the search list's first dir. */
4468 dsp->next = search_start;
4469 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4470 search_start = dsp;
4471 n = nam - dsp->fname;
4472 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4473 max_include_len = n + INCLUDE_LEN_FUDGE;
4475 dsp[0].got_name_map = 0;
4476 break;
4479 break;
4482 case '<':
4483 while (fin != limit && *fin != '>')
4484 *fend++ = *fin++;
4485 if (*fin == '>' && fin + 1 == limit) {
4486 angle_brackets = 1;
4487 /* If -I-, start with the first -I dir after the -I-. */
4488 search_start = first_bracket_include;
4489 break;
4491 goto fail;
4493 default:
4494 #ifdef VMS
4496 * Support '#include xyz' like VAX-C to allow for easy use of all the
4497 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4498 * code from case '<' is repeated here) and generates a warning.
4499 * (Note: macro expansion of `xyz' takes precedence.)
4501 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4502 the pre-decrement outside of the macro. */
4503 if (retried && (--fin, ISALPHA(*(U_CHAR *) (fin)))) {
4504 while (fin != limit && (!ISSPACE(*fin)))
4505 *fend++ = *fin++;
4506 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4507 vaxc_include = 1;
4508 if (fin == limit) {
4509 angle_brackets = 1;
4510 /* If -I-, start with the first -I dir after the -I-. */
4511 search_start = first_bracket_include;
4512 break;
4515 #endif
4517 fail:
4518 if (! retried) {
4519 /* Expand buffer and then remove any newline markers.
4520 We can't just tell expand_to_temp_buffer to omit the markers,
4521 since it would put extra spaces in include file names. */
4522 FILE_BUF trybuf;
4523 U_CHAR *src;
4524 int errors_before_expansion = errors;
4525 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4526 if (errors != errors_before_expansion) {
4527 free (trybuf.buf);
4528 goto invalid_include_file_name;
4530 src = trybuf.buf;
4531 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4532 limit = buf;
4533 while (src != trybuf.bufp) {
4534 switch ((*limit++ = *src++)) {
4535 case '\n':
4536 limit--;
4537 src++;
4538 break;
4540 case '\'':
4541 case '\"':
4543 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4544 NULL_PTR, NULL_PTR, NULL_PTR);
4545 while (src != src1)
4546 *limit++ = *src++;
4548 break;
4551 *limit = 0;
4552 free (trybuf.buf);
4553 retried = 1;
4554 goto get_filename;
4557 invalid_include_file_name:
4558 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4559 return 0;
4562 /* For #include_next, skip in the search path
4563 past the dir in which the containing file was found. */
4564 if (skip_dirs) {
4565 FILE_BUF *fp;
4566 for (fp = &instack[indepth]; fp >= instack; fp--)
4567 if (fp->fname != NULL) {
4568 /* fp->dir is null if the containing file was specified
4569 with an absolute file name. In that case, don't skip anything. */
4570 if (fp->dir)
4571 search_start = fp->dir->next;
4572 break;
4576 *fend = 0;
4577 flen = simplify_filename (fbeg);
4579 if (flen == 0)
4581 error ("empty file name in `#%s'", keyword->name);
4582 return 0;
4585 /* Allocate this permanently, because it gets stored in the definitions
4586 of macros. */
4587 fname = xmalloc (max_include_len + flen + 1);
4588 /* + 1 above for terminating null. */
4590 system_include_depth += angle_brackets;
4592 /* If specified file name is absolute, just open it. */
4594 if (absolute_filename (fbeg)) {
4595 strcpy (fname, fbeg);
4596 f = open_include_file (fname, NULL_PTR, importing, &inc);
4597 } else {
4599 struct bypass_dir {
4600 struct bypass_dir *next;
4601 char *fname;
4602 struct file_name_list *searchptr;
4603 } **bypass_slot = 0;
4605 /* Search directory path, trying to open the file.
4606 Copy each filename tried into FNAME. */
4608 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4610 if (searchptr == first_bracket_include) {
4611 /* Go to bypass directory if we know we've seen this file before. */
4612 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4613 struct bypass_dir *p;
4614 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4615 INCLUDE_HASHSIZE)];
4616 for (p = *bypass_slot; p; p = p->next)
4617 if (!strcmp (fbeg, p->fname)) {
4618 searchptr = p->searchptr;
4619 bypass_slot = 0;
4620 break;
4624 #ifdef VMS
4625 /* Change this 1/2 Unix 1/2 VMS file specification into a
4626 full VMS file specification */
4627 if (searchptr->fname[0])
4629 strcpy (fname, searchptr->fname);
4630 if (fname[strlen (fname) - 1] == ':')
4632 char *slashp;
4633 slashp = strchr (fbeg, '/');
4635 /* start at root-dir of logical device if no path given. */
4636 if (slashp == 0)
4637 strcat (fname, "[000000]");
4639 strcat (fname, fbeg);
4641 /* Fix up the filename */
4642 hack_vms_include_specification (fname, vaxc_include);
4644 else
4646 /* This is a normal VMS filespec, so use it unchanged. */
4647 strcpy (fname, fbeg);
4648 /* if it's '#include filename', add the missing .h */
4649 if (vaxc_include && index(fname,'.')==NULL)
4650 strcat (fname, ".h");
4652 #else
4653 strcpy (fname, searchptr->fname);
4654 strcat (fname, fbeg);
4655 #endif /* VMS */
4656 f = open_include_file (fname, searchptr, importing, &inc);
4657 if (f != -1) {
4658 if (bypass_slot && searchptr != first_bracket_include) {
4659 /* This is the first time we found this include file,
4660 and we found it after first_bracket_include.
4661 Record its location so that we can bypass to here next time. */
4662 struct bypass_dir *p
4663 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4664 p->next = *bypass_slot;
4665 p->fname = fname + strlen (searchptr->fname);
4666 p->searchptr = searchptr;
4667 *bypass_slot = p;
4669 break;
4671 #ifdef VMS
4672 /* Our VMS hacks can produce invalid filespecs, so don't worry
4673 about errors other than EACCES. */
4674 if (errno == EACCES)
4675 break;
4676 #else
4677 if (errno != ENOENT && errno != ENOTDIR)
4678 break;
4679 #endif
4684 if (f < 0) {
4686 if (f == -2) {
4687 /* The file was already included. */
4689 /* If generating dependencies and -MG was specified, we assume missing
4690 files are leaf files, living in the same directory as the source file
4691 or other similar place; these missing files may be generated from
4692 other files and may not exist yet (eg: y.tab.h). */
4693 } else if (print_deps_missing_files
4694 && (system_include_depth != 0) < print_deps)
4696 /* If it was requested as a system header file,
4697 then assume it belongs in the first place to look for such. */
4698 if (angle_brackets)
4700 if (search_start) {
4701 char *p = (char *) alloca (strlen (search_start->fname)
4702 + strlen (fbeg) + 1);
4703 strcpy (p, search_start->fname);
4704 strcat (p, fbeg);
4705 deps_output (p, ' ');
4708 else
4710 /* Otherwise, omit the directory, as if the file existed
4711 in the directory with the source. */
4712 deps_output (fbeg, ' ');
4715 /* If -M was specified, and this header file won't be added to the
4716 dependency list, then don't count this as an error, because we can
4717 still produce correct output. Otherwise, we can't produce correct
4718 output, because there may be dependencies we need inside the missing
4719 file, and we don't know what directory this missing file exists in. */
4720 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4721 warning ("No include path in which to find %s", fbeg);
4722 else if (f != -3)
4723 error_from_errno (fbeg);
4724 else
4725 error ("No include path in which to find %s", fbeg);
4727 } else {
4729 /* Actually process the file. */
4731 pcftry = (char *) alloca (strlen (fname) + 30);
4732 pcfbuf = 0;
4733 pcfnum = 0;
4735 if (!no_precomp)
4737 do {
4738 sprintf (pcftry, "%s%d", fname, pcfnum++);
4740 pcf = open (pcftry, O_RDONLY, 0666);
4741 if (pcf != -1)
4743 struct stat s;
4745 if (fstat (pcf, &s) != 0)
4746 pfatal_with_name (pcftry);
4747 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4748 || inc->st.st_dev != s.st_dev)
4750 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4751 /* Don't need it any more. */
4752 close (pcf);
4754 else
4756 /* Don't need it at all. */
4757 close (pcf);
4758 break;
4761 } while (pcf != -1 && !pcfbuf);
4764 /* Actually process the file */
4765 if (pcfbuf) {
4766 pcfname = xstrdup (pcftry);
4767 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) fname, op);
4769 else
4770 finclude (f, inc, op, is_system_include (fname), searchptr);
4773 system_include_depth -= angle_brackets;
4775 return 0;
4778 /* Return nonzero if the given FILENAME is an absolute pathname which
4779 designates a file within one of the known "system" include file
4780 directories. We assume here that if the given FILENAME looks like
4781 it is the name of a file which resides either directly in a "system"
4782 include file directory, or within any subdirectory thereof, then the
4783 given file must be a "system" include file. This function tells us
4784 if we should suppress pedantic errors/warnings for the given FILENAME.
4786 The value is 2 if the file is a C-language system header file
4787 for which C++ should (on most systems) assume `extern "C"'. */
4789 static int
4790 is_system_include (filename)
4791 register char *filename;
4793 struct file_name_list *searchptr;
4795 for (searchptr = first_system_include; searchptr;
4796 searchptr = searchptr->next)
4797 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4798 return searchptr->c_system_include_path + 1;
4799 return 0;
4802 /* Yield the non-directory suffix of a file name. */
4804 static char *
4805 base_name (fname)
4806 char *fname;
4808 char *s = fname;
4809 char *p;
4810 #if defined (__MSDOS__) || defined (_WIN32)
4811 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4812 #endif
4813 #ifdef VMS
4814 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4815 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4816 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4817 if (s != fname)
4818 return s;
4819 #endif
4820 if ((p = rindex (s, '/'))) s = p + 1;
4821 #ifdef DIR_SEPARATOR
4822 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4823 #endif
4824 return s;
4827 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4829 static int
4830 absolute_filename (filename)
4831 char *filename;
4833 #if defined (__MSDOS__) \
4834 || (defined (_WIN32) && !defined (__CYGWIN__) && !defined (_UWIN))
4835 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4836 #endif
4837 #if defined (__CYGWIN__)
4838 /* At present, any path that begins with a drive spec is absolute. */
4839 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4840 #endif
4841 #ifdef VMS
4842 if (index (filename, ':') != 0) return 1;
4843 #endif
4844 if (filename[0] == '/') return 1;
4845 #ifdef DIR_SEPARATOR
4846 if (filename[0] == DIR_SEPARATOR) return 1;
4847 #endif
4848 return 0;
4851 /* Returns whether or not a given character is a directory separator.
4852 Used by simplify_filename. */
4853 static inline int is_dir_separator PROTO ((int));
4855 static inline
4857 is_dir_separator(ch)
4858 char ch;
4860 return (ch == DIR_SEPARATOR)
4861 #if defined (DIR_SEPARATOR_2)
4862 || (ch == DIR_SEPARATOR_2)
4863 #endif
4867 /* Remove unnecessary characters from FILENAME in place,
4868 to avoid unnecessary filename aliasing.
4869 Return the length of the resulting string.
4871 Do only the simplifications allowed by Posix.
4872 It is OK to miss simplifications on non-Posix hosts,
4873 since this merely leads to suboptimal results. */
4875 static size_t
4876 simplify_filename (filename)
4877 char *filename;
4879 register char *from = filename;
4880 register char *to = filename;
4881 char *to0;
4883 /* Remove redundant initial /s. */
4884 if (is_dir_separator (*from))
4886 *to++ = DIR_SEPARATOR;
4887 if (is_dir_separator (*++from))
4889 if (is_dir_separator (*++from))
4891 /* 3 or more initial /s are equivalent to 1 /. */
4892 while (is_dir_separator (*++from))
4893 continue;
4895 else
4897 /* On some hosts // differs from /; Posix allows this. */
4898 *to++ = DIR_SEPARATOR;
4903 to0 = to;
4905 for (;;)
4907 #ifndef VMS
4908 if (from[0] == '.' && from[1] == '/')
4909 from += 2;
4910 else
4911 #endif
4913 /* Copy this component and trailing DIR_SEPARATOR, if any. */
4914 while (!is_dir_separator (*to++ = *from++))
4916 if (!to[-1])
4918 /* Trim . component at end of nonempty name. */
4919 to -= filename <= to - 3 && to[-3] == DIR_SEPARATOR && to[-2] == '.';
4921 /* Trim unnecessary trailing /s. */
4922 while (to0 < --to && to[-1] == DIR_SEPARATOR)
4923 continue;
4925 *to = 0;
4926 return to - filename;
4929 #if defined(DIR_SEPARATOR_2)
4930 /* Simplify to one directory separator. */
4931 to[-1] = DIR_SEPARATOR;
4932 #endif
4935 /* Skip /s after a /. */
4936 while (is_dir_separator (*from))
4937 from++;
4941 /* The file_name_map structure holds a mapping of file names for a
4942 particular directory. This mapping is read from the file named
4943 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4944 map filenames on a file system with severe filename restrictions,
4945 such as DOS. The format of the file name map file is just a series
4946 of lines with two tokens on each line. The first token is the name
4947 to map, and the second token is the actual name to use. */
4949 struct file_name_map
4951 struct file_name_map *map_next;
4952 char *map_from;
4953 char *map_to;
4956 #define FILE_NAME_MAP_FILE "header.gcc"
4958 /* Read a space delimited string of unlimited length from a stdio
4959 file. */
4961 static char *
4962 read_filename_string (ch, f)
4963 int ch;
4964 FILE *f;
4966 char *alloc, *set;
4967 int len;
4969 len = 20;
4970 set = alloc = xmalloc (len + 1);
4971 if (! is_space[ch])
4973 *set++ = ch;
4974 while ((ch = getc (f)) != EOF && ! is_space[ch])
4976 if (set - alloc == len)
4978 len *= 2;
4979 alloc = xrealloc (alloc, len + 1);
4980 set = alloc + len / 2;
4982 *set++ = ch;
4985 *set = '\0';
4986 ungetc (ch, f);
4987 return alloc;
4990 /* Read the file name map file for DIRNAME.
4991 If DIRNAME is empty, read the map file for the working directory;
4992 otherwise DIRNAME must end in '/'. */
4994 static struct file_name_map *
4995 read_name_map (dirname)
4996 char *dirname;
4998 /* This structure holds a linked list of file name maps, one per
4999 directory. */
5000 struct file_name_map_list
5002 struct file_name_map_list *map_list_next;
5003 char *map_list_name;
5004 struct file_name_map *map_list_map;
5006 static struct file_name_map_list *map_list;
5007 register struct file_name_map_list *map_list_ptr;
5008 char *name;
5009 FILE *f;
5010 size_t dirlen;
5012 for (map_list_ptr = map_list; map_list_ptr;
5013 map_list_ptr = map_list_ptr->map_list_next)
5014 if (! strcmp (map_list_ptr->map_list_name, dirname))
5015 return map_list_ptr->map_list_map;
5017 map_list_ptr = ((struct file_name_map_list *)
5018 xmalloc (sizeof (struct file_name_map_list)));
5019 map_list_ptr->map_list_name = xstrdup (dirname);
5020 map_list_ptr->map_list_map = NULL;
5022 dirlen = strlen (dirname);
5023 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
5024 strcpy (name, dirname);
5025 strcat (name, FILE_NAME_MAP_FILE);
5026 f = fopen (name, "r");
5027 if (!f)
5028 map_list_ptr->map_list_map = NULL;
5029 else
5031 int ch;
5033 while ((ch = getc (f)) != EOF)
5035 char *from, *to;
5036 struct file_name_map *ptr;
5037 size_t tolen;
5039 if (is_space[ch])
5040 continue;
5041 from = read_filename_string (ch, f);
5042 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5044 to = read_filename_string (ch, f);
5046 simplify_filename (from);
5047 tolen = simplify_filename (to);
5049 ptr = ((struct file_name_map *)
5050 xmalloc (sizeof (struct file_name_map)));
5051 ptr->map_from = from;
5053 /* Make the real filename absolute. */
5054 if (absolute_filename (to))
5055 ptr->map_to = to;
5056 else
5058 ptr->map_to = xmalloc (dirlen + tolen + 1);
5059 strcpy (ptr->map_to, dirname);
5060 strcat (ptr->map_to, to);
5061 free (to);
5064 ptr->map_next = map_list_ptr->map_list_map;
5065 map_list_ptr->map_list_map = ptr;
5067 while ((ch = getc (f)) != '\n')
5068 if (ch == EOF)
5069 break;
5071 fclose (f);
5074 map_list_ptr->map_list_next = map_list;
5075 map_list = map_list_ptr;
5077 return map_list_ptr->map_list_map;
5080 /* Try to open include file FILENAME. SEARCHPTR is the directory
5081 being tried from the include file search path.
5082 IMPORTING is "" if we are importing, null otherwise.
5083 Return -2 if found, either a matching name or a matching inode.
5084 Otherwise, open the file and return a file descriptor if successful
5085 or -1 if unsuccessful.
5086 Unless unsuccessful, put a descriptor of the included file into *PINC.
5087 This function maps filenames on file systems based on information read by
5088 read_name_map. */
5090 static int
5091 open_include_file (filename, searchptr, importing, pinc)
5092 char *filename;
5093 struct file_name_list *searchptr;
5094 U_CHAR *importing;
5095 struct include_file **pinc;
5097 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
5098 int fd = -2;
5100 /* Look up FNAME in include_hashtab. */
5101 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
5102 strlen (fname),
5103 INCLUDE_HASHSIZE)];
5104 struct include_file *inc, *head = *phead;
5105 for (inc = head; inc; inc = inc->next)
5106 if (!strcmp (fname, inc->fname))
5107 break;
5109 if (!inc
5110 || ! inc->control_macro
5111 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
5113 fd = open (fname, O_RDONLY, 0);
5115 if (fd < 0)
5117 #ifdef VMS
5118 /* if #include <dir/file> fails, try again with hacked spec. */
5119 if (!hack_vms_include_specification (fname, 0))
5120 return fd;
5121 fd = open (fname, O_RDONLY, 0);
5122 if (fd < 0)
5123 #endif
5124 return fd;
5127 if (!inc) {
5128 /* FNAME was not in include_hashtab; insert a new entry. */
5129 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
5130 inc->next = head;
5131 inc->fname = fname;
5132 inc->control_macro = 0;
5133 inc->deps_output = 0;
5134 if (fstat (fd, &inc->st) != 0)
5135 pfatal_with_name (fname);
5136 *phead = inc;
5138 /* Look for another file with the same inode and device. */
5139 if (lookup_ino_include (inc)
5140 && inc->control_macro
5141 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
5142 close (fd);
5143 fd = -2;
5147 /* For -M, add this file to the dependencies. */
5148 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
5149 inc->deps_output = 1;
5150 deps_output (fname, ' ');
5153 /* Handle -H option. */
5154 if (print_include_names)
5155 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5158 if (importing)
5159 inc->control_macro = importing;
5161 *pinc = inc;
5162 return fd;
5165 /* Return the remapped name of the include file FILENAME.
5166 SEARCHPTR is the directory being tried from the include file path. */
5168 static char *
5169 remap_include_file (filename, searchptr)
5170 char *filename;
5171 struct file_name_list *searchptr;
5173 register struct file_name_map *map;
5174 register char *from;
5176 if (searchptr)
5178 if (! searchptr->got_name_map)
5180 searchptr->name_map = read_name_map (searchptr->fname);
5181 searchptr->got_name_map = 1;
5184 /* Check the mapping for the directory we are using. */
5185 from = filename + strlen (searchptr->fname);
5186 for (map = searchptr->name_map; map; map = map->map_next)
5187 if (! strcmp (map->map_from, from))
5188 return map->map_to;
5191 from = base_name (filename);
5193 if (from != filename || !searchptr)
5195 /* Try to find a mapping file for the particular directory we are
5196 looking in. Thus #include <sys/types.h> will look up sys/types.h
5197 in /usr/include/header.gcc and look up types.h in
5198 /usr/include/sys/header.gcc. */
5200 char *dir = (char *) alloca (from - filename + 1);
5201 bcopy (filename, dir, from - filename);
5202 dir[from - filename] = '\0';
5204 for (map = read_name_map (dir); map; map = map->map_next)
5205 if (! strcmp (map->map_from, from))
5206 return map->map_to;
5209 return filename;
5212 /* Insert INC into the include file table, hashed by device and inode number.
5213 If a file with different name but same dev+ino was already in the table,
5214 return 1 and set INC's control macro to the already-known macro. */
5216 static int
5217 lookup_ino_include (inc)
5218 struct include_file *inc;
5220 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5221 % INCLUDE_HASHSIZE);
5222 struct include_file *i = include_ino_hashtab[hash];
5223 inc->next_ino = i;
5224 include_ino_hashtab[hash] = inc;
5226 for (; i; i = i->next_ino)
5227 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5228 && inc->st.st_dev == i->st.st_dev) {
5229 inc->control_macro = i->control_macro;
5230 return 1;
5233 return 0;
5236 /* Process file descriptor F, which corresponds to include file INC,
5237 with output to OP.
5238 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5239 "system" include directories (as decided by the `is_system_include'
5240 function above).
5241 DIRPTR is the link in the dir path through which this file was found,
5242 or 0 if the file name was absolute. */
5244 static void
5245 finclude (f, inc, op, system_header_p, dirptr)
5246 int f;
5247 struct include_file *inc;
5248 FILE_BUF *op;
5249 int system_header_p;
5250 struct file_name_list *dirptr;
5252 char *fname = inc->fname;
5253 int i;
5254 FILE_BUF *fp; /* For input stack frame */
5255 int missing_newline = 0;
5257 CHECK_DEPTH (return;);
5259 fp = &instack[indepth + 1];
5260 bzero ((char *) fp, sizeof (FILE_BUF));
5261 fp->nominal_fname = fp->fname = fname;
5262 fp->nominal_fname_len = strlen (fname);
5263 fp->inc = inc;
5264 fp->length = 0;
5265 fp->lineno = 1;
5266 fp->if_stack = if_stack;
5267 fp->system_header_p = system_header_p;
5268 fp->dir = dirptr;
5270 if (S_ISREG (inc->st.st_mode)) {
5271 size_t s = (size_t) inc->st.st_size;
5272 if (s != inc->st.st_size || s + 2 < s)
5273 memory_full ();
5274 fp->buf = (U_CHAR *) xmalloc (s + 2);
5275 fp->bufp = fp->buf;
5277 /* Read the file contents, knowing that s is an upper bound
5278 on the number of bytes we can read. */
5279 fp->length = safe_read (f, (char *) fp->buf, s);
5280 if (fp->length < 0) goto nope;
5282 else if (S_ISDIR (inc->st.st_mode)) {
5283 error ("directory `%s' specified in #include", fname);
5284 close (f);
5285 return;
5286 } else {
5287 /* Cannot count its file size before reading.
5288 First read the entire file into heap and
5289 copy them into buffer on stack. */
5291 int bsize = 2000;
5292 int st_size = 0;
5294 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5296 for (;;) {
5297 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5298 if (i < 0)
5299 goto nope; /* error! */
5300 st_size += i;
5301 if (st_size != bsize)
5302 break; /* End of file */
5303 bsize *= 2;
5304 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5306 fp->bufp = fp->buf;
5307 fp->length = st_size;
5310 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5311 /* Backslash-newline at end is not good enough. */
5312 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5313 fp->buf[fp->length++] = '\n';
5314 missing_newline = 1;
5316 fp->buf[fp->length] = '\0';
5318 /* Close descriptor now, so nesting does not use lots of descriptors. */
5319 close (f);
5321 /* Must do this before calling trigraph_pcp, so that the correct file name
5322 will be printed in warning messages. */
5324 indepth++;
5325 input_file_stack_tick++;
5327 if (!no_trigraphs)
5328 trigraph_pcp (fp);
5330 if (warn_white_space)
5331 check_white_space (fp);
5333 output_line_directive (fp, op, 0, enter_file);
5334 rescan (op, 0);
5336 if (missing_newline)
5337 fp->lineno--;
5339 if (pedantic && missing_newline)
5340 pedwarn ("file does not end in newline");
5342 indepth--;
5343 input_file_stack_tick++;
5344 output_line_directive (&instack[indepth], op, 0, leave_file);
5345 free (fp->buf);
5346 return;
5348 nope:
5350 perror_with_name (fname);
5351 close (f);
5352 free (fp->buf);
5355 /* Record that inclusion of the include file INC
5356 should be controlled by the macro named MACRO_NAME.
5357 This means that trying to include the file again
5358 will do something if that macro is defined. */
5360 static void
5361 record_control_macro (inc, macro_name)
5362 struct include_file *inc;
5363 U_CHAR *macro_name;
5365 if (!inc->control_macro || inc->control_macro[0])
5366 inc->control_macro = macro_name;
5369 /* Load the specified precompiled header into core, and verify its
5370 preconditions. PCF indicates the file descriptor to read, which must
5371 be a regular file. *ST is its file status.
5372 FNAME indicates the file name of the original header.
5373 *LIMIT will be set to an address one past the end of the file.
5374 If the preconditions of the file are not satisfied, the buffer is
5375 freed and we return 0. If the preconditions are satisfied, return
5376 the address of the buffer following the preconditions. The buffer, in
5377 this case, should never be freed because various pieces of it will
5378 be referred to until all precompiled strings are output at the end of
5379 the run. */
5381 static char *
5382 check_precompiled (pcf, st, fname, limit)
5383 int pcf;
5384 struct stat *st;
5385 char *fname ATTRIBUTE_UNUSED;
5386 char **limit;
5388 int length = 0;
5389 char *buf;
5390 char *cp;
5392 if (pcp_outfile)
5393 return 0;
5395 if (S_ISREG (st->st_mode))
5397 size_t s = (size_t) st->st_size;
5398 if (s != st->st_size || s + 2 < s)
5399 memory_full ();
5400 buf = xmalloc (s + 2);
5401 length = safe_read (pcf, buf, s);
5402 if (length < 0)
5403 goto nope;
5405 else
5406 abort ();
5408 if (length > 0 && buf[length-1] != '\n')
5409 buf[length++] = '\n';
5410 buf[length] = '\0';
5412 *limit = buf + length;
5414 /* File is in core. Check the preconditions. */
5415 if (!check_preconditions (buf))
5416 goto nope;
5417 for (cp = buf; *cp; cp++)
5419 #ifdef DEBUG_PCP
5420 fprintf (stderr, "Using preinclude %s\n", fname);
5421 #endif
5422 return cp + 1;
5424 nope:
5425 #ifdef DEBUG_PCP
5426 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5427 #endif
5428 free (buf);
5429 return 0;
5432 /* PREC (null terminated) points to the preconditions of a
5433 precompiled header. These are a series of #define and #undef
5434 lines which must match the current contents of the hash
5435 table. */
5437 static int
5438 check_preconditions (prec)
5439 char *prec;
5441 MACRODEF mdef;
5442 char *lineend;
5444 while (*prec) {
5445 lineend = index (prec, '\n');
5447 if (*prec++ != '#') {
5448 error ("Bad format encountered while reading precompiled file");
5449 return 0;
5451 if (!strncmp (prec, "define", 6)) {
5452 HASHNODE *hp;
5454 prec += 6;
5455 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5457 if (mdef.defn == 0)
5458 abort ();
5460 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5461 || (hp->type != T_MACRO && hp->type != T_CONST)
5462 || (hp->type == T_MACRO
5463 && !compare_defs (mdef.defn, hp->value.defn)
5464 && (mdef.defn->length != 2
5465 || mdef.defn->expansion[0] != '\n'
5466 || mdef.defn->expansion[1] != ' ')))
5467 return 0;
5468 } else if (!strncmp (prec, "undef", 5)) {
5469 char *name;
5470 int len;
5472 prec += 5;
5473 while (is_hor_space[(U_CHAR) *prec])
5474 prec++;
5475 name = prec;
5476 while (is_idchar[(U_CHAR) *prec])
5477 prec++;
5478 len = prec - name;
5480 if (lookup ((U_CHAR *) name, len, -1))
5481 return 0;
5482 } else {
5483 error ("Bad format encountered while reading precompiled file");
5484 return 0;
5486 prec = lineend + 1;
5488 /* They all passed successfully */
5489 return 1;
5492 /* Process the main body of a precompiled file. BUF points to the
5493 string section of the file, following the preconditions. LIMIT is one
5494 character past the end. NAME is the name of the file being read
5495 in. OP is the main output buffer. */
5497 static void
5498 pcfinclude (buf, name, op)
5499 U_CHAR *buf, *name;
5500 FILE_BUF *op;
5502 FILE_BUF tmpbuf;
5503 int nstrings;
5504 U_CHAR *cp = buf;
5506 /* First in the file comes 4 bytes indicating the number of strings, */
5507 /* in network byte order. (MSB first). */
5508 nstrings = *cp++;
5509 nstrings = (nstrings << 8) | *cp++;
5510 nstrings = (nstrings << 8) | *cp++;
5511 nstrings = (nstrings << 8) | *cp++;
5513 /* Looping over each string... */
5514 while (nstrings--) {
5515 U_CHAR *string_start;
5516 U_CHAR *endofthiskey;
5517 STRINGDEF *str;
5518 int nkeys;
5520 /* Each string starts with a STRINGDEF structure (str), followed */
5521 /* by the text of the string (string_start) */
5523 /* First skip to a longword boundary */
5524 /* ??? Why a 4-byte boundary? On all machines? */
5525 /* NOTE: This works correctly even if size_t
5526 is narrower than a pointer.
5527 Do not try risky measures here to get another type to use!
5528 Do not include stddef.h--it will fail! */
5529 if ((size_t) cp & 3)
5530 cp += 4 - ((size_t) cp & 3);
5532 /* Now get the string. */
5533 str = (STRINGDEF *) (PTR) cp;
5534 string_start = cp += sizeof (STRINGDEF);
5536 for (; *cp; cp++) /* skip the string */
5539 /* We need to macro expand the string here to ensure that the
5540 proper definition environment is in place. If it were only
5541 expanded when we find out it is needed, macros necessary for
5542 its proper expansion might have had their definitions changed. */
5543 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5544 /* Lineno is already set in the precompiled file */
5545 str->contents = tmpbuf.buf;
5546 str->len = tmpbuf.bufp - tmpbuf.buf;
5547 str->writeflag = 0;
5548 str->filename = name;
5549 str->output_mark = outbuf.bufp - outbuf.buf;
5551 str->chain = 0;
5552 *stringlist_tailp = str;
5553 stringlist_tailp = &str->chain;
5555 /* Next comes a fourbyte number indicating the number of keys
5556 for this string. */
5557 nkeys = *cp++;
5558 nkeys = (nkeys << 8) | *cp++;
5559 nkeys = (nkeys << 8) | *cp++;
5560 nkeys = (nkeys << 8) | *cp++;
5562 /* If this number is -1, then the string is mandatory. */
5563 if (nkeys == -1)
5564 str->writeflag = 1;
5565 else
5566 /* Otherwise, for each key, */
5567 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5568 KEYDEF *kp = (KEYDEF *) (PTR) cp;
5569 HASHNODE *hp;
5570 U_CHAR *bp;
5572 /* It starts with a KEYDEF structure */
5573 cp += sizeof (KEYDEF);
5575 /* Find the end of the key. At the end of this for loop we
5576 advance CP to the start of the next key using this variable. */
5577 endofthiskey = cp + strlen ((char *) cp);
5578 kp->str = str;
5580 /* Expand the key, and enter it into the hash table. */
5581 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5582 bp = tmpbuf.buf;
5584 while (is_hor_space[*bp])
5585 bp++;
5586 if (!is_idstart[*bp] || bp == tmpbuf.bufp) {
5587 str->writeflag = 1;
5588 continue;
5591 hp = lookup (bp, -1, -1);
5592 if (hp == NULL) {
5593 kp->chain = 0;
5594 install (bp, -1, T_PCSTRING, (char *) kp, -1);
5596 else if (hp->type == T_PCSTRING) {
5597 kp->chain = hp->value.keydef;
5598 hp->value.keydef = kp;
5600 else
5601 str->writeflag = 1;
5604 /* This output_line_directive serves to switch us back to the current
5605 input file in case some of these strings get output (which will
5606 result in line directives for the header file being output). */
5607 output_line_directive (&instack[indepth], op, 0, enter_file);
5610 /* Called from rescan when it hits a key for strings. Mark them all
5611 used and clean up. */
5613 static void
5614 pcstring_used (hp)
5615 HASHNODE *hp;
5617 KEYDEF *kp;
5619 for (kp = hp->value.keydef; kp; kp = kp->chain)
5620 kp->str->writeflag = 1;
5621 delete_macro (hp);
5624 /* Write the output, interspersing precompiled strings in their
5625 appropriate places. */
5627 static void
5628 write_output ()
5630 STRINGDEF *next_string;
5631 U_CHAR *cur_buf_loc;
5632 int line_directive_len = 80;
5633 char *line_directive = xmalloc (line_directive_len);
5634 int len;
5636 /* In each run through the loop, either cur_buf_loc ==
5637 next_string_loc, in which case we print a series of strings, or
5638 it is less than next_string_loc, in which case we write some of
5639 the buffer. */
5640 cur_buf_loc = outbuf.buf;
5641 next_string = stringlist;
5643 while (cur_buf_loc < outbuf.bufp || next_string) {
5644 if (next_string
5645 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5646 if (next_string->writeflag) {
5647 len = 4 * strlen ((char *) next_string->filename) + 32;
5648 while (len > line_directive_len)
5649 line_directive = xrealloc (line_directive,
5650 line_directive_len *= 2);
5651 sprintf (line_directive, "\n# %d ", next_string->lineno);
5652 strcpy (quote_string (line_directive + strlen (line_directive),
5653 (char *) next_string->filename,
5654 strlen ((char *) next_string->filename)),
5655 "\n");
5656 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5657 safe_write (fileno (stdout),
5658 (char *) next_string->contents, next_string->len);
5660 next_string = next_string->chain;
5662 else {
5663 len = (next_string
5664 ? (next_string->output_mark
5665 - (cur_buf_loc - outbuf.buf))
5666 : outbuf.bufp - cur_buf_loc);
5668 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5669 cur_buf_loc += len;
5672 free (line_directive);
5675 /* Pass a directive through to the output file.
5676 BUF points to the contents of the directive, as a contiguous string.
5677 LIMIT points to the first character past the end of the directive.
5678 KEYWORD is the keyword-table entry for the directive. */
5680 static void
5681 pass_thru_directive (buf, limit, op, keyword)
5682 U_CHAR *buf, *limit;
5683 FILE_BUF *op;
5684 struct directive *keyword;
5686 register int keyword_length = keyword->length;
5688 check_expand (op, 1 + keyword_length + (limit - buf));
5689 *op->bufp++ = '#';
5690 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5691 op->bufp += keyword_length;
5692 if (limit != buf && buf[0] != ' ')
5693 *op->bufp++ = ' ';
5694 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5695 op->bufp += (limit - buf);
5696 #if 0
5697 *op->bufp++ = '\n';
5698 /* Count the line we have just made in the output,
5699 to get in sync properly. */
5700 op->lineno++;
5701 #endif
5704 /* The arglist structure is built by do_define to tell
5705 collect_definition where the argument names begin. That
5706 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5707 would contain pointers to the strings x, y, and z.
5708 Collect_definition would then build a DEFINITION node,
5709 with reflist nodes pointing to the places x, y, and z had
5710 appeared. So the arglist is just convenience data passed
5711 between these two routines. It is not kept around after
5712 the current #define has been processed and entered into the
5713 hash table. */
5715 struct arglist {
5716 struct arglist *next;
5717 U_CHAR *name;
5718 int length;
5719 int argno;
5720 char rest_args;
5723 /* Create a DEFINITION node from a #define directive. Arguments are
5724 as for do_define. */
5726 static MACRODEF
5727 create_definition (buf, limit, op)
5728 U_CHAR *buf, *limit;
5729 FILE_BUF *op;
5731 U_CHAR *bp; /* temp ptr into input buffer */
5732 U_CHAR *symname; /* remember where symbol name starts */
5733 int sym_length; /* and how long it is */
5734 int line = instack[indepth].lineno;
5735 char *file = instack[indepth].nominal_fname;
5736 size_t file_len = instack[indepth].nominal_fname_len;
5737 int rest_args = 0;
5739 DEFINITION *defn;
5740 int arglengths = 0; /* Accumulate lengths of arg names
5741 plus number of args. */
5742 MACRODEF mdef;
5744 bp = buf;
5746 while (is_hor_space[*bp])
5747 bp++;
5749 symname = bp; /* remember where it starts */
5750 sym_length = check_macro_name (bp, 0);
5751 bp += sym_length;
5753 /* Lossage will occur if identifiers or control keywords are broken
5754 across lines using backslash. This is not the right place to take
5755 care of that. */
5757 if (*bp == '(') {
5758 struct arglist *arg_ptrs = NULL;
5759 int argno = 0;
5761 bp++; /* skip '(' */
5762 SKIP_WHITE_SPACE (bp);
5764 /* Loop over macro argument names. */
5765 while (*bp != ')') {
5766 struct arglist *temp;
5768 temp = (struct arglist *) alloca (sizeof (struct arglist));
5769 temp->name = bp;
5770 temp->next = arg_ptrs;
5771 temp->argno = argno++;
5772 temp->rest_args = 0;
5773 arg_ptrs = temp;
5775 if (rest_args)
5776 pedwarn ("another parameter follows `%s'",
5777 rest_extension);
5779 if (!is_idstart[*bp])
5781 if (c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5782 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
5784 /* This is the ISO C 9x way to write macros with variable
5785 number of arguments. */
5786 rest_args = 1;
5787 temp->rest_args = 1;
5789 else
5790 pedwarn ("invalid character in macro parameter name");
5793 /* Find the end of the arg name. */
5794 while (is_idchar[*bp]) {
5795 bp++;
5796 /* do we have a "special" rest-args extension here? */
5797 if (limit - bp > (long) REST_EXTENSION_LENGTH
5798 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5799 if (pedantic && !instack[indepth].system_header_p)
5800 pedwarn ("ANSI C does not allow macro with variable arguments");
5801 rest_args = 1;
5802 temp->rest_args = 1;
5803 break;
5806 if (bp == temp->name && rest_args == 1)
5808 /* This is the ISO C 9x style. */
5809 temp->name = (U_CHAR *) va_args_name;
5810 temp->length = VA_ARGS_NAME_LENGTH;
5812 else
5813 temp->length = bp - temp->name;
5814 if (rest_args == 1)
5815 bp += REST_EXTENSION_LENGTH;
5816 arglengths += temp->length + 2;
5817 SKIP_WHITE_SPACE (bp);
5818 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5819 error ("badly punctuated parameter list in `#define'");
5820 goto nope;
5822 if (*bp == ',') {
5823 bp++;
5824 SKIP_WHITE_SPACE (bp);
5825 /* A comma at this point can only be followed by an identifier. */
5826 if (!is_idstart[*bp]
5827 && !(c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5828 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)) {
5829 error ("badly punctuated parameter list in `#define'");
5830 goto nope;
5833 if (bp >= limit) {
5834 error ("unterminated parameter list in `#define'");
5835 goto nope;
5838 struct arglist *otemp;
5840 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5841 if (temp->length == otemp->length
5842 && bcmp (temp->name, otemp->name, temp->length) == 0)
5844 error ("duplicate argument name `%.*s' in `#define'",
5845 temp->length, temp->name);
5846 goto nope;
5848 if (rest_args == 0 && temp->length == VA_ARGS_NAME_LENGTH
5849 && bcmp (temp->name, va_args_name, VA_ARGS_NAME_LENGTH) == 0)
5851 error ("\
5852 reserved name `%s' used as argument name in `#define'", va_args_name);
5853 goto nope;
5858 ++bp; /* skip paren */
5859 SKIP_WHITE_SPACE (bp);
5860 /* now everything from bp before limit is the definition. */
5861 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5862 defn->rest_args = rest_args;
5864 /* Now set defn->args.argnames to the result of concatenating
5865 the argument names in reverse order
5866 with comma-space between them. */
5867 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5869 struct arglist *temp;
5870 int i = 0;
5871 for (temp = arg_ptrs; temp; temp = temp->next) {
5872 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5873 i += temp->length;
5874 if (temp->next != 0) {
5875 defn->args.argnames[i++] = ',';
5876 defn->args.argnames[i++] = ' ';
5879 defn->args.argnames[i] = 0;
5881 } else {
5882 /* Simple expansion or empty definition. */
5884 if (bp < limit)
5886 if (is_hor_space[*bp]) {
5887 bp++;
5888 SKIP_WHITE_SPACE (bp);
5889 } else if (sym_length) {
5890 switch (*bp) {
5891 case '!': case '"': case '#': case '%': case '&': case '\'':
5892 case ')': case '*': case '+': case ',': case '-': case '.':
5893 case '/': case ':': case ';': case '<': case '=': case '>':
5894 case '?': case '[': case '\\': case ']': case '^': case '{':
5895 case '|': case '}': case '~':
5896 warning ("missing white space after `#define %.*s'",
5897 sym_length, symname);
5898 break;
5900 default:
5901 pedwarn ("missing white space after `#define %.*s'",
5902 sym_length, symname);
5903 break;
5907 /* Now everything from bp before limit is the definition. */
5908 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5909 defn->args.argnames = (U_CHAR *) "";
5912 defn->line = line;
5913 defn->file = file;
5914 defn->file_len = file_len;
5916 /* OP is null if this is a predefinition */
5917 defn->predefined = !op;
5918 mdef.defn = defn;
5919 mdef.symnam = symname;
5920 mdef.symlen = sym_length;
5922 return mdef;
5924 nope:
5925 mdef.defn = 0;
5926 return mdef;
5929 /* Process a #define directive.
5930 BUF points to the contents of the #define directive, as a contiguous string.
5931 LIMIT points to the first character past the end of the definition.
5932 KEYWORD is the keyword-table entry for #define. */
5934 static int
5935 do_define (buf, limit, op, keyword)
5936 U_CHAR *buf, *limit;
5937 FILE_BUF *op;
5938 struct directive *keyword;
5940 int hashcode;
5941 MACRODEF mdef;
5942 enum node_type newtype = keyword->type == T_DEFINE ? T_MACRO : T_POISON;
5944 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5945 if (pcp_outfile && op)
5946 pass_thru_directive (buf, limit, op, keyword);
5948 mdef = create_definition (buf, limit, op);
5949 if (mdef.defn == 0)
5950 goto nope;
5952 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5955 HASHNODE *hp;
5956 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5957 int ok = 0;
5958 /* Redefining a precompiled key is ok. */
5959 if (hp->type == T_PCSTRING)
5960 ok = 1;
5961 /* Redefining a poisoned identifier is even worse than `not ok'. */
5962 else if (hp->type == T_POISON)
5963 ok = -1;
5964 /* Poisoning anything else is not ok.
5965 The poison should always come first. */
5966 else if (newtype == T_POISON)
5967 ok = 0;
5968 /* Redefining a macro is ok if the definitions are the same. */
5969 else if (hp->type == T_MACRO)
5970 ok = ! compare_defs (mdef.defn, hp->value.defn);
5971 /* Redefining a constant is ok with -D. */
5972 else if (hp->type == T_CONST)
5973 ok = ! done_initializing;
5975 /* Print the warning or error if it's not ok. */
5976 if (ok <= 0)
5978 /* If we are passing through #define and #undef directives, do
5979 that for this re-definition now. */
5980 if (debug_output && op)
5981 pass_thru_directive (buf, limit, op, keyword);
5983 if (hp->type == T_POISON)
5984 error ("redefining poisoned `%.*s'", mdef.symlen, mdef.symnam);
5985 else
5986 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5987 if (hp->type == T_MACRO)
5988 pedwarn_with_file_and_line (hp->value.defn->file,
5989 hp->value.defn->file_len,
5990 hp->value.defn->line,
5991 "this is the location of the previous definition");
5993 if (hp->type != T_POISON)
5995 /* Replace the old definition. */
5996 hp->type = newtype;
5997 hp->value.defn = mdef.defn;
5999 } else {
6000 /* If we are passing through #define and #undef directives, do
6001 that for this new definition now. */
6002 if (debug_output && op)
6003 pass_thru_directive (buf, limit, op, keyword);
6004 install (mdef.symnam, mdef.symlen, newtype,
6005 (char *) mdef.defn, hashcode);
6009 return 0;
6011 nope:
6013 return 1;
6016 /* Check a purported macro name SYMNAME, and yield its length.
6017 ASSERTION is nonzero if this is really for an assertion name. */
6019 static int
6020 check_macro_name (symname, assertion)
6021 U_CHAR *symname;
6022 int assertion;
6024 U_CHAR *p;
6025 int sym_length;
6027 for (p = symname; is_idchar[*p]; p++)
6029 sym_length = p - symname;
6030 if (sym_length == 0
6031 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
6032 error (assertion ? "invalid assertion name" : "invalid macro name");
6033 else if (!is_idstart[*symname]
6034 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
6035 error ((assertion
6036 ? "invalid assertion name `%.*s'"
6037 : "invalid macro name `%.*s'"),
6038 sym_length, symname);
6039 return sym_length;
6042 /* Return zero if two DEFINITIONs are isomorphic. */
6044 static int
6045 compare_defs (d1, d2)
6046 DEFINITION *d1, *d2;
6048 register struct reflist *a1, *a2;
6049 register U_CHAR *p1 = d1->expansion;
6050 register U_CHAR *p2 = d2->expansion;
6051 int first = 1;
6053 if (d1->nargs != d2->nargs)
6054 return 1;
6055 if (pedantic
6056 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
6057 return 1;
6058 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
6059 a1 = a1->next, a2 = a2->next) {
6060 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
6061 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
6062 || a1->argno != a2->argno
6063 || a1->stringify != a2->stringify
6064 || a1->raw_before != a2->raw_before
6065 || a1->raw_after != a2->raw_after)
6066 return 1;
6067 first = 0;
6068 p1 += a1->nchars;
6069 p2 += a2->nchars;
6071 if (a1 != a2)
6072 return 1;
6073 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
6074 p2, d2->length - (p2 - d2->expansion), 1))
6075 return 1;
6076 return 0;
6079 /* Return 1 if two parts of two macro definitions are effectively different.
6080 One of the parts starts at BEG1 and has LEN1 chars;
6081 the other has LEN2 chars at BEG2.
6082 Any sequence of whitespace matches any other sequence of whitespace.
6083 FIRST means these parts are the first of a macro definition;
6084 so ignore leading whitespace entirely.
6085 LAST means these parts are the last of a macro definition;
6086 so ignore trailing whitespace entirely. */
6088 static int
6089 comp_def_part (first, beg1, len1, beg2, len2, last)
6090 int first;
6091 U_CHAR *beg1, *beg2;
6092 int len1, len2;
6093 int last;
6095 register U_CHAR *end1 = beg1 + len1;
6096 register U_CHAR *end2 = beg2 + len2;
6097 if (first) {
6098 while (beg1 != end1 && is_space[*beg1]) beg1++;
6099 while (beg2 != end2 && is_space[*beg2]) beg2++;
6101 if (last) {
6102 while (beg1 != end1 && is_space[end1[-1]]) end1--;
6103 while (beg2 != end2 && is_space[end2[-1]]) end2--;
6105 while (beg1 != end1 && beg2 != end2) {
6106 if (is_space[*beg1] && is_space[*beg2]) {
6107 while (beg1 != end1 && is_space[*beg1]) beg1++;
6108 while (beg2 != end2 && is_space[*beg2]) beg2++;
6109 } else if (*beg1 == *beg2) {
6110 beg1++; beg2++;
6111 } else break;
6113 return (beg1 != end1) || (beg2 != end2);
6116 /* Read a replacement list for a macro with parameters.
6117 Build the DEFINITION structure.
6118 Reads characters of text starting at BUF until END.
6119 ARGLIST specifies the formal parameters to look for
6120 in the text of the definition; NARGS is the number of args
6121 in that list, or -1 for a macro name that wants no argument list.
6122 MACRONAME is the macro name itself (so we can avoid recursive expansion)
6123 and NAMELEN is its length in characters.
6125 Note that comments, backslash-newlines, and leading white space
6126 have already been deleted from the argument. */
6128 /* If there is no trailing whitespace, a Newline Space is added at the end
6129 to prevent concatenation that would be contrary to the standard. */
6131 static DEFINITION *
6132 collect_expansion (buf, end, nargs, arglist)
6133 U_CHAR *buf, *end;
6134 int nargs;
6135 struct arglist *arglist;
6137 DEFINITION *defn;
6138 register U_CHAR *p, *limit, *lastp, *exp_p;
6139 struct reflist *endpat = NULL;
6140 /* Pointer to first nonspace after last ## seen. */
6141 U_CHAR *concat = 0;
6142 /* Pointer to first nonspace after last single-# seen. */
6143 U_CHAR *stringify = 0;
6144 /* How those tokens were spelled. */
6145 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
6146 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
6147 int maxsize;
6148 int expected_delimiter = '\0';
6150 /* Scan thru the replacement list, ignoring comments and quoted
6151 strings, picking up on the macro calls. It does a linear search
6152 thru the arg list on every potential symbol. Profiling might say
6153 that something smarter should happen. */
6155 if (end < buf)
6156 abort ();
6158 /* Find the beginning of the trailing whitespace. */
6159 limit = end;
6160 p = buf;
6161 while (p < limit && is_space[limit[-1]]) limit--;
6163 /* Allocate space for the text in the macro definition.
6164 Each input char may or may not need 1 byte,
6165 so this is an upper bound.
6166 The extra 3 are for invented trailing newline-marker and final null. */
6167 maxsize = (sizeof (DEFINITION)
6168 + (limit - p) + 3);
6169 defn = (DEFINITION *) xcalloc (1, maxsize);
6171 defn->nargs = nargs;
6172 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6173 lastp = exp_p;
6175 if (p[0] == '#'
6176 ? p[1] == '#'
6177 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6178 error ("`##' at start of macro definition");
6179 p += p[0] == '#' ? 2 : 4;
6182 /* Process the main body of the definition. */
6183 while (p < limit) {
6184 int skipped_arg = 0;
6185 register U_CHAR c = *p++;
6187 *exp_p++ = c;
6189 if (!traditional) {
6190 switch (c) {
6191 case '\'':
6192 case '\"':
6193 if (expected_delimiter != '\0') {
6194 if (c == expected_delimiter)
6195 expected_delimiter = '\0';
6196 } else
6197 expected_delimiter = c;
6198 break;
6200 case '\\':
6201 if (expected_delimiter) {
6202 /* In a string, backslash goes through
6203 and makes next char ordinary. */
6204 *exp_p++ = *p++;
6206 break;
6208 case '%':
6209 if (!expected_delimiter && *p == ':') {
6210 /* %: is not a digraph if preceded by an odd number of '<'s. */
6211 U_CHAR *p0 = p - 1;
6212 while (buf < p0 && p0[-1] == '<')
6213 p0--;
6214 if ((p - p0) & 1) {
6215 /* Treat %:%: as ## and %: as #. */
6216 if (p[1] == '%' && p[2] == ':') {
6217 p += 2;
6218 goto sharp_sharp_token;
6220 if (nargs >= 0) {
6221 p++;
6222 goto sharp_token;
6226 break;
6228 case '#':
6229 /* # is ordinary inside a string. */
6230 if (expected_delimiter)
6231 break;
6232 if (*p == '#') {
6233 sharp_sharp_token:
6234 /* ##: concatenate preceding and following tokens. */
6235 /* Take out the first #, discard preceding whitespace. */
6236 exp_p--;
6237 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6238 --exp_p;
6239 /* Skip the second #. */
6240 p++;
6241 concat_sharp_token_type = c;
6242 if (is_hor_space[*p]) {
6243 concat_sharp_token_type = c + 1;
6244 p++;
6245 SKIP_WHITE_SPACE (p);
6247 concat = p;
6248 if (p == limit)
6249 error ("`##' at end of macro definition");
6250 } else if (nargs >= 0) {
6251 /* Single #: stringify following argument ref.
6252 Don't leave the # in the expansion. */
6253 sharp_token:
6254 exp_p--;
6255 stringify_sharp_token_type = c;
6256 if (is_hor_space[*p]) {
6257 stringify_sharp_token_type = c + 1;
6258 p++;
6259 SKIP_WHITE_SPACE (p);
6261 if (! is_idstart[*p] || nargs == 0
6262 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6263 error ("`#' operator is not followed by a macro argument name");
6264 else
6265 stringify = p;
6267 break;
6269 } else {
6270 /* In -traditional mode, recognize arguments inside strings and
6271 character constants, and ignore special properties of #.
6272 Arguments inside strings are considered "stringified", but no
6273 extra quote marks are supplied. */
6274 switch (c) {
6275 case '\'':
6276 case '\"':
6277 if (expected_delimiter != '\0') {
6278 if (c == expected_delimiter)
6279 expected_delimiter = '\0';
6280 } else
6281 expected_delimiter = c;
6282 break;
6284 case '\\':
6285 /* Backslash quotes delimiters and itself, but not macro args. */
6286 if (expected_delimiter != 0 && p < limit
6287 && (*p == expected_delimiter || *p == '\\')) {
6288 *exp_p++ = *p++;
6289 continue;
6291 break;
6293 case '/':
6294 if (expected_delimiter != '\0') /* No comments inside strings. */
6295 break;
6296 if (*p == '*') {
6297 /* If we find a comment that wasn't removed by handle_directive,
6298 this must be -traditional. So replace the comment with
6299 nothing at all. */
6300 exp_p--;
6301 while (++p < limit) {
6302 if (p[0] == '*' && p[1] == '/') {
6303 p += 2;
6304 break;
6307 #if 0
6308 /* Mark this as a concatenation-point, as if it had been ##. */
6309 concat = p;
6310 #endif
6312 break;
6316 #ifdef MULTIBYTE_CHARS
6317 /* Handle multibyte characters inside string and character literals. */
6318 if (expected_delimiter != '\0')
6320 int length;
6321 --p;
6322 length = local_mblen (p, limit - p);
6323 if (length > 1)
6325 --exp_p;
6326 bcopy (p, exp_p, length);
6327 p += length;
6328 exp_p += length;
6329 continue;
6331 ++p;
6333 #endif
6335 /* Handle the start of a symbol. */
6336 if (is_idchar[c] && nargs > 0) {
6337 U_CHAR *id_beg = p - 1;
6338 int id_len;
6340 --exp_p;
6341 while (p != limit && is_idchar[*p]) p++;
6342 id_len = p - id_beg;
6344 if (is_idstart[c]
6345 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6346 register struct arglist *arg;
6348 for (arg = arglist; arg != NULL; arg = arg->next) {
6349 struct reflist *tpat;
6351 if (arg->name[0] == c
6352 && arg->length == id_len
6353 && bcmp (arg->name, id_beg, id_len) == 0) {
6354 enum sharp_token_type tpat_stringify;
6355 if (expected_delimiter) {
6356 if (warn_stringify) {
6357 if (traditional) {
6358 warning ("macro argument `%.*s' is stringified.",
6359 id_len, arg->name);
6360 } else {
6361 warning ("macro arg `%.*s' would be stringified with -traditional.",
6362 id_len, arg->name);
6365 /* If ANSI, don't actually substitute inside a string. */
6366 if (!traditional)
6367 break;
6368 tpat_stringify = SHARP_TOKEN;
6369 } else {
6370 tpat_stringify
6371 = (stringify == id_beg
6372 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6374 /* make a pat node for this arg and append it to the end of
6375 the pat list */
6376 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6377 tpat->next = NULL;
6378 tpat->raw_before
6379 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6380 tpat->raw_after = NO_SHARP_TOKEN;
6381 tpat->rest_args = arg->rest_args;
6382 tpat->stringify = tpat_stringify;
6384 if (endpat == NULL)
6385 defn->pattern = tpat;
6386 else
6387 endpat->next = tpat;
6388 endpat = tpat;
6390 tpat->argno = arg->argno;
6391 tpat->nchars = exp_p - lastp;
6393 register U_CHAR *p1 = p;
6394 SKIP_WHITE_SPACE (p1);
6395 if (p1[0]=='#'
6396 ? p1[1]=='#'
6397 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6398 tpat->raw_after = p1[0] + (p != p1);
6400 lastp = exp_p; /* place to start copying from next time */
6401 skipped_arg = 1;
6402 break;
6407 /* If this was not a macro arg, copy it into the expansion. */
6408 if (! skipped_arg) {
6409 register U_CHAR *lim1 = p;
6410 p = id_beg;
6411 while (p != lim1)
6412 *exp_p++ = *p++;
6413 if (stringify == id_beg)
6414 error ("`#' operator should be followed by a macro argument name");
6419 if (!traditional && expected_delimiter == 0) {
6420 /* If ANSI, put in a newline-space marker to prevent token pasting.
6421 But not if "inside a string" (which in ANSI mode happens only for
6422 -D option). */
6423 *exp_p++ = '\n';
6424 *exp_p++ = ' ';
6427 *exp_p = '\0';
6429 defn->length = exp_p - defn->expansion;
6431 /* Crash now if we overrun the allocated size. */
6432 if (defn->length + 1 > maxsize)
6433 abort ();
6435 #if 0
6436 /* This isn't worth the time it takes. */
6437 /* give back excess storage */
6438 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6439 #endif
6441 return defn;
6444 static int
6445 do_assert (buf, limit, op, keyword)
6446 U_CHAR *buf, *limit;
6447 FILE_BUF *op ATTRIBUTE_UNUSED;
6448 struct directive *keyword ATTRIBUTE_UNUSED;
6450 U_CHAR *bp; /* temp ptr into input buffer */
6451 U_CHAR *symname; /* remember where symbol name starts */
6452 int sym_length; /* and how long it is */
6453 struct arglist *tokens = NULL;
6455 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6456 pedwarn ("ANSI C does not allow `#assert'");
6458 bp = buf;
6460 while (is_hor_space[*bp])
6461 bp++;
6463 symname = bp; /* remember where it starts */
6464 sym_length = check_macro_name (bp, 1);
6465 bp += sym_length;
6466 /* #define doesn't do this, but we should. */
6467 SKIP_WHITE_SPACE (bp);
6469 /* Lossage will occur if identifiers or control tokens are broken
6470 across lines using backslash. This is not the right place to take
6471 care of that. */
6473 if (*bp != '(') {
6474 error ("missing token-sequence in `#assert'");
6475 return 1;
6479 int error_flag = 0;
6481 bp++; /* skip '(' */
6482 SKIP_WHITE_SPACE (bp);
6484 tokens = read_token_list (&bp, limit, &error_flag);
6485 if (error_flag)
6486 return 1;
6487 if (tokens == 0) {
6488 error ("empty token-sequence in `#assert'");
6489 return 1;
6492 ++bp; /* skip paren */
6493 SKIP_WHITE_SPACE (bp);
6496 /* If this name isn't already an assertion name, make it one.
6497 Error if it was already in use in some other way. */
6500 ASSERTION_HASHNODE *hp;
6501 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6502 struct tokenlist_list *value
6503 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6505 hp = assertion_lookup (symname, sym_length, hashcode);
6506 if (hp == NULL) {
6507 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6508 error ("`defined' redefined as assertion");
6509 hp = assertion_install (symname, sym_length, hashcode);
6512 /* Add the spec'd token-sequence to the list of such. */
6513 value->tokens = tokens;
6514 value->next = hp->value;
6515 hp->value = value;
6518 return 0;
6521 static int
6522 do_unassert (buf, limit, op, keyword)
6523 U_CHAR *buf, *limit;
6524 FILE_BUF *op ATTRIBUTE_UNUSED;
6525 struct directive *keyword ATTRIBUTE_UNUSED;
6527 U_CHAR *bp; /* temp ptr into input buffer */
6528 U_CHAR *symname; /* remember where symbol name starts */
6529 int sym_length; /* and how long it is */
6531 struct arglist *tokens = NULL;
6532 int tokens_specified = 0;
6534 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6535 pedwarn ("ANSI C does not allow `#unassert'");
6537 bp = buf;
6539 while (is_hor_space[*bp])
6540 bp++;
6542 symname = bp; /* remember where it starts */
6543 sym_length = check_macro_name (bp, 1);
6544 bp += sym_length;
6545 /* #define doesn't do this, but we should. */
6546 SKIP_WHITE_SPACE (bp);
6548 /* Lossage will occur if identifiers or control tokens are broken
6549 across lines using backslash. This is not the right place to take
6550 care of that. */
6552 if (*bp == '(') {
6553 int error_flag = 0;
6555 bp++; /* skip '(' */
6556 SKIP_WHITE_SPACE (bp);
6558 tokens = read_token_list (&bp, limit, &error_flag);
6559 if (error_flag)
6560 return 1;
6561 if (tokens == 0) {
6562 error ("empty token list in `#unassert'");
6563 return 1;
6566 tokens_specified = 1;
6568 ++bp; /* skip paren */
6569 SKIP_WHITE_SPACE (bp);
6573 ASSERTION_HASHNODE *hp;
6574 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6575 struct tokenlist_list *tail, *prev;
6577 hp = assertion_lookup (symname, sym_length, hashcode);
6578 if (hp == NULL)
6579 return 1;
6581 /* If no token list was specified, then eliminate this assertion
6582 entirely. */
6583 if (! tokens_specified) {
6584 struct tokenlist_list *next;
6585 for (tail = hp->value; tail; tail = next) {
6586 next = tail->next;
6587 free_token_list (tail->tokens);
6588 free (tail);
6590 delete_assertion (hp);
6591 } else {
6592 /* If a list of tokens was given, then delete any matching list. */
6594 tail = hp->value;
6595 prev = 0;
6596 while (tail) {
6597 struct tokenlist_list *next = tail->next;
6598 if (compare_token_lists (tail->tokens, tokens)) {
6599 if (prev)
6600 prev->next = next;
6601 else
6602 hp->value = tail->next;
6603 free_token_list (tail->tokens);
6604 free (tail);
6605 } else {
6606 prev = tail;
6608 tail = next;
6613 return 0;
6616 /* Test whether there is an assertion named NAME
6617 and optionally whether it has an asserted token list TOKENS.
6618 NAME is not null terminated; its length is SYM_LENGTH.
6619 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6622 check_assertion (name, sym_length, tokens_specified, tokens)
6623 U_CHAR *name;
6624 int sym_length;
6625 int tokens_specified;
6626 struct arglist *tokens;
6628 ASSERTION_HASHNODE *hp;
6629 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6631 if (pedantic && !instack[indepth].system_header_p)
6632 pedwarn ("ANSI C does not allow testing assertions");
6634 hp = assertion_lookup (name, sym_length, hashcode);
6635 if (hp == NULL)
6636 /* It is not an assertion; just return false. */
6637 return 0;
6639 /* If no token list was specified, then value is 1. */
6640 if (! tokens_specified)
6641 return 1;
6644 struct tokenlist_list *tail;
6646 tail = hp->value;
6648 /* If a list of tokens was given,
6649 then succeed if the assertion records a matching list. */
6651 while (tail) {
6652 if (compare_token_lists (tail->tokens, tokens))
6653 return 1;
6654 tail = tail->next;
6657 /* Fail if the assertion has no matching list. */
6658 return 0;
6662 /* Compare two lists of tokens for equality including order of tokens. */
6664 static int
6665 compare_token_lists (l1, l2)
6666 struct arglist *l1, *l2;
6668 while (l1 && l2) {
6669 if (l1->length != l2->length)
6670 return 0;
6671 if (bcmp (l1->name, l2->name, l1->length))
6672 return 0;
6673 l1 = l1->next;
6674 l2 = l2->next;
6677 /* Succeed if both lists end at the same time. */
6678 return l1 == l2;
6681 /* Read a space-separated list of tokens ending in a close parenthesis.
6682 Return a list of strings, in the order they were written.
6683 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6684 Parse the text starting at *BPP, and update *BPP.
6685 Don't parse beyond LIMIT. */
6687 static struct arglist *
6688 read_token_list (bpp, limit, error_flag)
6689 U_CHAR **bpp;
6690 U_CHAR *limit;
6691 int *error_flag;
6693 struct arglist *token_ptrs = 0;
6694 U_CHAR *bp = *bpp;
6695 int depth = 1;
6697 *error_flag = 0;
6699 /* Loop over the assertion value tokens. */
6700 while (depth > 0) {
6701 struct arglist *temp;
6702 int eofp = 0;
6703 U_CHAR *beg = bp;
6705 /* Find the end of the token. */
6706 if (*bp == '(') {
6707 bp++;
6708 depth++;
6709 } else if (*bp == ')') {
6710 depth--;
6711 if (depth == 0)
6712 break;
6713 bp++;
6714 } else if (*bp == '"' || *bp == '\'')
6715 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6716 else
6717 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6718 && *bp != '"' && *bp != '\'' && bp != limit)
6719 bp++;
6721 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6722 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6723 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6724 temp->name[bp - beg] = 0;
6725 temp->next = token_ptrs;
6726 token_ptrs = temp;
6727 temp->length = bp - beg;
6729 SKIP_WHITE_SPACE (bp);
6731 if (bp >= limit) {
6732 error ("unterminated token sequence in `#assert' or `#unassert'");
6733 *error_flag = -1;
6734 return 0;
6737 *bpp = bp;
6739 /* We accumulated the names in reverse order.
6740 Now reverse them to get the proper order. */
6742 register struct arglist *prev = 0, *this, *next;
6743 for (this = token_ptrs; this; this = next) {
6744 next = this->next;
6745 this->next = prev;
6746 prev = this;
6748 return prev;
6752 static void
6753 free_token_list (tokens)
6754 struct arglist *tokens;
6756 while (tokens) {
6757 struct arglist *next = tokens->next;
6758 free (tokens->name);
6759 free (tokens);
6760 tokens = next;
6764 /* Install a name in the assertion hash table.
6766 If LEN is >= 0, it is the length of the name.
6767 Otherwise, compute the length by scanning the entire name.
6769 If HASH is >= 0, it is the precomputed hash code.
6770 Otherwise, compute the hash code. */
6772 static ASSERTION_HASHNODE *
6773 assertion_install (name, len, hash)
6774 U_CHAR *name;
6775 int len;
6776 int hash;
6778 register ASSERTION_HASHNODE *hp;
6779 register int i, bucket;
6780 register U_CHAR *p, *q;
6782 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6783 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6784 bucket = hash;
6785 hp->bucket_hdr = &assertion_hashtab[bucket];
6786 hp->next = assertion_hashtab[bucket];
6787 assertion_hashtab[bucket] = hp;
6788 hp->prev = NULL;
6789 if (hp->next != NULL)
6790 hp->next->prev = hp;
6791 hp->length = len;
6792 hp->value = 0;
6793 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6794 p = hp->name;
6795 q = name;
6796 for (i = 0; i < len; i++)
6797 *p++ = *q++;
6798 hp->name[len] = 0;
6799 return hp;
6802 /* Find the most recent hash node for name "name" (ending with first
6803 non-identifier char) installed by install
6805 If LEN is >= 0, it is the length of the name.
6806 Otherwise, compute the length by scanning the entire name.
6808 If HASH is >= 0, it is the precomputed hash code.
6809 Otherwise, compute the hash code. */
6811 static ASSERTION_HASHNODE *
6812 assertion_lookup (name, len, hash)
6813 U_CHAR *name;
6814 int len;
6815 int hash;
6817 register ASSERTION_HASHNODE *bucket;
6819 bucket = assertion_hashtab[hash];
6820 while (bucket) {
6821 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6822 return bucket;
6823 bucket = bucket->next;
6825 return NULL;
6828 static void
6829 delete_assertion (hp)
6830 ASSERTION_HASHNODE *hp;
6833 if (hp->prev != NULL)
6834 hp->prev->next = hp->next;
6835 if (hp->next != NULL)
6836 hp->next->prev = hp->prev;
6838 /* Make sure that the bucket chain header that the deleted guy was
6839 on points to the right thing afterwards. */
6840 if (hp == *hp->bucket_hdr)
6841 *hp->bucket_hdr = hp->next;
6843 free (hp);
6847 * interpret #line directive. Remembers previously seen fnames
6848 * in its very own hash table.
6850 #define FNAME_HASHSIZE 37
6852 static int
6853 do_line (buf, limit, op, keyword)
6854 U_CHAR *buf, *limit;
6855 FILE_BUF *op;
6856 struct directive *keyword ATTRIBUTE_UNUSED;
6858 register U_CHAR *bp;
6859 FILE_BUF *ip = &instack[indepth];
6860 FILE_BUF tem;
6861 int new_lineno;
6862 enum file_change_code file_change = same_file;
6864 /* Expand any macros. */
6865 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6867 /* Point to macroexpanded line, which is null-terminated now. */
6868 bp = tem.buf;
6869 limit = tem.bufp;
6870 SKIP_WHITE_SPACE (bp);
6872 if (!ISDIGIT (*bp)) {
6873 error ("invalid format `#line' directive");
6874 return 0;
6877 /* The Newline at the end of this line remains to be processed.
6878 To put the next line at the specified line number,
6879 we must store a line number now that is one less. */
6880 new_lineno = atoi ((char *) bp) - 1;
6882 /* NEW_LINENO is one less than the actual line number here. */
6883 if (pedantic && new_lineno < 0)
6884 pedwarn ("line number out of range in `#line' directive");
6886 /* skip over the line number. */
6887 while (ISDIGIT (*bp))
6888 bp++;
6890 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6891 if (*bp && !is_space[*bp]) {
6892 error ("invalid format `#line' directive");
6893 return;
6895 #endif
6897 SKIP_WHITE_SPACE (bp);
6899 if (*bp == '\"') {
6900 static HASHNODE *fname_table[FNAME_HASHSIZE];
6901 HASHNODE *hp, **hash_bucket;
6902 U_CHAR *fname, *p;
6903 int fname_length;
6905 fname = ++bp;
6907 /* Turn the file name, which is a character string literal,
6908 into a null-terminated string. Do this in place. */
6909 p = bp;
6910 for (;;)
6911 switch ((*p++ = *bp++)) {
6912 case '\\':
6913 if (! ignore_escape_flag)
6915 char *bpc = (char *) bp;
6916 HOST_WIDEST_INT c = parse_escape (&bpc, (HOST_WIDEST_INT) (U_CHAR) (-1));
6917 bp = (U_CHAR *) bpc;
6918 if (c < 0)
6919 p--;
6920 else
6921 p[-1] = c;
6923 break;
6925 case '\"':
6926 *--p = 0;
6927 goto fname_done;
6929 fname_done:
6930 fname_length = p - fname;
6932 SKIP_WHITE_SPACE (bp);
6933 if (*bp) {
6934 if (pedantic)
6935 pedwarn ("garbage at end of `#line' directive");
6936 if (*bp == '1')
6937 file_change = enter_file;
6938 else if (*bp == '2')
6939 file_change = leave_file;
6940 else if (*bp == '3')
6941 ip->system_header_p = 1;
6942 else if (*bp == '4')
6943 ip->system_header_p = 2;
6944 else {
6945 error ("invalid format `#line' directive");
6946 return 0;
6949 bp++;
6950 SKIP_WHITE_SPACE (bp);
6951 if (*bp == '3') {
6952 ip->system_header_p = 1;
6953 bp++;
6954 SKIP_WHITE_SPACE (bp);
6956 if (*bp == '4') {
6957 ip->system_header_p = 2;
6958 bp++;
6959 SKIP_WHITE_SPACE (bp);
6961 if (*bp) {
6962 error ("invalid format `#line' directive");
6963 return 0;
6967 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6968 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6969 if (hp->length == fname_length &&
6970 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6971 ip->nominal_fname = hp->value.cpval;
6972 ip->nominal_fname_len = fname_length;
6973 break;
6975 if (hp == 0) {
6976 /* Didn't find it; cons up a new one. */
6977 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6978 hp->next = *hash_bucket;
6979 *hash_bucket = hp;
6981 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6982 ip->nominal_fname_len = hp->length = fname_length;
6983 bcopy (fname, hp->value.cpval, fname_length + 1);
6985 } else if (*bp) {
6986 error ("invalid format `#line' directive");
6987 return 0;
6990 ip->lineno = new_lineno;
6991 output_line_directive (ip, op, 0, file_change);
6992 check_expand (op, ip->length - (ip->bufp - ip->buf));
6993 return 0;
6996 /* Remove the definition of a symbol from the symbol table.
6997 according to un*x /lib/cpp, it is not an error to undef
6998 something that has no definitions, so it isn't one here either. */
7000 static int
7001 do_undef (buf, limit, op, keyword)
7002 U_CHAR *buf, *limit;
7003 FILE_BUF *op;
7004 struct directive *keyword;
7006 int sym_length;
7007 HASHNODE *hp;
7008 U_CHAR *orig_buf = buf;
7010 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
7011 if (pcp_outfile && op)
7012 pass_thru_directive (buf, limit, op, keyword);
7014 SKIP_WHITE_SPACE (buf);
7015 sym_length = check_macro_name (buf, 0);
7017 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
7018 /* If we are generating additional info for debugging (with -g) we
7019 need to pass through all effective #undef directives. */
7020 if (debug_output && op)
7021 pass_thru_directive (orig_buf, limit, op, keyword);
7022 if (hp->type == T_POISON)
7023 error ("cannot undefine poisoned `%s'", hp->name);
7024 else {
7025 if (hp->type != T_MACRO)
7026 warning ("undefining `%s'", hp->name);
7027 delete_macro (hp);
7031 if (pedantic) {
7032 buf += sym_length;
7033 SKIP_WHITE_SPACE (buf);
7034 if (buf != limit)
7035 pedwarn ("garbage after `#undef' directive");
7037 return 0;
7041 /* Report an error detected by the program we are processing.
7042 Use the text of the line in the error message. */
7044 static int
7045 do_error (buf, limit, op, keyword)
7046 U_CHAR *buf, *limit;
7047 FILE_BUF *op ATTRIBUTE_UNUSED;
7048 struct directive *keyword;
7050 int length = limit - buf;
7051 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7052 bcopy ((char *) buf, (char *) copy, length);
7053 copy[length] = 0;
7054 SKIP_WHITE_SPACE (copy);
7056 switch (keyword->type) {
7057 case T_ERROR:
7058 error ("#error %s", copy);
7059 break;
7061 case T_WARNING:
7062 if (pedantic && !instack[indepth].system_header_p)
7063 pedwarn ("ANSI C does not allow `#warning'");
7064 warning ("#warning %s", copy);
7065 break;
7067 default:
7068 abort ();
7071 return 0;
7073 /* Remember the name of the current file being read from so that we can
7074 avoid ever including it again. */
7076 static void
7077 do_once ()
7079 int i;
7081 for (i = indepth; i >= 0; i--)
7082 if (instack[i].inc) {
7083 record_control_macro (instack[i].inc, (U_CHAR *) "");
7084 break;
7088 /* Report program identification. */
7090 static int
7091 do_ident (buf, limit, op, keyword)
7092 U_CHAR *buf, *limit;
7093 FILE_BUF *op;
7094 struct directive *keyword ATTRIBUTE_UNUSED;
7096 FILE_BUF trybuf;
7097 int len;
7099 /* Allow #ident in system headers, since that's not user's fault. */
7100 if (pedantic && !instack[indepth].system_header_p)
7101 pedwarn ("ANSI C does not allow `#ident'");
7103 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
7104 buf = trybuf.buf;
7105 len = trybuf.bufp - buf;
7107 /* Output expanded directive. */
7108 check_expand (op, 7 + len);
7109 bcopy ("#ident ", (char *) op->bufp, 7);
7110 op->bufp += 7;
7111 bcopy ((char *) buf, (char *) op->bufp, len);
7112 op->bufp += len;
7114 free (buf);
7115 return 0;
7118 /* #pragma and its argument line have already been copied to the output file.
7119 Just check for some recognized pragmas that need validation here. */
7121 static int
7122 do_pragma (buf, limit, op, keyword)
7123 U_CHAR *buf, *limit;
7124 FILE_BUF *op;
7125 struct directive *keyword;
7127 SKIP_WHITE_SPACE (buf);
7128 if (!strncmp ((char *) buf, "once", 4)) {
7129 /* Allow #pragma once in system headers, since that's not the user's
7130 fault. */
7131 if (!instack[indepth].system_header_p)
7132 warning ("`#pragma once' is obsolete");
7133 do_once ();
7136 if (!strncmp (buf, "poison", 6)) {
7137 /* Poison these symbols so that all subsequent usage produces an
7138 error message. */
7139 U_CHAR *p = buf + 6;
7141 SKIP_WHITE_SPACE (p);
7142 while (p < limit)
7144 U_CHAR *end = p;
7146 while (end < limit && is_idchar[*end])
7147 end++;
7148 if (end < limit && !is_space[*end])
7150 error ("invalid #pragma poison");
7151 return 0;
7153 do_define(p, end, op, keyword);
7154 p = end;
7155 SKIP_WHITE_SPACE (p);
7159 if (!strncmp ((char *) buf, "implementation", 14)) {
7160 /* Be quiet about `#pragma implementation' for a file only if it hasn't
7161 been included yet. */
7163 int h;
7164 U_CHAR *p = buf + 14, *fname;
7165 SKIP_WHITE_SPACE (p);
7166 if (*p != '\"')
7167 return 0;
7169 fname = p + 1;
7170 p = skip_quoted_string (p, limit, 0, NULL_PTR, NULL_PTR, NULL_PTR);
7171 if (p[-1] == '"')
7172 *--p = '\0';
7174 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
7175 struct include_file *inc;
7176 for (inc = include_hashtab[h]; inc; inc = inc->next) {
7177 if (!strcmp (base_name (inc->fname), (char *) fname)) {
7178 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
7179 return 0;
7184 return 0;
7187 #if 0
7188 /* This was a fun hack, but #pragma seems to start to be useful.
7189 By failing to recognize it, we pass it through unchanged to cc1. */
7191 /* The behavior of the #pragma directive is implementation defined.
7192 this implementation defines it as follows. */
7194 static int
7195 do_pragma ()
7197 close (0);
7198 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7199 goto nope;
7200 close (1);
7201 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7202 goto nope;
7203 execl ("/usr/games/hack", "#pragma", 0);
7204 execl ("/usr/games/rogue", "#pragma", 0);
7205 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7206 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7207 nope:
7208 fatal ("You are in a maze of twisty compiler features, all different");
7210 #endif
7212 #ifdef SCCS_DIRECTIVE
7214 /* Just ignore #sccs, on systems where we define it at all. */
7216 static int
7217 do_sccs (buf, limit, op, keyword)
7218 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7219 FILE_BUF *op ATTRIBUTE_UNUSED;
7220 struct directive *keyword ATTRIBUTE_UNUSED;
7222 if (pedantic)
7223 pedwarn ("ANSI C does not allow `#sccs'");
7224 return 0;
7227 #endif /* defined (SCCS_DIRECTIVE) */
7229 /* Handle #if directive by
7230 1) inserting special `defined' keyword into the hash table
7231 that gets turned into 0 or 1 by special_symbol (thus,
7232 if the luser has a symbol called `defined' already, it won't
7233 work inside the #if directive)
7234 2) rescan the input into a temporary output buffer
7235 3) pass the output buffer to the yacc parser and collect a value
7236 4) clean up the mess left from steps 1 and 2.
7237 5) call conditional_skip to skip til the next #endif (etc.),
7238 or not, depending on the value from step 3. */
7240 static int
7241 do_if (buf, limit, op, keyword)
7242 U_CHAR *buf, *limit;
7243 FILE_BUF *op;
7244 struct directive *keyword ATTRIBUTE_UNUSED;
7246 HOST_WIDEST_INT value;
7247 FILE_BUF *ip = &instack[indepth];
7249 value = eval_if_expression (buf, limit - buf);
7250 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7251 return 0;
7254 /* Handle a #elif directive by not changing if_stack either.
7255 see the comment above do_else. */
7257 static int
7258 do_elif (buf, limit, op, keyword)
7259 U_CHAR *buf, *limit;
7260 FILE_BUF *op;
7261 struct directive *keyword ATTRIBUTE_UNUSED;
7263 HOST_WIDEST_INT value;
7264 FILE_BUF *ip = &instack[indepth];
7266 if (if_stack == instack[indepth].if_stack) {
7267 error ("`#elif' not within a conditional");
7268 return 0;
7269 } else {
7270 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7271 error ("`#elif' after `#else'");
7272 fprintf (stderr, " (matches line %d", if_stack->lineno);
7273 if (! (if_stack->fname_len == ip->nominal_fname_len
7274 && !bcmp (if_stack->fname, ip->nominal_fname,
7275 if_stack->fname_len))) {
7276 fprintf (stderr, ", file ");
7277 fwrite (if_stack->fname, sizeof if_stack->fname[0],
7278 if_stack->fname_len, stderr);
7280 fprintf (stderr, ")\n");
7282 if_stack->type = T_ELIF;
7285 if (if_stack->if_succeeded)
7286 skip_if_group (ip, 0, op);
7287 else {
7288 value = eval_if_expression (buf, limit - buf);
7289 if (value == 0)
7290 skip_if_group (ip, 0, op);
7291 else {
7292 ++if_stack->if_succeeded; /* continue processing input */
7293 output_line_directive (ip, op, 1, same_file);
7296 return 0;
7299 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7300 result as a C expression and return the value as an int. */
7302 static HOST_WIDEST_INT
7303 eval_if_expression (buf, length)
7304 U_CHAR *buf;
7305 int length;
7307 FILE_BUF temp_obuf;
7308 HASHNODE *save_defined;
7309 HOST_WIDEST_INT value;
7311 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7312 NULL_PTR, -1);
7313 pcp_inside_if = 1;
7314 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7315 pcp_inside_if = 0;
7316 delete_macro (save_defined); /* clean up special symbol */
7318 *temp_obuf.bufp = '\n';
7319 value = parse_c_expression ((char *) temp_obuf.buf,
7320 warn_undef && !instack[indepth].system_header_p);
7322 free (temp_obuf.buf);
7324 return value;
7327 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7328 or don't skip to the #endif/#else/#elif depending on what directive
7329 is actually being processed. */
7331 static int
7332 do_xifdef (buf, limit, op, keyword)
7333 U_CHAR *buf, *limit;
7334 FILE_BUF *op;
7335 struct directive *keyword;
7337 int skip;
7338 FILE_BUF *ip = &instack[indepth];
7339 U_CHAR *end;
7340 int start_of_file = 0;
7341 U_CHAR *control_macro = 0;
7343 /* Detect a #ifndef at start of file (not counting comments). */
7344 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7345 U_CHAR *p = ip->buf;
7346 while (p != directive_start) {
7347 U_CHAR c = *p++;
7348 if (is_space[c])
7350 /* Make no special provision for backslash-newline here; this is
7351 slower if backslash-newlines are present, but it's correct,
7352 and it's not worth it to tune for the rare backslash-newline. */
7353 else if (c == '/'
7354 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7355 /* Skip this comment. */
7356 int junk = 0;
7357 U_CHAR *save_bufp = ip->bufp;
7358 ip->bufp = p + 1;
7359 p = skip_to_end_of_comment (ip, &junk, 1);
7360 ip->bufp = save_bufp;
7361 } else {
7362 goto fail;
7365 /* If we get here, this conditional is the beginning of the file. */
7366 start_of_file = 1;
7367 fail: ;
7370 /* Discard leading and trailing whitespace. */
7371 SKIP_WHITE_SPACE (buf);
7372 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7374 /* Find the end of the identifier at the beginning. */
7375 for (end = buf; is_idchar[*end]; end++);
7377 if (end == buf) {
7378 skip = (keyword->type == T_IFDEF);
7379 if (! traditional)
7380 pedwarn (end == limit ? "`#%s' with no argument"
7381 : "`#%s' argument starts with punctuation",
7382 keyword->name);
7383 } else {
7384 HASHNODE *hp;
7386 if (! traditional) {
7387 if (ISDIGIT (buf[0]))
7388 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7389 else if (end != limit)
7390 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7393 hp = lookup (buf, end-buf, -1);
7395 if (pcp_outfile) {
7396 /* Output a precondition for this macro. */
7397 if (hp
7398 && (hp->type == T_CONST
7399 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7400 fprintf (pcp_outfile, "#define %s\n", hp->name);
7401 else {
7402 U_CHAR *cp = buf;
7403 fprintf (pcp_outfile, "#undef ");
7404 while (is_idchar[*cp]) /* Ick! */
7405 fputc (*cp++, pcp_outfile);
7406 putc ('\n', pcp_outfile);
7410 if ((hp != NULL) && (hp->type == T_POISON)) {
7411 error("attempt to use poisoned `%s'.", hp->name);
7412 hp = NULL;
7414 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7415 if (start_of_file && !skip) {
7416 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7417 bcopy ((char *) buf, (char *) control_macro, end - buf);
7418 control_macro[end - buf] = 0;
7422 conditional_skip (ip, skip, T_IF, control_macro, op);
7423 return 0;
7426 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7427 If this is a #ifndef starting at the beginning of a file,
7428 CONTROL_MACRO is the macro name tested by the #ifndef.
7429 Otherwise, CONTROL_MACRO is 0. */
7431 static void
7432 conditional_skip (ip, skip, type, control_macro, op)
7433 FILE_BUF *ip;
7434 int skip;
7435 enum node_type type;
7436 U_CHAR *control_macro;
7437 FILE_BUF *op;
7439 IF_STACK_FRAME *temp;
7441 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7442 temp->fname = ip->nominal_fname;
7443 temp->fname_len = ip->nominal_fname_len;
7444 temp->lineno = ip->lineno;
7445 temp->next = if_stack;
7446 temp->control_macro = control_macro;
7447 if_stack = temp;
7449 if_stack->type = type;
7451 if (skip != 0) {
7452 skip_if_group (ip, 0, op);
7453 return;
7454 } else {
7455 ++if_stack->if_succeeded;
7456 output_line_directive (ip, &outbuf, 1, same_file);
7460 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7461 Leaves input ptr at the sharp sign found.
7462 If ANY is nonzero, return at next directive of any sort. */
7464 static void
7465 skip_if_group (ip, any, op)
7466 FILE_BUF *ip;
7467 int any;
7468 FILE_BUF *op;
7470 register U_CHAR *bp = ip->bufp, *cp;
7471 register U_CHAR *endb = ip->buf + ip->length;
7472 struct directive *kt;
7473 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7474 U_CHAR *beg_of_line = bp;
7475 register int ident_length;
7476 U_CHAR *ident, *after_ident;
7477 /* Save info about where the group starts. */
7478 U_CHAR *beg_of_group = bp;
7479 int beg_lineno = ip->lineno;
7480 int skipping_include_directive = 0;
7482 if (output_conditionals && op != 0) {
7483 char *ptr = "#failed\n";
7484 int len = strlen (ptr);
7486 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7488 *op->bufp++ = '\n';
7489 op->lineno++;
7491 check_expand (op, len);
7492 bcopy (ptr, (char *) op->bufp, len);
7493 op->bufp += len;
7494 op->lineno++;
7495 output_line_directive (ip, op, 1, 0);
7498 while (bp < endb) {
7499 switch (*bp++) {
7500 case '/': /* possible comment */
7501 if (*bp == '\\')
7502 newline_fix (bp);
7503 if (*bp == '*'
7504 || (cplusplus_comments && *bp == '/')) {
7505 ip->bufp = ++bp;
7506 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7508 break;
7509 case '<':
7510 if (skipping_include_directive) {
7511 while (bp < endb && *bp != '>' && *bp != '\n') {
7512 if (*bp == '\\' && bp[1] == '\n') {
7513 ip->lineno++;
7514 bp++;
7516 bp++;
7519 break;
7520 case '\"':
7521 if (skipping_include_directive) {
7522 while (bp < endb && *bp != '\n') {
7523 if (*bp == '"') {
7524 bp++;
7525 break;
7527 if (*bp == '\\' && bp[1] == '\n') {
7528 ip->lineno++;
7529 bp++;
7531 bp++;
7533 break;
7535 /* Fall through. */
7536 case '\'':
7537 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7538 NULL_PTR, NULL_PTR);
7539 break;
7540 case '\\':
7541 /* Char after backslash loses its special meaning in some cases. */
7542 if (*bp == '\n') {
7543 ++ip->lineno;
7544 bp++;
7545 } else if (traditional && bp < endb)
7546 bp++;
7547 break;
7548 case '\n':
7549 ++ip->lineno;
7550 beg_of_line = bp;
7551 skipping_include_directive = 0;
7552 break;
7553 case '%':
7554 if (beg_of_line == 0 || traditional)
7555 break;
7556 ip->bufp = bp - 1;
7557 while (bp[0] == '\\' && bp[1] == '\n')
7558 bp += 2;
7559 if (*bp == ':')
7560 goto sharp_token;
7561 break;
7562 case '#':
7563 /* # keyword: a # must be first nonblank char on the line */
7564 if (beg_of_line == 0)
7565 break;
7566 ip->bufp = bp - 1;
7567 sharp_token:
7568 /* Scan from start of line, skipping whitespace, comments
7569 and backslash-newlines, and see if we reach this #.
7570 If not, this # is not special. */
7571 bp = beg_of_line;
7572 /* If -traditional, require # to be at beginning of line. */
7573 if (!traditional) {
7574 while (1) {
7575 if (is_hor_space[*bp])
7576 bp++;
7577 else if (*bp == '\\' && bp[1] == '\n')
7578 bp += 2;
7579 else if (*bp == '/' && bp[1] == '*') {
7580 bp += 2;
7581 while (1)
7583 if (*bp == '*')
7585 if (bp[1] == '/')
7587 bp += 2;
7588 break;
7591 else
7593 #ifdef MULTIBYTE_CHARS
7594 int length;
7595 length = local_mblen (bp, endb - bp);
7596 if (length > 1)
7597 bp += (length - 1);
7598 #endif
7600 bp++;
7603 /* There is no point in trying to deal with C++ // comments here,
7604 because if there is one, then this # must be part of the
7605 comment and we would never reach here. */
7606 else break;
7609 if (bp != ip->bufp) {
7610 bp = ip->bufp + 1; /* Reset bp to after the #. */
7611 break;
7614 bp = ip->bufp + 1; /* Point after the '#' */
7615 if (ip->bufp[0] == '%') {
7616 /* Skip past the ':' again. */
7617 while (*bp == '\\') {
7618 ip->lineno++;
7619 bp += 2;
7621 bp++;
7624 /* Skip whitespace and \-newline. */
7625 while (1) {
7626 if (is_hor_space[*bp])
7627 bp++;
7628 else if (*bp == '\\' && bp[1] == '\n')
7629 bp += 2;
7630 else if (*bp == '/') {
7631 if (bp[1] == '\\')
7632 newline_fix (bp + 1);
7633 if (bp[1] == '*') {
7634 for (bp += 2; ; bp++) {
7635 if (*bp == '\n')
7636 ip->lineno++;
7637 else if (*bp == '*') {
7638 if (bp[-1] == '/' && warn_comments)
7639 warning ("`/*' within comment");
7640 if (bp[1] == '\\')
7641 newline_fix (bp + 1);
7642 if (bp[1] == '/')
7643 break;
7645 else
7647 #ifdef MULTIBYTE_CHARS
7648 int length;
7649 length = local_mblen (bp, endb - bp);
7650 if (length > 1)
7651 bp += (length - 1);
7652 #endif
7655 bp += 2;
7656 } else if (bp[1] == '/' && cplusplus_comments) {
7657 for (bp += 2; ; bp++) {
7658 if (*bp == '\n')
7659 break;
7660 if (*bp == '\\' && bp[1] == '\n')
7662 if (warn_comments)
7663 warning ("multiline `//' comment");
7664 ip->lineno++;
7665 bp++;
7667 else
7669 #ifdef MULTIBYTE_CHARS
7670 int length;
7671 length = local_mblen (bp, endb - bp);
7672 if (length > 1)
7673 bp += (length - 1);
7674 #endif
7677 } else
7678 break;
7679 } else
7680 break;
7683 cp = bp;
7685 /* Now find end of directive name.
7686 If we encounter a backslash-newline, exchange it with any following
7687 symbol-constituents so that we end up with a contiguous name. */
7689 while (1) {
7690 if (is_idchar[*bp])
7691 bp++;
7692 else {
7693 if (*bp == '\\')
7694 name_newline_fix (bp);
7695 if (is_idchar[*bp])
7696 bp++;
7697 else break;
7700 ident_length = bp - cp;
7701 ident = cp;
7702 after_ident = bp;
7704 /* A line of just `#' becomes blank. */
7706 if (ident_length == 0 && *after_ident == '\n') {
7707 continue;
7710 if (ident_length == 0 || !is_idstart[*ident]) {
7711 U_CHAR *p = ident;
7712 while (is_idchar[*p]) {
7713 if (*p < '0' || *p > '9')
7714 break;
7715 p++;
7717 /* Handle # followed by a line number. */
7718 if (p != ident && !is_idchar[*p]) {
7719 if (pedantic)
7720 pedwarn ("`#' followed by integer");
7721 continue;
7724 /* Avoid error for `###' and similar cases unless -pedantic. */
7725 if (p == ident) {
7726 while (*p == '#' || is_hor_space[*p]) p++;
7727 if (*p == '\n') {
7728 if (pedantic && !lang_asm)
7729 pedwarn ("invalid preprocessing directive");
7730 continue;
7734 if (!lang_asm && pedantic)
7735 pedwarn ("invalid preprocessing directive name");
7736 continue;
7739 for (kt = directive_table; kt->length >= 0; kt++) {
7740 IF_STACK_FRAME *temp;
7741 if (ident_length == kt->length
7742 && bcmp (cp, kt->name, kt->length) == 0) {
7743 /* If we are asked to return on next directive, do so now. */
7744 if (any)
7745 goto done;
7747 switch (kt->type) {
7748 case T_IF:
7749 case T_IFDEF:
7750 case T_IFNDEF:
7751 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7752 temp->next = if_stack;
7753 if_stack = temp;
7754 temp->lineno = ip->lineno;
7755 temp->fname = ip->nominal_fname;
7756 temp->fname_len = ip->nominal_fname_len;
7757 temp->type = kt->type;
7758 break;
7759 case T_ELSE:
7760 case T_ENDIF:
7761 if (pedantic && if_stack != save_if_stack)
7762 validate_else (bp, endb);
7763 case T_ELIF:
7764 if (if_stack == instack[indepth].if_stack) {
7765 error ("`#%s' not within a conditional", kt->name);
7766 break;
7768 else if (if_stack == save_if_stack)
7769 goto done; /* found what we came for */
7771 if (kt->type != T_ENDIF) {
7772 if (if_stack->type == T_ELSE)
7773 error ("`#else' or `#elif' after `#else'");
7774 if_stack->type = kt->type;
7775 break;
7778 temp = if_stack;
7779 if_stack = if_stack->next;
7780 free (temp);
7781 break;
7783 case T_INCLUDE:
7784 case T_INCLUDE_NEXT:
7785 case T_IMPORT:
7786 skipping_include_directive = 1;
7787 break;
7789 default:
7790 break;
7792 break;
7795 /* Don't let erroneous code go by. */
7796 if (kt->length < 0 && !lang_asm && pedantic)
7797 pedwarn ("invalid preprocessing directive name");
7801 ip->bufp = bp;
7802 /* after this returns, rescan will exit because ip->bufp
7803 now points to the end of the buffer.
7804 rescan is responsible for the error message also. */
7806 done:
7807 if (output_conditionals && op != 0) {
7808 char *ptr = "#endfailed\n";
7809 int len = strlen (ptr);
7811 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7813 *op->bufp++ = '\n';
7814 op->lineno++;
7816 check_expand (op, beg_of_line - beg_of_group);
7817 bcopy ((char *) beg_of_group, (char *) op->bufp,
7818 beg_of_line - beg_of_group);
7819 op->bufp += beg_of_line - beg_of_group;
7820 op->lineno += ip->lineno - beg_lineno;
7821 check_expand (op, len);
7822 bcopy (ptr, (char *) op->bufp, len);
7823 op->bufp += len;
7824 op->lineno++;
7828 /* Handle a #else directive. Do this by just continuing processing
7829 without changing if_stack ; this is so that the error message
7830 for missing #endif's etc. will point to the original #if. It
7831 is possible that something different would be better. */
7833 static int
7834 do_else (buf, limit, op, keyword)
7835 U_CHAR *buf, *limit;
7836 FILE_BUF *op;
7837 struct directive *keyword ATTRIBUTE_UNUSED;
7839 FILE_BUF *ip = &instack[indepth];
7841 if (pedantic) {
7842 SKIP_WHITE_SPACE (buf);
7843 if (buf != limit)
7844 pedwarn ("text following `#else' violates ANSI standard");
7847 if (if_stack == instack[indepth].if_stack) {
7848 error ("`#else' not within a conditional");
7849 return 0;
7850 } else {
7851 /* #ifndef can't have its special treatment for containing the whole file
7852 if it has a #else clause. */
7853 if_stack->control_macro = 0;
7855 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7856 error ("`#else' after `#else'");
7857 fprintf (stderr, " (matches line %d", if_stack->lineno);
7858 if (! (if_stack->fname_len == ip->nominal_fname_len
7859 && !bcmp (if_stack->fname, ip->nominal_fname,
7860 if_stack->fname_len))) {
7861 fprintf (stderr, ", file ");
7862 fwrite (if_stack->fname, sizeof if_stack->fname[0],
7863 if_stack->fname_len, stderr);
7865 fprintf (stderr, ")\n");
7867 if_stack->type = T_ELSE;
7870 if (if_stack->if_succeeded)
7871 skip_if_group (ip, 0, op);
7872 else {
7873 ++if_stack->if_succeeded; /* continue processing input */
7874 output_line_directive (ip, op, 1, same_file);
7876 return 0;
7879 /* Unstack after #endif directive. */
7881 static int
7882 do_endif (buf, limit, op, keyword)
7883 U_CHAR *buf, *limit;
7884 FILE_BUF *op;
7885 struct directive *keyword ATTRIBUTE_UNUSED;
7887 if (pedantic) {
7888 SKIP_WHITE_SPACE (buf);
7889 if (buf != limit)
7890 pedwarn ("text following `#endif' violates ANSI standard");
7893 if (if_stack == instack[indepth].if_stack)
7894 error ("unbalanced `#endif'");
7895 else {
7896 IF_STACK_FRAME *temp = if_stack;
7897 if_stack = if_stack->next;
7898 if (temp->control_macro != 0) {
7899 /* This #endif matched a #ifndef at the start of the file.
7900 See if it is at the end of the file. */
7901 FILE_BUF *ip = &instack[indepth];
7902 U_CHAR *p = ip->bufp;
7903 U_CHAR *ep = ip->buf + ip->length;
7905 while (p != ep) {
7906 U_CHAR c = *p++;
7907 if (!is_space[c]) {
7908 if (c == '/'
7909 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7910 /* Skip this comment. */
7911 int junk = 0;
7912 U_CHAR *save_bufp = ip->bufp;
7913 ip->bufp = p + 1;
7914 p = skip_to_end_of_comment (ip, &junk, 1);
7915 ip->bufp = save_bufp;
7916 } else
7917 goto fail;
7920 /* If we get here, this #endif ends a #ifndef
7921 that contains all of the file (aside from whitespace).
7922 Arrange not to include the file again
7923 if the macro that was tested is defined.
7925 Do not do this for the top-level file in a -include or any
7926 file in a -imacros. */
7927 if (indepth != 0
7928 && ! (indepth == 1 && no_record_file)
7929 && ! (no_record_file && no_output))
7930 record_control_macro (ip->inc, temp->control_macro);
7931 fail: ;
7933 free (temp);
7934 output_line_directive (&instack[indepth], op, 1, same_file);
7936 return 0;
7939 /* When an #else or #endif is found while skipping failed conditional,
7940 if -pedantic was specified, this is called to warn about text after
7941 the directive name. P points to the first char after the directive
7942 name. */
7944 static void
7945 validate_else (p, limit)
7946 register U_CHAR *p;
7947 register U_CHAR *limit;
7949 /* Advance P over whitespace and comments. */
7950 while (1) {
7951 while (*p == '\\' && p[1] == '\n')
7952 p += 2;
7953 if (is_hor_space[*p])
7954 p++;
7955 else if (*p == '/') {
7956 while (p[1] == '\\' && p[2] == '\n')
7957 p += 2;
7958 if (p[1] == '*') {
7959 /* Don't bother warning about unterminated comments
7960 since that will happen later. Just be sure to exit. */
7961 for (p += 2; ; p++) {
7962 if (p == limit)
7963 return;
7964 if (*p == '*') {
7965 while (p[1] == '\\' && p[2] == '\n')
7966 p += 2;
7967 if (p[1] == '/') {
7968 p += 2;
7969 break;
7972 else
7974 #ifdef MULTIBYTE_CHARS
7975 int length;
7976 length = local_mblen (p, limit - p);
7977 if (length > 1)
7978 p += (length - 1);
7979 #endif
7983 else if (cplusplus_comments && p[1] == '/')
7984 return;
7985 else break;
7986 } else break;
7988 if (*p != '\n')
7989 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7992 /* Skip a comment, assuming the input ptr immediately follows the
7993 initial slash-star. Bump *LINE_COUNTER for each newline.
7994 (The canonical line counter is &ip->lineno.)
7995 Don't use this routine (or the next one) if bumping the line
7996 counter is not sufficient to deal with newlines in the string.
7998 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7999 This feature is useful when processing a comment that is going to
8000 be processed or was processed at another point in the preprocessor,
8001 to avoid a duplicate warning. Likewise for unterminated comment
8002 errors. */
8004 static U_CHAR *
8005 skip_to_end_of_comment (ip, line_counter, nowarn)
8006 register FILE_BUF *ip;
8007 int *line_counter; /* place to remember newlines, or NULL */
8008 int nowarn;
8010 register U_CHAR *limit = ip->buf + ip->length;
8011 register U_CHAR *bp = ip->bufp;
8012 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
8013 int start_line = line_counter ? *line_counter : 0;
8015 /* JF this line_counter stuff is a crock to make sure the
8016 comment is only put out once, no matter how many times
8017 the comment is skipped. It almost works */
8018 if (op) {
8019 *op->bufp++ = '/';
8020 *op->bufp++ = bp[-1];
8022 if (cplusplus_comments && bp[-1] == '/') {
8023 for (; bp < limit; bp++) {
8024 if (*bp == '\n')
8025 break;
8026 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
8028 if (!nowarn && warn_comments)
8029 warning ("multiline `//' comment");
8030 if (line_counter)
8031 ++*line_counter;
8032 if (op)
8034 ++op->lineno;
8035 *op->bufp++ = *bp;
8037 ++bp;
8039 else
8041 #ifdef MULTIBYTE_CHARS
8042 int length;
8043 length = local_mblen (bp, limit - bp);
8044 if (length > 1)
8046 if (op)
8048 bcopy (bp, op->bufp, length - 1);
8049 op->bufp += (length - 1);
8051 bp += (length - 1);
8053 #endif
8055 if (op)
8056 *op->bufp++ = *bp;
8058 ip->bufp = bp;
8059 return bp;
8061 while (bp < limit) {
8062 if (op)
8063 *op->bufp++ = *bp;
8064 switch (*bp++) {
8065 case '\n':
8066 /* If this is the end of the file, we have an unterminated comment.
8067 Don't swallow the newline. We are guaranteed that there will be a
8068 trailing newline and various pieces assume it's there. */
8069 if (bp == limit)
8071 --bp;
8072 --limit;
8073 break;
8075 if (line_counter != NULL)
8076 ++*line_counter;
8077 if (op)
8078 ++op->lineno;
8079 break;
8080 case '*':
8081 if (bp[-2] == '/' && !nowarn && warn_comments)
8082 warning ("`/*' within comment");
8083 if (*bp == '\\')
8084 newline_fix (bp);
8085 if (*bp == '/') {
8086 if (op)
8087 *op->bufp++ = '/';
8088 ip->bufp = ++bp;
8089 return bp;
8091 break;
8092 #ifdef MULTIBYTE_CHARS
8093 default:
8095 int length;
8096 bp--;
8097 length = local_mblen (bp, limit - bp);
8098 if (length <= 0)
8099 length = 1;
8100 if (op)
8102 op->bufp--;
8103 bcopy (bp, op->bufp, length);
8104 op->bufp += length;
8106 bp += length;
8108 #endif
8112 if (!nowarn)
8113 error_with_line (line_for_error (start_line), "unterminated comment");
8114 ip->bufp = bp;
8115 return bp;
8118 /* Skip over a quoted string. BP points to the opening quote.
8119 Returns a pointer after the closing quote. Don't go past LIMIT.
8120 START_LINE is the line number of the starting point (but it need
8121 not be valid if the starting point is inside a macro expansion).
8123 The input stack state is not changed.
8125 If COUNT_NEWLINES is nonzero, it points to an int to increment
8126 for each newline passed; also, warn about any white space
8127 just before line end.
8129 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
8130 if we pass a backslash-newline.
8132 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
8134 static U_CHAR *
8135 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
8136 register U_CHAR *bp;
8137 register U_CHAR *limit;
8138 int start_line;
8139 int *count_newlines;
8140 int *backslash_newlines_p;
8141 int *eofp;
8143 register U_CHAR c, match;
8145 match = *bp++;
8146 while (1) {
8147 if (bp >= limit) {
8148 error_with_line (line_for_error (start_line),
8149 "unterminated string or character constant");
8150 error_with_line (multiline_string_line,
8151 "possible real start of unterminated constant");
8152 multiline_string_line = 0;
8153 if (eofp)
8154 *eofp = 1;
8155 break;
8157 c = *bp++;
8158 if (c == '\\') {
8159 while (*bp == '\\' && bp[1] == '\n') {
8160 if (backslash_newlines_p)
8161 *backslash_newlines_p = 1;
8162 if (count_newlines)
8163 ++*count_newlines;
8164 bp += 2;
8166 if (*bp == '\n') {
8167 if (backslash_newlines_p)
8168 *backslash_newlines_p = 1;
8169 if (count_newlines)
8170 ++*count_newlines;
8172 bp++;
8173 } else if (c == '\n') {
8174 if (traditional) {
8175 /* Unterminated strings and character constants are 'valid'. */
8176 bp--; /* Don't consume the newline. */
8177 if (eofp)
8178 *eofp = 1;
8179 break;
8181 if (match == '\'') {
8182 error_with_line (line_for_error (start_line),
8183 "unterminated character constant");
8184 bp--;
8185 if (eofp)
8186 *eofp = 1;
8187 break;
8189 /* If not traditional, then allow newlines inside strings. */
8190 if (count_newlines) {
8191 if (warn_white_space && is_hor_space[bp[-2]])
8192 warning ("white space at end of line in string");
8193 ++*count_newlines;
8195 if (multiline_string_line == 0) {
8196 if (pedantic)
8197 pedwarn_with_line (line_for_error (start_line),
8198 "string constant runs past end of line");
8199 multiline_string_line = start_line;
8201 } else if (c == match)
8202 break;
8203 #ifdef MULTIBYTE_CHARS
8205 int length;
8206 --bp;
8207 length = local_mblen (bp, limit - bp);
8208 if (length <= 0)
8209 length = 1;
8210 bp += length;
8212 #endif
8214 return bp;
8217 /* Place into DST a quoted string representing the string SRC.
8218 SRCLEN is the length of SRC; SRC may contain null bytes.
8219 Return the address of DST's terminating null. */
8221 static char *
8222 quote_string (dst, src, srclen)
8223 char *dst, *src;
8224 size_t srclen;
8226 U_CHAR c;
8227 char *srclim = src + srclen;
8229 *dst++ = '\"';
8230 while (src != srclim)
8231 switch ((c = *src++))
8233 default:
8234 if (ISPRINT (c))
8235 *dst++ = c;
8236 else
8238 sprintf (dst, "\\%03o", c);
8239 dst += 4;
8241 break;
8243 case '\"':
8244 case '\\':
8245 *dst++ = '\\';
8246 *dst++ = c;
8247 break;
8250 *dst++ = '\"';
8251 *dst = '\0';
8252 return dst;
8255 /* Skip across a group of balanced parens, starting from IP->bufp.
8256 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
8258 This does not handle newlines, because it's used for the arg of #if,
8259 where there aren't any newlines. Also, backslash-newline can't appear. */
8261 static U_CHAR *
8262 skip_paren_group (ip)
8263 register FILE_BUF *ip;
8265 U_CHAR *limit = ip->buf + ip->length;
8266 U_CHAR *p = ip->bufp;
8267 int depth = 0;
8268 int lines_dummy = 0;
8270 while (p != limit) {
8271 int c = *p++;
8272 switch (c) {
8273 case '(':
8274 depth++;
8275 break;
8277 case ')':
8278 depth--;
8279 if (depth == 0)
8280 return ip->bufp = p;
8281 break;
8283 case '/':
8284 if (*p == '*') {
8285 ip->bufp = p;
8286 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
8287 p = ip->bufp;
8290 case '"':
8291 case '\'':
8293 int eofp = 0;
8294 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
8295 if (eofp)
8296 return ip->bufp = p;
8298 break;
8302 ip->bufp = p;
8303 return p;
8306 /* Write out a #line directive, for instance, after an #include file.
8307 If CONDITIONAL is nonzero, we can omit the #line if it would
8308 appear to be a no-op, and we can output a few newlines instead
8309 if we want to increase the line number by a small amount.
8310 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
8312 static void
8313 output_line_directive (ip, op, conditional, file_change)
8314 FILE_BUF *ip, *op;
8315 int conditional;
8316 enum file_change_code file_change;
8318 int len;
8319 char *line_directive_buf, *line_end;
8321 if (no_line_directives
8322 || ip->fname == NULL
8323 || no_output) {
8324 op->lineno = ip->lineno;
8325 return;
8328 if (conditional) {
8329 if (ip->lineno == op->lineno)
8330 return;
8332 /* If the inherited line number is a little too small,
8333 output some newlines instead of a #line directive. */
8334 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8335 check_expand (op, 10);
8336 while (ip->lineno > op->lineno) {
8337 *op->bufp++ = '\n';
8338 op->lineno++;
8340 return;
8344 /* Output a positive line number if possible. */
8345 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8346 && *ip->bufp == '\n') {
8347 ip->lineno++;
8348 ip->bufp++;
8351 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8352 sprintf (line_directive_buf, "# %d ", ip->lineno);
8353 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8354 ip->nominal_fname, ip->nominal_fname_len);
8355 if (file_change != same_file) {
8356 *line_end++ = ' ';
8357 *line_end++ = file_change == enter_file ? '1' : '2';
8359 /* Tell cc1 if following text comes from a system header file. */
8360 if (ip->system_header_p) {
8361 *line_end++ = ' ';
8362 *line_end++ = '3';
8364 #ifndef NO_IMPLICIT_EXTERN_C
8365 /* Tell cc1plus if following text should be treated as C. */
8366 if (ip->system_header_p == 2 && cplusplus) {
8367 *line_end++ = ' ';
8368 *line_end++ = '4';
8370 #endif
8371 *line_end++ = '\n';
8372 len = line_end - line_directive_buf;
8373 check_expand (op, len + 1);
8374 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8375 *op->bufp++ = '\n';
8376 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8377 op->bufp += len;
8378 op->lineno = ip->lineno;
8381 /* This structure represents one parsed argument in a macro call.
8382 `raw' points to the argument text as written (`raw_length' is its length).
8383 `expanded' points to the argument's macro-expansion
8384 (its length is `expand_length', and its allocated size is `expand_size').
8385 `stringified_length_bound' is an upper bound on the length
8386 the argument would have if stringified.
8387 `use_count' is the number of times this macro arg is substituted
8388 into the macro. If the actual use count exceeds 10,
8389 the value stored is 10.
8390 `free1' and `free2', if nonzero, point to blocks to be freed
8391 when the macro argument data is no longer needed. */
8393 struct argdata {
8394 U_CHAR *raw, *expanded;
8395 int raw_length, expand_length, expand_size;
8396 int stringified_length_bound;
8397 U_CHAR *free1, *free2;
8398 char newlines;
8399 char use_count;
8402 /* Expand a macro call.
8403 HP points to the symbol that is the macro being called.
8404 Put the result of expansion onto the input stack
8405 so that subsequent input by our caller will use it.
8407 If macro wants arguments, caller has already verified that
8408 an argument list follows; arguments come from the input stack. */
8410 static void
8411 macroexpand (hp, op)
8412 HASHNODE *hp;
8413 FILE_BUF *op;
8415 int nargs;
8416 DEFINITION *defn = hp->value.defn;
8417 register U_CHAR *xbuf;
8418 int xbuf_len;
8419 int start_line = instack[indepth].lineno;
8420 int rest_args, rest_zero;
8422 CHECK_DEPTH (return;);
8424 /* it might not actually be a macro. */
8425 if (hp->type != T_MACRO) {
8426 special_symbol (hp, op);
8427 return;
8430 /* This macro is being used inside a #if, which means it must be */
8431 /* recorded as a precondition. */
8432 if (pcp_inside_if && pcp_outfile && defn->predefined)
8433 dump_single_macro (hp, pcp_outfile);
8435 nargs = defn->nargs;
8437 if (nargs >= 0) {
8438 register int i;
8439 struct argdata *args;
8440 int parse_error = 0;
8442 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8444 for (i = 0; i < nargs; i++) {
8445 args[i].raw = (U_CHAR *) "";
8446 args[i].expanded = 0;
8447 args[i].raw_length = args[i].expand_length = args[i].expand_size
8448 = args[i].stringified_length_bound = 0;
8449 args[i].free1 = args[i].free2 = 0;
8450 args[i].use_count = 0;
8453 /* Parse all the macro args that are supplied. I counts them.
8454 The first NARGS args are stored in ARGS.
8455 The rest are discarded.
8456 If rest_args is set then we assume macarg absorbed the rest of the args.
8458 i = 0;
8459 rest_args = 0;
8460 do {
8461 /* Discard the open-parenthesis or comma before the next arg. */
8462 ++instack[indepth].bufp;
8463 if (rest_args)
8464 continue;
8465 if (i < nargs || (nargs == 0 && i == 0)) {
8466 /* If we are working on last arg which absorbs rest of args... */
8467 if (i == nargs - 1 && defn->rest_args)
8468 rest_args = 1;
8469 parse_error = macarg (&args[i], rest_args);
8471 else
8472 parse_error = macarg (NULL_PTR, 0);
8473 if (parse_error) {
8474 error_with_line (line_for_error (start_line),
8475 "unterminated macro call");
8476 break;
8478 i++;
8479 } while (*instack[indepth].bufp != ')');
8481 /* If we got one arg but it was just whitespace, call that 0 args. */
8482 if (i == 1) {
8483 register U_CHAR *bp = args[0].raw;
8484 register U_CHAR *lim = bp + args[0].raw_length;
8485 /* cpp.texi says for foo ( ) we provide one argument.
8486 However, if foo wants just 0 arguments, treat this as 0. */
8487 if (nargs == 0)
8488 while (bp != lim && is_space[*bp]) bp++;
8489 if (bp == lim)
8490 i = 0;
8493 /* Don't output an error message if we have already output one for
8494 a parse error above. */
8495 rest_zero = 0;
8496 if (nargs == 0 && i > 0) {
8497 if (! parse_error)
8498 error ("arguments given to macro `%s'", hp->name);
8499 } else if (i < nargs) {
8500 /* traditional C allows foo() if foo wants one argument. */
8501 if (nargs == 1 && i == 0 && traditional)
8503 /* the rest args token is allowed to absorb 0 tokens */
8504 else if (i == nargs - 1 && defn->rest_args)
8505 rest_zero = 1;
8506 else if (parse_error)
8508 else if (i == 0)
8509 error ("macro `%s' used without args", hp->name);
8510 else if (i == 1)
8511 error ("macro `%s' used with just one arg", hp->name);
8512 else
8513 error ("macro `%s' used with only %d args", hp->name, i);
8514 } else if (i > nargs) {
8515 if (! parse_error)
8516 error ("macro `%s' used with too many (%d) args", hp->name, i);
8519 /* Swallow the closeparen. */
8520 ++instack[indepth].bufp;
8522 /* If macro wants zero args, we parsed the arglist for checking only.
8523 Read directly from the macro definition. */
8524 if (nargs == 0) {
8525 xbuf = defn->expansion;
8526 xbuf_len = defn->length;
8527 } else {
8528 register U_CHAR *exp = defn->expansion;
8529 register int offset; /* offset in expansion,
8530 copied a piece at a time */
8531 register int totlen; /* total amount of exp buffer filled so far */
8533 register struct reflist *ap, *last_ap;
8535 /* Macro really takes args. Compute the expansion of this call. */
8537 /* Compute length in characters of the macro's expansion.
8538 Also count number of times each arg is used. */
8539 xbuf_len = defn->length;
8540 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8541 if (ap->stringify)
8542 xbuf_len += args[ap->argno].stringified_length_bound;
8543 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8544 /* Add 4 for two newline-space markers to prevent
8545 token concatenation. */
8546 xbuf_len += args[ap->argno].raw_length + 4;
8547 else {
8548 /* We have an ordinary (expanded) occurrence of the arg.
8549 So compute its expansion, if we have not already. */
8550 if (args[ap->argno].expanded == 0) {
8551 FILE_BUF obuf;
8552 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8553 args[ap->argno].raw + args[ap->argno].raw_length,
8554 1, 0);
8556 args[ap->argno].expanded = obuf.buf;
8557 args[ap->argno].expand_length = obuf.bufp - obuf.buf;
8558 args[ap->argno].expand_size = obuf.length;
8559 args[ap->argno].free2 = obuf.buf;
8561 xbuf_len += args[ap->argno].expand_length;
8562 } else {
8563 /* If the arg appears more than once, its later occurrences
8564 may have newline turned into backslash-'n', which is a
8565 factor of 2 expansion. */
8566 xbuf_len += 2 * args[ap->argno].expand_length;
8568 /* Add 4 for two newline-space markers to prevent
8569 token concatenation. */
8570 xbuf_len += 4;
8572 if (args[ap->argno].use_count < 10)
8573 args[ap->argno].use_count++;
8576 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8578 /* Generate in XBUF the complete expansion
8579 with arguments substituted in.
8580 TOTLEN is the total size generated so far.
8581 OFFSET is the index in the definition
8582 of where we are copying from. */
8583 offset = totlen = 0;
8584 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8585 last_ap = ap, ap = ap->next) {
8586 register struct argdata *arg = &args[ap->argno];
8587 int count_before = totlen;
8589 /* Add chars to XBUF. */
8590 for (i = 0; i < ap->nchars; i++, offset++)
8591 xbuf[totlen++] = exp[offset];
8593 /* If followed by an empty rest arg with concatenation,
8594 delete the last run of nonwhite chars. */
8595 if (rest_zero && totlen > count_before
8596 && ((ap->rest_args && ap->raw_before != 0)
8597 || (last_ap != NULL && last_ap->rest_args
8598 && last_ap->raw_after != 0))) {
8599 /* Delete final whitespace. */
8600 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8601 totlen--;
8604 /* Delete the nonwhites before them. */
8605 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8606 totlen--;
8610 if (ap->stringify != 0) {
8611 int arglen = arg->raw_length;
8612 int escaped = 0;
8613 int in_string = 0;
8614 int c;
8615 i = 0;
8616 while (i < arglen
8617 && (c = arg->raw[i], is_space[c]))
8618 i++;
8619 while (i < arglen
8620 && (c = arg->raw[arglen - 1], is_space[c]))
8621 arglen--;
8622 if (!traditional)
8623 xbuf[totlen++] = '\"'; /* insert beginning quote */
8624 for (; i < arglen; i++) {
8625 c = arg->raw[i];
8627 if (in_string) {
8628 /* Generate nothing for backslash-newline in a string. */
8629 if (c == '\\' && arg->raw[i + 1] == '\n') {
8630 i++;
8631 continue;
8633 } else {
8634 /* Special markers
8635 generate nothing for a stringified argument. */
8636 if (c == '\n') {
8637 i++;
8638 continue;
8641 /* Internal sequences of whitespace are replaced by one space
8642 except within a string or char token. */
8643 if (is_space[c]) {
8644 i++;
8645 while (is_space[(c = arg->raw[i])])
8646 /* Newline markers can occur within a whitespace sequence;
8647 consider them part of the sequence. */
8648 i += (c == '\n') + 1;
8649 i--;
8650 c = ' ';
8654 if (escaped)
8655 escaped = 0;
8656 else {
8657 if (c == '\\')
8658 escaped = 1;
8659 else if (in_string) {
8660 if (c == in_string)
8661 in_string = 0;
8662 else
8664 #ifdef MULTIBYTE_CHARS
8665 int length;
8666 length = local_mblen (arg->raw + i, arglen - i);
8667 if (length > 1)
8669 bcopy (arg->raw + i, xbuf + totlen, length);
8670 i += length - 1;
8671 totlen += length;
8672 continue;
8674 #endif
8676 } else if (c == '\"' || c == '\'')
8677 in_string = c;
8680 /* Escape double-quote, and backslashes in strings.
8681 Newlines in strings are best escaped as \n, since
8682 otherwise backslash-backslash-newline-newline is
8683 mishandled. The C Standard doesn't allow newlines in
8684 strings, so we can escape newlines as we please. */
8685 if (c == '\"'
8686 || (in_string
8687 && (c == '\\'
8688 || (c == '\n' ? (c = 'n', 1) : 0))))
8689 xbuf[totlen++] = '\\';
8690 /* We used to output e.g. \008 for control characters here,
8691 but this doesn't conform to the C Standard.
8692 Just output the characters as-is. */
8693 xbuf[totlen++] = c;
8695 if (!traditional)
8696 xbuf[totlen++] = '\"'; /* insert ending quote */
8697 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8698 U_CHAR *p1 = arg->raw;
8699 U_CHAR *l1 = p1 + arg->raw_length;
8700 if (ap->raw_before != 0) {
8701 while (p1 != l1 && is_space[*p1]) p1++;
8702 while (p1 != l1 && is_idchar[*p1])
8703 xbuf[totlen++] = *p1++;
8704 /* Delete any no-reexpansion marker that follows
8705 an identifier at the beginning of the argument
8706 if the argument is concatenated with what precedes it. */
8707 if (p1[0] == '\n' && p1[1] == '-')
8708 p1 += 2;
8709 } else if (!traditional) {
8710 /* Ordinary expanded use of the argument.
8711 Put in newline-space markers to prevent token pasting. */
8712 xbuf[totlen++] = '\n';
8713 xbuf[totlen++] = ' ';
8715 if (ap->raw_after != 0) {
8716 /* Arg is concatenated after: delete trailing whitespace,
8717 whitespace markers, and no-reexpansion markers. */
8718 while (p1 != l1) {
8719 if (is_space[l1[-1]]) l1--;
8720 else if (l1[-1] == '-') {
8721 U_CHAR *p2 = l1 - 1;
8722 /* If a `-' is preceded by an odd number of newlines then it
8723 and the last newline are a no-reexpansion marker. */
8724 while (p2 != p1 && p2[-1] == '\n') p2--;
8725 if ((l1 - 1 - p2) & 1) {
8726 l1 -= 2;
8728 else break;
8730 else break;
8734 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8735 totlen += l1 - p1;
8736 if (!traditional && ap->raw_after == 0) {
8737 /* Ordinary expanded use of the argument.
8738 Put in newline-space markers to prevent token pasting. */
8739 xbuf[totlen++] = '\n';
8740 xbuf[totlen++] = ' ';
8742 } else {
8743 /* Ordinary expanded use of the argument.
8744 Put in newline-space markers to prevent token pasting. */
8745 if (!traditional) {
8746 xbuf[totlen++] = '\n';
8747 xbuf[totlen++] = ' ';
8749 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8750 arg->expand_length);
8751 totlen += arg->expand_length;
8752 if (!traditional) {
8753 xbuf[totlen++] = '\n';
8754 xbuf[totlen++] = ' ';
8756 /* If a macro argument with newlines is used multiple times,
8757 then only expand the newlines once. This avoids creating output
8758 lines which don't correspond to any input line, which confuses
8759 gdb and gcov. */
8760 if (arg->use_count > 1 && arg->newlines > 0) {
8761 /* Don't bother doing change_newlines for subsequent
8762 uses of arg. */
8763 arg->use_count = 1;
8764 change_newlines (arg);
8768 if (totlen > xbuf_len)
8769 abort ();
8772 /* If there is anything left of the definition after handling
8773 the arg list, copy that in too. */
8775 for (i = offset; i < defn->length; i++) {
8776 /* if we've reached the end of the macro */
8777 if (exp[i] == ')')
8778 rest_zero = 0;
8779 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8780 && last_ap->raw_after != 0))
8781 xbuf[totlen++] = exp[i];
8784 xbuf[totlen] = 0;
8785 xbuf_len = totlen;
8787 for (i = 0; i < nargs; i++) {
8788 if (args[i].free1 != 0)
8789 free (args[i].free1);
8790 if (args[i].free2 != 0)
8791 free (args[i].free2);
8794 } else {
8795 xbuf = defn->expansion;
8796 xbuf_len = defn->length;
8799 /* Now put the expansion on the input stack
8800 so our caller will commence reading from it. */
8802 register FILE_BUF *ip2;
8804 ip2 = &instack[++indepth];
8806 ip2->fname = 0;
8807 ip2->nominal_fname = 0;
8808 ip2->nominal_fname_len = 0;
8809 ip2->inc = 0;
8810 /* This may not be exactly correct, but will give much better error
8811 messages for nested macro calls than using a line number of zero. */
8812 ip2->lineno = start_line;
8813 ip2->buf = xbuf;
8814 ip2->length = xbuf_len;
8815 ip2->bufp = xbuf;
8816 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8817 ip2->macro = hp;
8818 ip2->if_stack = if_stack;
8819 ip2->system_header_p = 0;
8821 /* Recursive macro use sometimes works traditionally.
8822 #define foo(x,y) bar (x (y,0), y)
8823 foo (foo, baz) */
8825 if (!traditional)
8826 hp->type = T_DISABLED;
8830 /* Parse a macro argument and store the info on it into *ARGPTR.
8831 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8832 Return nonzero to indicate a syntax error. */
8834 static int
8835 macarg (argptr, rest_args)
8836 register struct argdata *argptr;
8837 int rest_args;
8839 FILE_BUF *ip = &instack[indepth];
8840 int paren = 0;
8841 int lineno0 = ip->lineno;
8842 int comments = 0;
8843 int result = 0;
8845 /* Try to parse as much of the argument as exists at this
8846 input stack level. */
8847 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8848 &paren, &ip->lineno, &comments, rest_args);
8850 /* If we find the end of the argument at this level,
8851 set up *ARGPTR to point at it in the input stack. */
8852 if (!(ip->fname != 0 && (ip->lineno != lineno0 || comments != 0))
8853 && bp != ip->buf + ip->length) {
8854 if (argptr != 0) {
8855 argptr->raw = ip->bufp;
8856 argptr->raw_length = bp - ip->bufp;
8857 argptr->newlines = ip->lineno - lineno0;
8859 ip->bufp = bp;
8860 } else {
8861 /* This input stack level ends before the macro argument does.
8862 We must pop levels and keep parsing.
8863 Therefore, we must allocate a temporary buffer and copy
8864 the macro argument into it. */
8865 int bufsize = bp - ip->bufp;
8866 int extra = ip->lineno - lineno0;
8867 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8868 int final_start = 0;
8870 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8871 ip->bufp = bp;
8873 while (bp == ip->buf + ip->length) {
8874 if (instack[indepth].macro == 0) {
8875 result = 1;
8876 break;
8878 ip->macro->type = T_MACRO;
8879 if (ip->free_ptr)
8880 free (ip->free_ptr);
8881 ip = &instack[--indepth];
8882 lineno0 = ip->lineno;
8883 comments = 0;
8884 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8885 &ip->lineno, &comments, rest_args);
8886 final_start = bufsize;
8887 bufsize += bp - ip->bufp;
8888 extra += ip->lineno - lineno0;
8889 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8890 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8891 bp - ip->bufp);
8892 ip->bufp = bp;
8895 /* Now, if arg is actually wanted, record its raw form,
8896 discarding comments and duplicating newlines in whatever
8897 part of it did not come from a macro expansion.
8898 EXTRA space has been preallocated for duplicating the newlines.
8899 FINAL_START is the index of the start of that part. */
8900 if (argptr != 0) {
8901 argptr->raw = buffer;
8902 argptr->raw_length = bufsize;
8903 argptr->free1 = buffer;
8904 argptr->newlines = ip->lineno - lineno0;
8905 if ((argptr->newlines || comments) && ip->fname != 0)
8906 argptr->raw_length
8907 = final_start +
8908 discard_comments (argptr->raw + final_start,
8909 argptr->raw_length - final_start,
8910 argptr->newlines);
8911 argptr->raw[argptr->raw_length] = 0;
8912 if (argptr->raw_length > bufsize + extra)
8913 abort ();
8917 /* If we are not discarding this argument,
8918 macroexpand it and compute its length as stringified.
8919 All this info goes into *ARGPTR. */
8921 if (argptr != 0) {
8922 register U_CHAR *buf, *lim;
8923 register int totlen;
8925 buf = argptr->raw;
8926 lim = buf + argptr->raw_length;
8928 while (buf != lim && is_space[*buf])
8929 buf++;
8930 while (buf != lim && is_space[lim[-1]])
8931 lim--;
8932 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8933 while (buf != lim) {
8934 register U_CHAR c = *buf++;
8935 totlen++;
8936 /* Internal sequences of whitespace are replaced by one space
8937 in most cases, but not always. So count all the whitespace
8938 in case we need to keep it all. */
8939 #if 0
8940 if (is_space[c])
8941 SKIP_ALL_WHITE_SPACE (buf);
8942 else
8943 #endif
8944 if (c == '\"' || c == '\\' || c == '\n') /* escape these chars */
8945 totlen++;
8947 argptr->stringified_length_bound = totlen;
8949 return result;
8952 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8953 taken from the expansion of MACRO,
8954 counting parens in *DEPTHPTR,
8955 and return if reach LIMIT
8956 or before a `)' that would make *DEPTHPTR negative
8957 or before a comma when *DEPTHPTR is zero.
8958 Single and double quotes are matched and termination
8959 is inhibited within them. Comments also inhibit it.
8960 Value returned is pointer to stopping place.
8962 Increment *NEWLINES each time a newline is passed.
8963 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8964 Set *COMMENTS to 1 if a comment is seen. */
8966 static U_CHAR *
8967 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8968 U_CHAR *start;
8969 register U_CHAR *limit;
8970 struct hashnode *macro;
8971 int *depthptr, *newlines, *comments;
8972 int rest_args;
8974 register U_CHAR *bp = start;
8976 while (bp < limit) {
8977 switch (*bp) {
8978 case '(':
8979 (*depthptr)++;
8980 break;
8981 case ')':
8982 if (--(*depthptr) < 0)
8983 return bp;
8984 break;
8985 case '\\':
8986 /* Traditionally, backslash makes following char not special. */
8987 if (traditional && bp + 1 < limit && bp[1] != '\n')
8988 bp++;
8989 break;
8990 case '\n':
8991 ++*newlines;
8992 break;
8993 case '/':
8994 if (macro)
8995 break;
8996 if (bp[1] == '\\')
8997 newline_fix (bp + 1);
8998 if (bp[1] == '*') {
8999 *comments = 1;
9000 for (bp += 2; bp < limit; bp++) {
9001 if (*bp == '\n')
9002 ++*newlines;
9003 else if (*bp == '*') {
9004 if (bp[-1] == '/' && warn_comments)
9005 warning ("`/*' within comment");
9006 if (bp[1] == '\\')
9007 newline_fix (bp + 1);
9008 if (bp[1] == '/') {
9009 bp++;
9010 break;
9013 else
9015 #ifdef MULTIBYTE_CHARS
9016 int length;
9017 length = local_mblen (bp, limit - bp);
9018 if (length > 1)
9019 bp += (length - 1);
9020 #endif
9023 } else if (bp[1] == '/' && cplusplus_comments) {
9024 *comments = 1;
9025 for (bp += 2; bp < limit; bp++) {
9026 if (*bp == '\n') {
9027 ++*newlines;
9028 break;
9030 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
9032 ++*newlines;
9033 if (warn_comments)
9034 warning ("multiline `//' comment");
9035 ++bp;
9037 else
9039 #ifdef MULTIBYTE_CHARS
9040 int length;
9041 length = local_mblen (bp, limit - bp);
9042 if (length > 1)
9043 bp += (length - 1);
9044 #endif
9048 break;
9049 case '\'':
9050 case '\"':
9052 int quotec;
9053 for (quotec = *bp++; bp < limit && *bp != quotec; bp++) {
9054 if (*bp == '\\') {
9055 bp++;
9056 if (*bp == '\n')
9057 ++*newlines;
9058 while (*bp == '\\' && bp[1] == '\n') {
9059 bp += 2;
9060 ++*newlines;
9062 } else if (*bp == '\n') {
9063 if (warn_white_space && is_hor_space[bp[-1]] && ! macro)
9064 warning ("white space at end of line in string");
9065 ++*newlines;
9066 if (quotec == '\'')
9067 break;
9069 else
9071 #ifdef MULTIBYTE_CHARS
9072 int length;
9073 length = local_mblen (bp, limit - bp);
9074 if (length > 1)
9075 bp += (length - 1);
9076 #endif
9080 break;
9081 case ',':
9082 /* if we've returned to lowest level and we aren't absorbing all args */
9083 if ((*depthptr) == 0 && rest_args == 0)
9084 return bp;
9085 break;
9087 bp++;
9090 return bp;
9093 /* Discard comments and duplicate newlines
9094 in the string of length LENGTH at START,
9095 except inside of string constants.
9096 The string is copied into itself with its beginning staying fixed.
9098 NEWLINES is the number of newlines that must be duplicated.
9099 We assume that that much extra space is available past the end
9100 of the string. */
9102 static int
9103 discard_comments (start, length, newlines)
9104 U_CHAR *start;
9105 int length;
9106 int newlines;
9108 register U_CHAR *ibp;
9109 register U_CHAR *obp;
9110 register U_CHAR *limit;
9111 register int c;
9113 /* If we have newlines to duplicate, copy everything
9114 that many characters up. Then, in the second part,
9115 we will have room to insert the newlines
9116 while copying down.
9117 NEWLINES may actually be too large, because it counts
9118 newlines in string constants, and we don't duplicate those.
9119 But that does no harm. */
9120 if (newlines > 0) {
9121 ibp = start + length;
9122 obp = ibp + newlines;
9123 limit = start;
9124 while (limit != ibp)
9125 *--obp = *--ibp;
9128 ibp = start + newlines;
9129 limit = start + length + newlines;
9130 obp = start;
9132 while (ibp < limit) {
9133 *obp++ = c = *ibp++;
9134 switch (c) {
9135 case '\n':
9136 /* Duplicate the newline. */
9137 *obp++ = '\n';
9138 break;
9140 case '\\':
9141 if (*ibp == '\n') {
9142 obp--;
9143 ibp++;
9145 break;
9147 case '/':
9148 if (*ibp == '\\')
9149 newline_fix (ibp);
9150 /* Delete any comment. */
9151 if (cplusplus_comments && ibp[0] == '/') {
9152 /* Comments are equivalent to spaces. */
9153 obp[-1] = ' ';
9154 ibp++;
9155 while (ibp < limit)
9157 if (*ibp == '\n')
9158 break;
9159 if (*ibp == '\\' && ibp + 1 < limit && ibp[1] == '\n')
9160 ibp++;
9161 else
9163 #ifdef MULTIBYTE_CHARS
9164 int length = local_mblen (ibp, limit - ibp);
9165 if (length > 1)
9166 ibp += (length - 1);
9167 #endif
9169 ibp++;
9171 break;
9173 if (ibp[0] != '*' || ibp + 1 >= limit)
9174 break;
9175 /* Comments are equivalent to spaces.
9176 For -traditional, a comment is equivalent to nothing. */
9177 if (traditional)
9178 obp--;
9179 else
9180 obp[-1] = ' ';
9181 while (++ibp < limit) {
9182 if (ibp[0] == '*') {
9183 if (ibp[1] == '\\')
9184 newline_fix (ibp + 1);
9185 if (ibp[1] == '/') {
9186 ibp += 2;
9187 break;
9190 else
9192 #ifdef MULTIBYTE_CHARS
9193 int length = local_mblen (ibp, limit - ibp);
9194 if (length > 1)
9195 ibp += (length - 1);
9196 #endif
9199 break;
9201 case '\'':
9202 case '\"':
9203 /* Notice and skip strings, so that we don't
9204 think that comments start inside them,
9205 and so we don't duplicate newlines in them. */
9207 int quotec = c;
9208 while (ibp < limit) {
9209 *obp++ = c = *ibp++;
9210 if (c == quotec)
9211 break;
9212 if (c == '\n')
9214 if (quotec == '\'')
9215 break;
9217 else if (c == '\\') {
9218 if (ibp < limit && *ibp == '\n') {
9219 ibp++;
9220 obp--;
9221 } else {
9222 while (*ibp == '\\' && ibp[1] == '\n')
9223 ibp += 2;
9224 if (ibp < limit)
9225 *obp++ = *ibp++;
9228 else
9230 #ifdef MULTIBYTE_CHARS
9231 int length;
9232 ibp--;
9233 length = local_mblen (ibp, limit - ibp);
9234 if (length > 1)
9236 obp--;
9237 bcopy (ibp, obp, length);
9238 ibp += length;
9239 obp += length;
9241 else
9242 ibp++;
9243 #endif
9247 break;
9251 return obp - start;
9254 /* Turn newlines to spaces in the macro argument ARG.
9255 Remove backslash-newline from string constants,
9256 and turn other newlines in string constants to backslash-'n'. */
9258 static void
9259 change_newlines (arg)
9260 struct argdata *arg;
9262 U_CHAR *start = arg->expanded;
9263 int length = arg->expand_length;
9264 register U_CHAR *ibp;
9265 register U_CHAR *obp;
9266 register U_CHAR *limit;
9267 register int c;
9269 ibp = start;
9270 limit = start + length;
9271 obp = start;
9273 while (ibp < limit) {
9274 *obp++ = c = *ibp++;
9275 switch (c) {
9276 case '\n':
9277 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
9278 string. Skip past the newline and its duplicate.
9279 Put a space in the output. */
9280 if (*ibp == '\n')
9282 ibp++;
9283 obp--;
9284 *obp++ = ' ';
9286 break;
9288 case '\'':
9289 case '\"':
9290 /* Notice and skip strings, so that we don't delete newlines in them. */
9292 int quotec = c;
9293 while (ibp < limit) {
9294 *obp++ = c = *ibp++;
9295 if (c == quotec)
9296 break;
9297 else if (c == '\\' && ibp < limit && *ibp == '\n')
9298 *obp++ = *ibp++;
9299 else if (c == '\n')
9301 if (quotec == '\'')
9302 break;
9304 else
9306 #ifdef MULTIBYTE_CHARS
9307 int length;
9308 ibp--;
9309 length = local_mblen (ibp, limit - ibp);
9310 if (length > 1)
9312 obp--;
9313 bcopy (ibp, obp, length);
9314 ibp += length;
9315 obp += length;
9317 else
9318 ibp++;
9319 #endif
9323 break;
9327 arg->expand_length = obp - arg->expanded;
9329 if (start != arg->expanded)
9330 free (start);
9333 /* notice - output message to stderr */
9335 static void
9336 notice VPROTO ((const char * msgid, ...))
9338 #ifndef ANSI_PROTOTYPES
9339 const char * msgid;
9340 #endif
9341 va_list args;
9343 VA_START (args, msgid);
9345 #ifndef ANSI_PROTOTYPES
9346 msgid = va_arg (args, const char *);
9347 #endif
9349 vnotice (msgid, args);
9350 va_end (args);
9353 static void
9354 vnotice (msgid, args)
9355 const char *msgid;
9356 va_list args;
9358 vfprintf (stderr, _(msgid), args);
9361 /* error - print error message and increment count of errors. */
9363 void
9364 error VPROTO ((const char * msgid, ...))
9366 #ifndef ANSI_PROTOTYPES
9367 const char * msgid;
9368 #endif
9369 va_list args;
9371 VA_START (args, msgid);
9373 #ifndef ANSI_PROTOTYPES
9374 msgid = va_arg (args, const char *);
9375 #endif
9377 verror (msgid, args);
9378 va_end (args);
9381 void
9382 verror (msgid, args)
9383 const char *msgid;
9384 va_list args;
9386 int i;
9387 FILE_BUF *ip = NULL;
9389 print_containing_files ();
9391 for (i = indepth; i >= 0; i--)
9392 if (instack[i].fname != NULL) {
9393 ip = &instack[i];
9394 break;
9397 if (ip != NULL) {
9398 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9399 ip->nominal_fname_len, stderr);
9400 fprintf (stderr, ":%d: ", ip->lineno);
9402 vnotice (msgid, args);
9403 fprintf (stderr, "\n");
9404 errors++;
9407 /* Error including a message from `errno'. */
9409 static void
9410 error_from_errno (name)
9411 char *name;
9413 int e = errno;
9414 int i;
9415 FILE_BUF *ip = NULL;
9417 print_containing_files ();
9419 for (i = indepth; i >= 0; i--)
9420 if (instack[i].fname != NULL) {
9421 ip = &instack[i];
9422 break;
9425 if (ip != NULL) {
9426 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9427 ip->nominal_fname_len, stderr);
9428 fprintf (stderr, ":%d: ", ip->lineno);
9431 fprintf (stderr, "%s: %s\n", name, xstrerror (e));
9433 errors++;
9436 /* Print error message but don't count it. */
9438 void
9439 warning VPROTO ((const char * msgid, ...))
9441 #ifndef ANSI_PROTOTYPES
9442 const char * msgid;
9443 #endif
9444 va_list args;
9446 VA_START (args, msgid);
9448 #ifndef ANSI_PROTOTYPES
9449 msgid = va_arg (args, const char *);
9450 #endif
9452 vwarning (msgid, args);
9453 va_end (args);
9456 static void
9457 vwarning (msgid, args)
9458 const char *msgid;
9459 va_list args;
9461 int i;
9462 FILE_BUF *ip = NULL;
9464 if (inhibit_warnings)
9465 return;
9467 if (warnings_are_errors)
9468 errors++;
9470 print_containing_files ();
9472 for (i = indepth; i >= 0; i--)
9473 if (instack[i].fname != NULL) {
9474 ip = &instack[i];
9475 break;
9478 if (ip != NULL) {
9479 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9480 ip->nominal_fname_len, stderr);
9481 fprintf (stderr, ":%d: ", ip->lineno);
9483 notice ("warning: ");
9484 vnotice (msgid, args);
9485 fprintf (stderr, "\n");
9488 static void
9489 error_with_line VPROTO ((int line, const char * msgid, ...))
9491 #ifndef ANSI_PROTOTYPES
9492 int line;
9493 const char * msgid;
9494 #endif
9495 va_list args;
9497 VA_START (args, msgid);
9499 #ifndef ANSI_PROTOTYPES
9500 line = va_arg (args, int);
9501 msgid = va_arg (args, const char *);
9502 #endif
9504 verror_with_line (line, msgid, args);
9505 va_end (args);
9509 static void
9510 verror_with_line (line, msgid, args)
9511 int line;
9512 const char *msgid;
9513 va_list args;
9515 int i;
9516 FILE_BUF *ip = NULL;
9518 print_containing_files ();
9520 for (i = indepth; i >= 0; i--)
9521 if (instack[i].fname != NULL) {
9522 ip = &instack[i];
9523 break;
9526 if (ip != NULL) {
9527 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9528 ip->nominal_fname_len, stderr);
9529 fprintf (stderr, ":%d: ", line);
9531 vnotice (msgid, args);
9532 fprintf (stderr, "\n");
9533 errors++;
9536 static void
9537 warning_with_line VPROTO ((int line, const char * msgid, ...))
9539 #ifndef ANSI_PROTOTYPES
9540 int line;
9541 const char * msgid;
9542 #endif
9543 va_list args;
9545 VA_START (args, msgid);
9547 #ifndef ANSI_PROTOTYPES
9548 line = va_arg (args, int);
9549 msgid = va_arg (args, const char *);
9550 #endif
9552 vwarning_with_line (line, msgid, args);
9553 va_end (args);
9556 static void
9557 vwarning_with_line (line, msgid, args)
9558 int line;
9559 const char *msgid;
9560 va_list args;
9562 int i;
9563 FILE_BUF *ip = NULL;
9565 if (inhibit_warnings)
9566 return;
9568 if (warnings_are_errors)
9569 errors++;
9571 print_containing_files ();
9573 for (i = indepth; i >= 0; i--)
9574 if (instack[i].fname != NULL) {
9575 ip = &instack[i];
9576 break;
9579 if (ip != NULL) {
9580 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9581 ip->nominal_fname_len, stderr);
9582 fprintf (stderr, line ? ":%d: " : ": ", line);
9584 notice ("warning: ");
9585 vnotice (msgid, args);
9586 fprintf (stderr, "\n");
9589 /* Print an error message and maybe count it. */
9591 void
9592 pedwarn VPROTO ((const char * msgid, ...))
9594 #ifndef ANSI_PROTOTYPES
9595 const char * msgid;
9596 #endif
9597 va_list args;
9599 VA_START (args, msgid);
9601 #ifndef ANSI_PROTOTYPES
9602 msgid = va_arg (args, const char *);
9603 #endif
9605 if (pedantic_errors)
9606 verror (msgid, args);
9607 else
9608 vwarning (msgid, args);
9609 va_end (args);
9612 void
9613 pedwarn_with_line VPROTO ((int line, const char * msgid, ...))
9615 #ifndef ANSI_PROTOTYPES
9616 int line;
9617 const char * msgid;
9618 #endif
9619 va_list args;
9621 VA_START (args, msgid);
9623 #ifndef ANSI_PROTOTYPES
9624 line = va_arg (args, int);
9625 msgid = va_arg (args, const char *);
9626 #endif
9628 if (pedantic_errors)
9629 verror_with_line (line, msgid, args);
9630 else
9631 vwarning_with_line (line, msgid, args);
9632 va_end (args);
9635 /* Report a warning (or an error if pedantic_errors)
9636 giving specified file name and line number, not current. */
9638 static void
9639 pedwarn_with_file_and_line VPROTO ((const char *file, size_t file_len, int line,
9640 const char * msgid, ...))
9642 #ifndef ANSI_PROTOTYPES
9643 const char *file;
9644 size_t file_len;
9645 int line;
9646 const char * msgid;
9647 #endif
9648 va_list args;
9650 if (!pedantic_errors && inhibit_warnings)
9651 return;
9653 VA_START (args, msgid);
9655 #ifndef ANSI_PROTOTYPES
9656 file = va_arg (args, const char *);
9657 file_len = va_arg (args, size_t);
9658 line = va_arg (args, int);
9659 msgid = va_arg (args, const char *);
9660 #endif
9662 if (file) {
9663 fwrite (file, sizeof file[0], file_len, stderr);
9664 fprintf (stderr, ":%d: ", line);
9666 if (pedantic_errors)
9667 errors++;
9668 if (!pedantic_errors)
9669 notice ("warning: ");
9670 vnotice (msgid, args);
9671 va_end (args);
9672 fprintf (stderr, "\n");
9675 static void
9676 pedwarn_strange_white_space (ch)
9677 int ch;
9679 switch (ch)
9681 case '\f': pedwarn ("formfeed in preprocessing directive"); break;
9682 case '\r': pedwarn ("carriage return in preprocessing directive"); break;
9683 case '\v': pedwarn ("vertical tab in preprocessing directive"); break;
9684 default: abort ();
9688 /* Print the file names and line numbers of the #include
9689 directives which led to the current file. */
9691 static void
9692 print_containing_files ()
9694 FILE_BUF *ip = NULL;
9695 int i;
9696 int first = 1;
9698 /* If stack of files hasn't changed since we last printed
9699 this info, don't repeat it. */
9700 if (last_error_tick == input_file_stack_tick)
9701 return;
9703 for (i = indepth; i >= 0; i--)
9704 if (instack[i].fname != NULL) {
9705 ip = &instack[i];
9706 break;
9709 /* Give up if we don't find a source file. */
9710 if (ip == NULL)
9711 return;
9713 /* Find the other, outer source files. */
9714 for (i--; i >= 0; i--)
9715 if (instack[i].fname != NULL) {
9716 ip = &instack[i];
9717 if (first) {
9718 first = 0;
9719 notice ( "In file included from ");
9720 } else {
9721 notice (",\n from ");
9724 fwrite (ip->nominal_fname, sizeof ip->nominal_fname[0],
9725 ip->nominal_fname_len, stderr);
9726 fprintf (stderr, ":%d", ip->lineno);
9728 if (! first)
9729 fprintf (stderr, ":\n");
9731 /* Record we have printed the status as of this time. */
9732 last_error_tick = input_file_stack_tick;
9735 /* Return the line at which an error occurred.
9736 The error is not necessarily associated with the current spot
9737 in the input stack, so LINE says where. LINE will have been
9738 copied from ip->lineno for the current input level.
9739 If the current level is for a file, we return LINE.
9740 But if the current level is not for a file, LINE is meaningless.
9741 In that case, we return the lineno of the innermost file. */
9743 static int
9744 line_for_error (line)
9745 int line;
9747 int i;
9748 int line1 = line;
9750 for (i = indepth; i >= 0; ) {
9751 if (instack[i].fname != 0)
9752 return line1;
9753 i--;
9754 if (i < 0)
9755 return 0;
9756 line1 = instack[i].lineno;
9758 abort ();
9759 /*NOTREACHED*/
9760 return 0;
9764 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9766 * As things stand, nothing is ever placed in the output buffer to be
9767 * removed again except when it's KNOWN to be part of an identifier,
9768 * so flushing and moving down everything left, instead of expanding,
9769 * should work ok.
9772 /* You might think void was cleaner for the return type,
9773 but that would get type mismatch in check_expand in strict ANSI. */
9775 static int
9776 grow_outbuf (obuf, needed)
9777 register FILE_BUF *obuf;
9778 register int needed;
9780 register U_CHAR *p;
9781 int minsize;
9783 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9784 return 0;
9786 /* Make it at least twice as big as it is now. */
9787 obuf->length *= 2;
9788 /* Make it have at least 150% of the free space we will need. */
9789 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9790 if (minsize > obuf->length)
9791 obuf->length = minsize;
9793 p = (U_CHAR *) xrealloc (obuf->buf, obuf->length);
9795 obuf->bufp = p + (obuf->bufp - obuf->buf);
9796 obuf->buf = p;
9798 return 0;
9801 /* Symbol table for macro names and special symbols */
9804 * install a name in the main hash table, even if it is already there.
9805 * name stops with first non alphanumeric, except leading '#'.
9806 * caller must check against redefinition if that is desired.
9807 * delete_macro () removes things installed by install () in fifo order.
9808 * this is important because of the `defined' special symbol used
9809 * in #if, and also if pushdef/popdef directives are ever implemented.
9811 * If LEN is >= 0, it is the length of the name.
9812 * Otherwise, compute the length by scanning the entire name.
9814 * If HASH is >= 0, it is the precomputed hash code.
9815 * Otherwise, compute the hash code.
9818 static HASHNODE *
9819 install (name, len, type, value, hash)
9820 U_CHAR *name;
9821 int len;
9822 enum node_type type;
9823 char *value;
9824 int hash;
9826 register HASHNODE *hp;
9827 register int i, bucket;
9828 register U_CHAR *p, *q;
9830 if (len < 0) {
9831 p = name;
9832 while (is_idchar[*p])
9833 p++;
9834 len = p - name;
9837 if (hash < 0)
9838 hash = hashf (name, len, HASHSIZE);
9840 i = sizeof (HASHNODE) + len + 1;
9841 hp = (HASHNODE *) xmalloc (i);
9842 bucket = hash;
9843 hp->bucket_hdr = &hashtab[bucket];
9844 hp->next = hashtab[bucket];
9845 hashtab[bucket] = hp;
9846 hp->prev = NULL;
9847 if (hp->next != NULL)
9848 hp->next->prev = hp;
9849 hp->type = type;
9850 hp->length = len;
9851 hp->value.cpval = value;
9852 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9853 p = hp->name;
9854 q = name;
9855 for (i = 0; i < len; i++)
9856 *p++ = *q++;
9857 hp->name[len] = 0;
9858 return hp;
9862 * find the most recent hash node for name "name" (ending with first
9863 * non-identifier char) installed by install
9865 * If LEN is >= 0, it is the length of the name.
9866 * Otherwise, compute the length by scanning the entire name.
9868 * If HASH is >= 0, it is the precomputed hash code.
9869 * Otherwise, compute the hash code.
9872 HASHNODE *
9873 lookup (name, len, hash)
9874 U_CHAR *name;
9875 int len;
9876 int hash;
9878 register U_CHAR *bp;
9879 register HASHNODE *bucket;
9881 if (len < 0) {
9882 for (bp = name; is_idchar[*bp]; bp++) ;
9883 len = bp - name;
9886 if (hash < 0)
9887 hash = hashf (name, len, HASHSIZE);
9889 bucket = hashtab[hash];
9890 while (bucket) {
9891 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9892 return bucket;
9893 bucket = bucket->next;
9895 return NULL;
9899 * Delete a hash node. Some weirdness to free junk from macros.
9900 * More such weirdness will have to be added if you define more hash
9901 * types that need it.
9904 /* Note that the DEFINITION of a macro is removed from the hash table
9905 but its storage is not freed. This would be a storage leak
9906 except that it is not reasonable to keep undefining and redefining
9907 large numbers of macros many times.
9908 In any case, this is necessary, because a macro can be #undef'd
9909 in the middle of reading the arguments to a call to it.
9910 If #undef freed the DEFINITION, that would crash. */
9912 static void
9913 delete_macro (hp)
9914 HASHNODE *hp;
9917 if (hp->prev != NULL)
9918 hp->prev->next = hp->next;
9919 if (hp->next != NULL)
9920 hp->next->prev = hp->prev;
9922 /* Make sure that the bucket chain header that the deleted guy was
9923 on points to the right thing afterwards. */
9924 if (hp == *hp->bucket_hdr)
9925 *hp->bucket_hdr = hp->next;
9927 #if 0
9928 if (hp->type == T_MACRO) {
9929 DEFINITION *d = hp->value.defn;
9930 struct reflist *ap, *nextap;
9932 for (ap = d->pattern; ap != NULL; ap = nextap) {
9933 nextap = ap->next;
9934 free (ap);
9936 free (d);
9938 #endif
9939 free (hp);
9943 * return hash function on name. must be compatible with the one
9944 * computed a step at a time, elsewhere
9947 static int
9948 hashf (name, len, hashsize)
9949 register U_CHAR *name;
9950 register int len;
9951 int hashsize;
9953 register int r = 0;
9955 while (len--)
9956 r = HASHSTEP (r, *name++);
9958 return MAKE_POS (r) % hashsize;
9962 /* Dump the definition of a single macro HP to OF. */
9964 static void
9965 dump_single_macro (hp, of)
9966 register HASHNODE *hp;
9967 FILE *of;
9969 register DEFINITION *defn = hp->value.defn;
9970 struct reflist *ap;
9971 int offset;
9972 int concat;
9975 /* Print the definition of the macro HP. */
9977 fprintf (of, "#define %s", hp->name);
9979 if (defn->nargs >= 0) {
9980 int i;
9982 fprintf (of, "(");
9983 for (i = 0; i < defn->nargs; i++) {
9984 dump_arg_n (defn, i, of);
9985 if (i + 1 < defn->nargs)
9986 fprintf (of, ", ");
9988 fprintf (of, ")");
9991 fprintf (of, " ");
9993 offset = 0;
9994 concat = 0;
9995 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9996 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9997 offset += ap->nchars;
9998 if (!traditional) {
9999 if (ap->nchars != 0)
10000 concat = 0;
10001 if (ap->stringify) {
10002 switch (ap->stringify) {
10003 case SHARP_TOKEN: fprintf (of, "#"); break;
10004 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
10005 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
10006 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
10007 default: abort ();
10010 if (ap->raw_before != 0) {
10011 if (concat) {
10012 switch (ap->raw_before) {
10013 case WHITE_SHARP_TOKEN:
10014 case WHITE_PERCENT_COLON_TOKEN:
10015 fprintf (of, " ");
10016 break;
10017 default:
10018 break;
10020 } else {
10021 switch (ap->raw_before) {
10022 case SHARP_TOKEN: fprintf (of, "##"); break;
10023 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
10024 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
10025 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
10026 default: abort ();
10030 concat = 0;
10032 dump_arg_n (defn, ap->argno, of);
10033 if (!traditional && ap->raw_after != 0) {
10034 switch (ap->raw_after) {
10035 case SHARP_TOKEN: fprintf (of, "##"); break;
10036 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
10037 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
10038 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
10039 default: abort ();
10041 concat = 1;
10044 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
10045 fprintf (of, "\n");
10048 /* Dump all macro definitions as #defines to stdout. */
10050 static void
10051 dump_all_macros ()
10053 int bucket;
10055 for (bucket = 0; bucket < HASHSIZE; bucket++) {
10056 register HASHNODE *hp;
10058 for (hp = hashtab[bucket]; hp; hp= hp->next) {
10059 if (hp->type == T_MACRO)
10060 dump_single_macro (hp, stdout);
10065 /* Output to OF a substring of a macro definition.
10066 BASE is the beginning of the definition.
10067 Output characters START thru LENGTH.
10068 Unless traditional, discard newlines outside of strings, thus
10069 converting funny-space markers to ordinary spaces. */
10071 static void
10072 dump_defn_1 (base, start, length, of)
10073 U_CHAR *base;
10074 int start;
10075 int length;
10076 FILE *of;
10078 U_CHAR *p = base + start;
10079 U_CHAR *limit = base + start + length;
10081 if (traditional)
10082 fwrite (p, sizeof (*p), length, of);
10083 else {
10084 while (p < limit) {
10085 if (*p == '\"' || *p =='\'') {
10086 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
10087 NULL_PTR, NULL_PTR);
10088 fwrite (p, sizeof (*p), p1 - p, of);
10089 p = p1;
10090 } else {
10091 if (*p != '\n')
10092 putc (*p, of);
10093 p++;
10099 /* Print the name of argument number ARGNUM of macro definition DEFN
10100 to OF.
10101 Recall that DEFN->args.argnames contains all the arg names
10102 concatenated in reverse order with comma-space in between. */
10104 static void
10105 dump_arg_n (defn, argnum, of)
10106 DEFINITION *defn;
10107 int argnum;
10108 FILE *of;
10110 register U_CHAR *p = defn->args.argnames;
10111 while (argnum + 1 < defn->nargs) {
10112 p = (U_CHAR *) index ((char *) p, ' ') + 1;
10113 argnum++;
10116 while (*p && *p != ',') {
10117 putc (*p, of);
10118 p++;
10122 /* Initialize syntactic classifications of characters. */
10124 static void
10125 initialize_char_syntax ()
10127 register int i;
10130 * Set up is_idchar and is_idstart tables. These should be
10131 * faster than saying (is_alpha (c) || c == '_'), etc.
10132 * Set up these things before calling any routines tthat
10133 * refer to them.
10135 for (i = 'a'; i <= 'z'; i++) {
10136 is_idchar[TOUPPER(i)] = 1;
10137 is_idchar[i] = 1;
10138 is_idstart[TOUPPER(i)] = 1;
10139 is_idstart[i] = 1;
10141 for (i = '0'; i <= '9'; i++)
10142 is_idchar[i] = 1;
10143 is_idchar['_'] = 1;
10144 is_idstart['_'] = 1;
10145 is_idchar['$'] = 1;
10146 is_idstart['$'] = 1;
10148 /* horizontal space table */
10149 is_hor_space[' '] = 1;
10150 is_hor_space['\t'] = 1;
10151 is_hor_space['\v'] = 1;
10152 is_hor_space['\f'] = 1;
10153 is_hor_space['\r'] = 1;
10155 is_space[' '] = 1;
10156 is_space['\t'] = 1;
10157 is_space['\v'] = 1;
10158 is_space['\f'] = 1;
10159 is_space['\n'] = 1;
10160 is_space['\r'] = 1;
10163 /* Initialize the built-in macros. */
10165 static void
10166 initialize_builtins (inp, outp)
10167 FILE_BUF *inp;
10168 FILE_BUF *outp;
10170 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
10171 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
10172 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
10173 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
10174 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
10175 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
10176 #ifndef NO_BUILTIN_SIZE_TYPE
10177 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
10178 #endif
10179 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10180 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
10181 #endif
10182 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
10183 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
10184 NULL_PTR, -1);
10185 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
10186 NULL_PTR, -1);
10187 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
10188 NULL_PTR, -1);
10189 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
10190 if (!traditional) {
10191 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
10192 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
10194 /* This is supplied using a -D by the compiler driver
10195 so that it is present only when truly compiling with GNU C. */
10196 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
10197 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
10199 if (debug_output)
10201 char directive[2048];
10202 U_CHAR *udirective = (U_CHAR *) directive;
10203 register struct directive *dp = &directive_table[0];
10204 struct tm *timebuf = timestamp ();
10206 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
10207 instack[0].nominal_fname);
10208 output_line_directive (inp, outp, 0, same_file);
10209 pass_thru_directive (udirective, &udirective[strlen (directive)],
10210 outp, dp);
10212 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
10213 output_line_directive (inp, outp, 0, same_file);
10214 pass_thru_directive (udirective, &udirective[strlen (directive)],
10215 outp, dp);
10217 #ifndef NO_BUILTIN_SIZE_TYPE
10218 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
10219 output_line_directive (inp, outp, 0, same_file);
10220 pass_thru_directive (udirective, &udirective[strlen (directive)],
10221 outp, dp);
10222 #endif
10224 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10225 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
10226 output_line_directive (inp, outp, 0, same_file);
10227 pass_thru_directive (udirective, &udirective[strlen (directive)],
10228 outp, dp);
10229 #endif
10231 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
10232 output_line_directive (inp, outp, 0, same_file);
10233 pass_thru_directive (udirective, &udirective[strlen (directive)],
10234 outp, dp);
10236 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
10237 monthnames[timebuf->tm_mon],
10238 timebuf->tm_mday, timebuf->tm_year + 1900);
10239 output_line_directive (inp, outp, 0, same_file);
10240 pass_thru_directive (udirective, &udirective[strlen (directive)],
10241 outp, dp);
10243 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
10244 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
10245 output_line_directive (inp, outp, 0, same_file);
10246 pass_thru_directive (udirective, &udirective[strlen (directive)],
10247 outp, dp);
10249 if (!traditional)
10251 sprintf (directive, " __STDC__ 1");
10252 output_line_directive (inp, outp, 0, same_file);
10253 pass_thru_directive (udirective, &udirective[strlen (directive)],
10254 outp, dp);
10256 if (objc)
10258 sprintf (directive, " __OBJC__ 1");
10259 output_line_directive (inp, outp, 0, same_file);
10260 pass_thru_directive (udirective, &udirective[strlen (directive)],
10261 outp, dp);
10267 * process a given definition string, for initialization
10268 * If STR is just an identifier, define it with value 1.
10269 * If STR has anything after the identifier, then it should
10270 * be identifier=definition.
10273 static void
10274 make_definition (str)
10275 char *str;
10277 FILE_BUF *ip;
10278 struct directive *kt;
10279 U_CHAR *buf, *p;
10281 p = buf = (U_CHAR *) str;
10282 if (!is_idstart[*p]) {
10283 error ("malformed option `-D %s'", str);
10284 return;
10286 while (is_idchar[*++p])
10288 if (*p == '(') {
10289 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
10291 if (*p++ != ')')
10292 p = (U_CHAR *) str; /* Error */
10294 if (*p == 0) {
10295 buf = (U_CHAR *) alloca (p - buf + 4);
10296 strcpy ((char *)buf, str);
10297 strcat ((char *)buf, " 1");
10298 } else if (*p != '=') {
10299 error ("malformed option `-D %s'", str);
10300 return;
10301 } else {
10302 U_CHAR *q;
10303 /* Copy the entire option so we can modify it. */
10304 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
10305 strncpy ((char *) buf, str, p - (U_CHAR *) str);
10306 /* Change the = to a space. */
10307 buf[p - (U_CHAR *) str] = ' ';
10308 /* Scan for any backslash-newline and remove it. */
10309 p++;
10310 q = &buf[p - (U_CHAR *) str];
10311 while (*p) {
10312 if (*p == '\"' || *p == '\'') {
10313 int unterminated = 0;
10314 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
10315 NULL_PTR, NULL_PTR, &unterminated);
10316 if (unterminated)
10317 return;
10318 while (p != p1) {
10319 if (*p == '\\' && p[1] == '\n')
10320 p += 2;
10321 else if (*p == '\n')
10323 *q++ = '\\';
10324 *q++ = 'n';
10325 p++;
10327 else
10328 *q++ = *p++;
10330 } else if (*p == '\\' && p[1] == '\n')
10331 p += 2;
10332 /* Change newline chars into newline-markers. */
10333 else if (*p == '\n')
10335 *q++ = '\n';
10336 *q++ = '\n';
10337 p++;
10339 else
10340 *q++ = *p++;
10342 *q = 0;
10345 ip = &instack[++indepth];
10346 ip->nominal_fname = ip->fname = "*Initialization*";
10347 ip->nominal_fname_len = strlen (ip->nominal_fname);
10349 ip->buf = ip->bufp = buf;
10350 ip->length = strlen ((char *) buf);
10351 ip->lineno = 1;
10352 ip->macro = 0;
10353 ip->free_ptr = 0;
10354 ip->if_stack = if_stack;
10355 ip->system_header_p = 0;
10357 for (kt = directive_table; kt->type != T_DEFINE; kt++)
10360 /* Pass NULL instead of OP, since this is a "predefined" macro. */
10361 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
10362 --indepth;
10365 /* JF, this does the work for the -U option */
10367 static void
10368 make_undef (str, op)
10369 char *str;
10370 FILE_BUF *op;
10372 FILE_BUF *ip;
10373 struct directive *kt;
10375 ip = &instack[++indepth];
10376 ip->nominal_fname = ip->fname = "*undef*";
10377 ip->nominal_fname_len = strlen (ip->nominal_fname);
10379 ip->buf = ip->bufp = (U_CHAR *) str;
10380 ip->length = strlen (str);
10381 ip->lineno = 1;
10382 ip->macro = 0;
10383 ip->free_ptr = 0;
10384 ip->if_stack = if_stack;
10385 ip->system_header_p = 0;
10387 for (kt = directive_table; kt->type != T_UNDEF; kt++)
10390 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
10391 --indepth;
10394 /* Process the string STR as if it appeared as the body of a #assert.
10395 OPTION is the option name for which STR was the argument. */
10397 static void
10398 make_assertion (option, str)
10399 const char *option;
10400 const char *str;
10402 FILE_BUF *ip;
10403 struct directive *kt;
10404 U_CHAR *buf, *p, *q;
10406 /* Copy the entire option so we can modify it. */
10407 buf = (U_CHAR *) alloca (strlen (str) + 1);
10408 strcpy ((char *) buf, str);
10409 /* Scan for any backslash-newline and remove it. */
10410 p = q = buf;
10411 while (*p) {
10412 if (*p == '\\' && p[1] == '\n')
10413 p += 2;
10414 else
10415 *q++ = *p++;
10417 *q = 0;
10419 p = buf;
10420 if (!is_idstart[*p]) {
10421 error ("malformed option `%s %s'", option, str);
10422 return;
10424 while (is_idchar[*++p])
10426 SKIP_WHITE_SPACE (p);
10427 if (! (*p == 0 || *p == '(')) {
10428 error ("malformed option `%s %s'", option, str);
10429 return;
10432 ip = &instack[++indepth];
10433 ip->nominal_fname = ip->fname = "*Initialization*";
10434 ip->nominal_fname_len = strlen (ip->nominal_fname);
10436 ip->buf = ip->bufp = buf;
10437 ip->length = strlen ((char *) buf);
10438 ip->lineno = 1;
10439 ip->macro = 0;
10440 ip->free_ptr = 0;
10441 ip->if_stack = if_stack;
10442 ip->system_header_p = 0;
10444 for (kt = directive_table; kt->type != T_ASSERT; kt++)
10447 /* Pass NULL as output ptr to do_define since we KNOW it never does
10448 any output.... */
10449 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
10450 --indepth;
10453 /* The previous include prefix, if any, is PREV_FILE_NAME.
10454 Translate any pathnames with COMPONENT.
10455 Allocate a new include prefix whose name is the
10456 simplified concatenation of PREFIX and NAME,
10457 with a trailing / added if needed.
10458 But return 0 if the include prefix should be ignored,
10459 e.g. because it is a duplicate of PREV_FILE_NAME. */
10461 static struct file_name_list *
10462 new_include_prefix (prev_file_name, component, prefix, name)
10463 struct file_name_list *prev_file_name;
10464 const char *component;
10465 const char *prefix;
10466 const char *name;
10468 if (name == 0)
10469 fatal ("Directory name missing after command line option");
10471 if (*name == 0)
10472 /* Ignore the empty string. */
10473 return 0;
10475 prefix = update_path (prefix, component);
10476 name = update_path (name, component);
10479 struct file_name_list *dir
10480 = ((struct file_name_list *)
10481 xmalloc (sizeof (struct file_name_list)
10482 + strlen (prefix) + strlen (name) + 2));
10483 size_t len;
10484 strcpy (dir->fname, prefix);
10485 strcat (dir->fname, name);
10486 len = simplify_filename (dir->fname);
10488 /* Convert directory name to a prefix. */
10489 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10490 if (len == 1 && dir->fname[len - 1] == '.')
10491 len = 0;
10492 else
10493 #ifdef VMS
10494 /* must be '/', hack_vms_include_specification triggers on it. */
10495 dir->fname[len++] = '/';
10496 #else
10497 dir->fname[len++] = DIR_SEPARATOR;
10498 #endif
10499 dir->fname[len] = 0;
10502 /* Ignore a directory whose name matches the previous one. */
10503 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10504 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10505 if (!first_bracket_include)
10506 first_bracket_include = prev_file_name;
10507 free (dir);
10508 return 0;
10511 #ifndef VMS
10512 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10514 /* Add a trailing "." if there is a filename. This increases the number
10515 of systems that can stat directories. We remove it below. */
10516 if (len != 0)
10518 dir->fname[len] = '.';
10519 dir->fname[len + 1] = 0;
10522 /* Ignore a nonexistent directory. */
10523 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10524 if (errno != ENOENT && errno != ENOTDIR)
10525 error_from_errno (dir->fname);
10526 free (dir);
10527 return 0;
10530 if (len != 0)
10531 dir->fname[len] = 0;
10533 /* Ignore a directory whose identity matches the previous one. */
10534 if (prev_file_name
10535 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10536 && prev_file_name->st.st_dev == dir->st.st_dev) {
10537 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10538 if (!first_bracket_include)
10539 first_bracket_include = prev_file_name;
10540 free (dir);
10541 return 0;
10543 #endif /* ! VMS */
10545 dir->next = 0;
10546 dir->c_system_include_path = 0;
10547 dir->got_name_map = 0;
10549 return dir;
10553 /* Append a chain of `struct file_name_list's
10554 to the end of the main include chain.
10555 FIRST is the beginning of the chain to append, and LAST is the end. */
10557 static void
10558 append_include_chain (first, last)
10559 struct file_name_list *first, *last;
10561 struct file_name_list *dir;
10563 if (!first || !last)
10564 return;
10566 if (include == 0)
10567 include = first;
10568 else
10569 last_include->next = first;
10571 if (first_bracket_include == 0)
10572 first_bracket_include = first;
10574 for (dir = first; ; dir = dir->next) {
10575 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10576 if (len > max_include_len)
10577 max_include_len = len;
10578 if (dir == last)
10579 break;
10582 last->next = NULL;
10583 last_include = last;
10586 /* Place into DST a representation of the file named SRC that is suitable
10587 for `make'. Do not null-terminate DST. Return its length. */
10588 static int
10589 quote_string_for_make (dst, src)
10590 char *dst;
10591 const char *src;
10593 const char *p = src;
10594 int i = 0;
10595 for (;;)
10597 char c = *p++;
10598 switch (c)
10600 case '\0':
10601 case ' ':
10602 case '\t':
10604 /* GNU make uses a weird quoting scheme for white space.
10605 A space or tab preceded by 2N+1 backslashes represents
10606 N backslashes followed by space; a space or tab
10607 preceded by 2N backslashes represents N backslashes at
10608 the end of a file name; and backslashes in other
10609 contexts should not be doubled. */
10610 const char *q;
10611 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10613 if (dst)
10614 dst[i] = '\\';
10615 i++;
10618 if (!c)
10619 return i;
10620 if (dst)
10621 dst[i] = '\\';
10622 i++;
10623 goto ordinary_char;
10625 case '$':
10626 if (dst)
10627 dst[i] = c;
10628 i++;
10629 /* Fall through. This can mishandle things like "$(" but
10630 there's no easy fix. */
10631 default:
10632 ordinary_char:
10633 /* This can mishandle characters in the string "\0\n%*?[\\~";
10634 exactly which chars are mishandled depends on the `make' version.
10635 We know of no portable solution for this;
10636 even GNU make 3.76.1 doesn't solve the problem entirely.
10637 (Also, '\0' is mishandled due to our calling conventions.) */
10638 if (dst)
10639 dst[i] = c;
10640 i++;
10641 break;
10647 /* Add output to `deps_buffer' for the -M switch.
10648 STRING points to the text to be output.
10649 SPACER is ':' for targets, ' ' for dependencies. */
10651 static void
10652 deps_output (string, spacer)
10653 const char *string;
10654 int spacer;
10656 int size = quote_string_for_make ((char *) 0, string);
10658 if (size == 0)
10659 return;
10661 #ifndef MAX_OUTPUT_COLUMNS
10662 #define MAX_OUTPUT_COLUMNS 72
10663 #endif
10664 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10665 && 1 < deps_column) {
10666 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10667 deps_size += 4;
10668 deps_column = 1;
10669 if (spacer == ' ')
10670 spacer = 0;
10673 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10674 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10675 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10677 if (spacer == ' ') {
10678 deps_buffer[deps_size++] = ' ';
10679 deps_column++;
10681 quote_string_for_make (&deps_buffer[deps_size], string);
10682 deps_size += size;
10683 deps_column += size;
10684 if (spacer == ':') {
10685 deps_buffer[deps_size++] = ':';
10686 deps_column++;
10688 deps_buffer[deps_size] = 0;
10691 void
10692 fatal VPROTO ((const char * msgid, ...))
10694 #ifndef ANSI_PROTOTYPES
10695 const char * msgid;
10696 #endif
10697 va_list args;
10699 fprintf (stderr, "%s: ", progname);
10700 VA_START (args, msgid);
10702 #ifndef ANSI_PROTOTYPES
10703 msgid = va_arg (args, const char *);
10704 #endif
10705 vnotice (msgid, args);
10706 va_end (args);
10707 fprintf (stderr, "\n");
10708 exit (FATAL_EXIT_CODE);
10711 /* More 'friendly' abort that prints the line and file.
10712 config.h can #define abort fancy_abort if you like that sort of thing. */
10714 void
10715 fancy_abort ()
10717 fatal ("Internal gcc abort.");
10720 static void
10721 perror_with_name (name)
10722 char *name;
10724 fprintf (stderr, "%s: %s: %s\n", progname, name, xstrerror (errno));
10725 errors++;
10728 static void
10729 pfatal_with_name (name)
10730 char *name;
10732 perror_with_name (name);
10733 #ifdef VMS
10734 exit (vaxc$errno);
10735 #else
10736 exit (FATAL_EXIT_CODE);
10737 #endif
10740 /* Handler for SIGPIPE. */
10742 static void
10743 pipe_closed (signo)
10744 /* If this is missing, some compilers complain. */
10745 int signo ATTRIBUTE_UNUSED;
10747 fatal ("output pipe has been closed");
10750 static void
10751 memory_full ()
10753 fatal ("Memory exhausted.");
10756 #ifdef VMS
10758 /* Under VMS we need to fix up the "include" specification filename.
10760 Rules for possible conversions
10762 fullname tried paths
10764 name name
10765 ./dir/name [.dir]name
10766 /dir/name dir:name
10767 /name [000000]name, name
10768 dir/name dir:[000000]name, dir:name, dir/name
10769 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10770 path:/name path:[000000]name, path:name
10771 path:/dir/name path:[000000.dir]name, path:[dir]name
10772 path:dir/name path:[dir]name
10773 [path]:[dir]name [path.dir]name
10774 path/[dir]name [path.dir]name
10776 The path:/name input is constructed when expanding <> includes.
10778 return 1 if name was changed, 0 else. */
10780 static int
10781 hack_vms_include_specification (fullname, vaxc_include)
10782 char *fullname;
10783 int vaxc_include;
10785 register char *basename, *unixname, *local_ptr, *first_slash;
10786 int f, check_filename_before_returning, must_revert;
10787 char Local[512];
10789 check_filename_before_returning = 0;
10790 must_revert = 0;
10791 /* See if we can find a 1st slash. If not, there's no path information. */
10792 first_slash = index (fullname, '/');
10793 if (first_slash == 0)
10794 return 0; /* Nothing to do!!! */
10796 /* construct device spec if none given. */
10798 if (index (fullname, ':') == 0)
10801 /* If fullname has a slash, take it as device spec. */
10803 if (first_slash == fullname)
10805 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10806 if (first_slash)
10807 *first_slash = ':'; /* make device spec */
10808 for (basename = fullname; *basename != 0; basename++)
10809 *basename = *(basename+1); /* remove leading slash */
10811 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10812 && (first_slash[-1] != ':')
10813 && (first_slash[-1] != ']')) /* or a vms path */
10815 *first_slash = ':';
10817 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10818 && (first_slash[-1] == '.'))
10819 fullname += 2;
10822 /* Get part after first ':' (basename[-1] == ':')
10823 or last '/' (basename[-1] == '/'). */
10825 basename = base_name (fullname);
10828 * Check if we have a vax-c style '#include filename'
10829 * and add the missing .h
10832 if (vaxc_include && !index (basename,'.'))
10833 strcat (basename, ".h");
10835 local_ptr = Local; /* initialize */
10837 /* We are trying to do a number of things here. First of all, we are
10838 trying to hammer the filenames into a standard format, such that later
10839 processing can handle them.
10841 If the file name contains something like [dir.], then it recognizes this
10842 as a root, and strips the ".]". Later processing will add whatever is
10843 needed to get things working properly.
10845 If no device is specified, then the first directory name is taken to be
10846 a device name (or a rooted logical). */
10848 /* Point to the UNIX filename part (which needs to be fixed!)
10849 but skip vms path information.
10850 [basename != fullname since first_slash != 0]. */
10852 if ((basename[-1] == ':') /* vms path spec. */
10853 || (basename[-1] == ']')
10854 || (basename[-1] == '>'))
10855 unixname = basename;
10856 else
10857 unixname = fullname;
10859 if (*unixname == '/')
10860 unixname++;
10862 /* If the directory spec is not rooted, we can just copy
10863 the UNIX filename part and we are done. */
10865 if (((basename - fullname) > 1)
10866 && ( (basename[-1] == ']')
10867 || (basename[-1] == '>')))
10869 if (basename[-2] != '.')
10872 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10873 -> PATH]:/name (basename = '/name', unixname = 'name')
10874 We strip the `]', and then splice the two parts of the name in the
10875 usual way. Given the default locations for include files in cccp.c,
10876 we will only use this code if the user specifies alternate locations
10877 with the /include (-I) switch on the command line. */
10879 basename -= 1; /* Strip "]" */
10880 unixname--; /* backspace */
10882 else
10885 /* The VMS part has a ".]" at the end, and this will not do. Later
10886 processing will add a second directory spec, and this would be a syntax
10887 error. Thus we strip the ".]", and thus merge the directory specs.
10888 We also backspace unixname, so that it points to a '/'. This inhibits the
10889 generation of the 000000 root directory spec (which does not belong here
10890 in this case). */
10892 basename -= 2; /* Strip ".]" */
10893 unixname--; /* backspace */
10897 else
10901 /* We drop in here if there is no VMS style directory specification yet.
10902 If there is no device specification either, we make the first dir a
10903 device and try that. If we do not do this, then we will be essentially
10904 searching the users default directory (as if they did a #include "asdf.h").
10906 Then all we need to do is to push a '[' into the output string. Later
10907 processing will fill this in, and close the bracket. */
10909 if ((unixname != fullname) /* vms path spec found. */
10910 && (basename[-1] != ':'))
10911 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10913 *local_ptr++ = '['; /* Open the directory specification */
10916 if (unixname == fullname) /* no vms dir spec. */
10918 must_revert = 1;
10919 if ((first_slash != 0) /* unix dir spec. */
10920 && (*unixname != '/') /* not beginning with '/' */
10921 && (*unixname != '.')) /* or './' or '../' */
10922 *local_ptr++ = '.'; /* dir is local ! */
10925 /* at this point we assume that we have the device spec, and (at least
10926 the opening "[" for a directory specification. We may have directories
10927 specified already.
10929 If there are no other slashes then the filename will be
10930 in the "root" directory. Otherwise, we need to add
10931 directory specifications. */
10933 if (index (unixname, '/') == 0)
10935 /* if no directories specified yet and none are following. */
10936 if (local_ptr[-1] == '[')
10938 /* Just add "000000]" as the directory string */
10939 strcpy (local_ptr, "000000]");
10940 local_ptr += strlen (local_ptr);
10941 check_filename_before_returning = 1; /* we might need to fool with this later */
10944 else
10947 /* As long as there are still subdirectories to add, do them. */
10948 while (index (unixname, '/') != 0)
10950 /* If this token is "." we can ignore it
10951 if it's not at the beginning of a path. */
10952 if ((unixname[0] == '.') && (unixname[1] == '/'))
10954 /* remove it at beginning of path. */
10955 if ( ((unixname == fullname) /* no device spec */
10956 && (fullname+2 != basename)) /* starts with ./ */
10957 /* or */
10958 || ((basename[-1] == ':') /* device spec */
10959 && (unixname-1 == basename))) /* and ./ afterwards */
10960 *local_ptr++ = '.'; /* make '[.' start of path. */
10961 unixname += 2;
10962 continue;
10965 /* Add a subdirectory spec. Do not duplicate "." */
10966 if ( local_ptr[-1] != '.'
10967 && local_ptr[-1] != '['
10968 && local_ptr[-1] != '<')
10969 *local_ptr++ = '.';
10971 /* If this is ".." then the spec becomes "-" */
10972 if ( (unixname[0] == '.')
10973 && (unixname[1] == '.')
10974 && (unixname[2] == '/'))
10976 /* Add "-" and skip the ".." */
10977 if ((local_ptr[-1] == '.')
10978 && (local_ptr[-2] == '['))
10979 local_ptr--; /* prevent [.- */
10980 *local_ptr++ = '-';
10981 unixname += 3;
10982 continue;
10985 /* Copy the subdirectory */
10986 while (*unixname != '/')
10987 *local_ptr++= *unixname++;
10989 unixname++; /* Skip the "/" */
10992 /* Close the directory specification */
10993 if (local_ptr[-1] == '.') /* no trailing periods */
10994 local_ptr--;
10996 if (local_ptr[-1] == '[') /* no dir needed */
10997 local_ptr--;
10998 else
10999 *local_ptr++ = ']';
11002 /* Now add the filename. */
11004 while (*unixname)
11005 *local_ptr++ = *unixname++;
11006 *local_ptr = 0;
11008 /* Now append it to the original VMS spec. */
11010 strcpy ((must_revert==1)?fullname:basename, Local);
11012 /* If we put a [000000] in the filename, try to open it first. If this fails,
11013 remove the [000000], and return that name. This provides flexibility
11014 to the user in that they can use both rooted and non-rooted logical names
11015 to point to the location of the file. */
11017 if (check_filename_before_returning)
11019 f = open (fullname, O_RDONLY, 0666);
11020 if (f >= 0)
11022 /* The file name is OK as it is, so return it as is. */
11023 close (f);
11024 return 1;
11027 /* The filename did not work. Try to remove the [000000] from the name,
11028 and return it. */
11030 basename = index (fullname, '[');
11031 local_ptr = index (fullname, ']') + 1;
11032 strcpy (basename, local_ptr); /* this gets rid of it */
11036 return 1;
11038 #endif /* VMS */
11040 #ifdef VMS
11042 /* The following wrapper functions supply additional arguments to the VMS
11043 I/O routines to optimize performance with file handling. The arguments
11044 are:
11045 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
11046 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
11047 "fop=tef"- Truncate unused portions of file when closing file.
11048 "shr=nil"- Disallow file sharing while file is open. */
11050 static FILE *
11051 VMS_freopen (fname, type, oldfile)
11052 char *fname;
11053 char *type;
11054 FILE *oldfile;
11056 #undef freopen /* Get back the real freopen routine. */
11057 if (strcmp (type, "w") == 0)
11058 return freopen (fname, type, oldfile,
11059 "mbc=16", "deq=64", "fop=tef", "shr=nil");
11060 return freopen (fname, type, oldfile, "mbc=16");
11063 static FILE *
11064 VMS_fopen (fname, type)
11065 char *fname;
11066 char *type;
11068 #undef fopen /* Get back the real fopen routine. */
11069 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
11070 fixed arguments, which matches ANSI's specification but not VAXCRTL's
11071 pre-ANSI implementation. This hack circumvents the mismatch problem. */
11072 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
11074 if (*type == 'w')
11075 return (*vmslib_fopen) (fname, type, "mbc=32",
11076 "deq=64", "fop=tef", "shr=nil");
11077 else
11078 return (*vmslib_fopen) (fname, type, "mbc=32");
11081 static int
11082 VMS_open (fname, flags, prot)
11083 char *fname;
11084 int flags;
11085 int prot;
11087 #undef open /* Get back the real open routine. */
11088 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
11091 /* more VMS hackery */
11092 #include <fab.h>
11093 #include <nam.h>
11095 extern unsigned long SYS$PARSE(), SYS$SEARCH();
11097 /* Work around another library bug. If a file is located via a searchlist,
11098 and if the device it's on is not the same device as the one specified
11099 in the first element of that searchlist, then both stat() and fstat()
11100 will fail to return info about it. `errno' will be set to EVMSERR, and
11101 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
11102 We can get around this by fully parsing the filename and then passing
11103 that absolute name to stat().
11105 Without this fix, we can end up failing to find header files, which is
11106 bad enough, but then compounding the problem by reporting the reason for
11107 failure as "normal successful completion." */
11109 #undef fstat /* Get back to the library version. */
11111 static int
11112 VMS_fstat (fd, statbuf)
11113 int fd;
11114 struct stat *statbuf;
11116 int result = fstat (fd, statbuf);
11118 if (result < 0)
11120 FILE *fp;
11121 char nambuf[NAM$C_MAXRSS+1];
11123 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
11124 result = VMS_stat (nambuf, statbuf);
11125 /* No fclose(fp) here; that would close(fd) as well. */
11128 return result;
11131 static int
11132 VMS_stat (name, statbuf)
11133 const char *name;
11134 struct stat *statbuf;
11136 int result = stat (name, statbuf);
11138 if (result < 0)
11140 struct FAB fab;
11141 struct NAM nam;
11142 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
11143 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
11145 fab = cc$rms_fab;
11146 fab.fab$l_fna = (char *) name;
11147 fab.fab$b_fns = (unsigned char) strlen (name);
11148 fab.fab$l_nam = (void *) &nam;
11149 nam = cc$rms_nam;
11150 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
11151 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
11152 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
11153 if (SYS$PARSE (&fab) & 1)
11155 if (SYS$SEARCH (&fab) & 1)
11157 res_nam[nam.nam$b_rsl] = '\0';
11158 result = stat (res_nam, statbuf);
11160 /* Clean up searchlist context cached by the system. */
11161 nam.nam$b_nop = NAM$M_SYNCHK;
11162 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
11163 (void) SYS$PARSE (&fab);
11167 return result;
11170 static size_t
11171 VMS_fwrite (ptr, size, nitems, stream)
11172 void const *ptr;
11173 size_t size;
11174 size_t nitems;
11175 FILE *stream;
11177 /* VMS fwrite has undesirable results
11178 if STREAM happens to be a record oriented file.
11179 Work around this problem by writing each character individually. */
11180 char const *p = ptr;
11181 size_t bytes = size * nitems;
11182 char *lim = p + bytes;
11184 while (p < lim)
11185 if (putc (*p++, stream) == EOF)
11186 return 0;
11188 return bytes;
11190 #endif /* VMS */