Daily bump.
[official-gcc.git] / gcc / cccp.c
blob6e2d519f6263bee59b2c39076638b1c02b430e11
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 static int VMS_fstat (), VMS_stat ();
76 static int VMS_open ();
77 static FILE *VMS_fopen ();
78 static FILE *VMS_freopen ();
79 static int hack_vms_include_specification ();
80 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
81 #define INO_T_HASH(a) 0
82 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
83 #endif /* VMS */
85 /* Windows does not natively support inodes, and neither does MSDOS. */
86 #if (defined (_WIN32) && ! defined (__CYGWIN__) && ! defined (_UWIN)) \
87 || defined (__MSDOS__)
88 #define INO_T_EQ(a, b) 0
89 #endif
91 #ifndef INO_T_EQ
92 #define INO_T_EQ(a, b) ((a) == (b))
93 #endif
95 #ifndef INO_T_HASH
96 #define INO_T_HASH(a) (a)
97 #endif
99 #ifndef INCLUDE_LEN_FUDGE
100 #define INCLUDE_LEN_FUDGE 0
101 #endif
103 /* External declarations. */
105 extern char *version_string;
106 HOST_WIDEST_INT parse_escape PROTO((char **, HOST_WIDEST_INT));
107 HOST_WIDEST_INT parse_c_expression PROTO((char *, int));
109 /* Name under which this program was invoked. */
111 static char *progname;
113 /* Nonzero means use extra default include directories for C++. */
115 static int cplusplus;
117 /* Nonzero means handle cplusplus style comments */
119 static int cplusplus_comments;
121 /* Nonzero means handle #import, for objective C. */
123 static int objc;
125 /* Nonzero means this is an assembly file, and allow
126 unknown directives, which could be comments. */
128 static int lang_asm;
130 /* Current maximum length of directory names in the search path
131 for include files. (Altered as we get more of them.) */
133 static int max_include_len;
135 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
137 static int for_lint = 0;
139 /* Nonzero means copy comments into the output file. */
141 static int put_out_comments = 0;
143 /* Nonzero means don't process the ANSI trigraph sequences. */
145 static int no_trigraphs = 0;
147 /* Nonzero means print the names of included files rather than
148 the preprocessed output. 1 means just the #include "...",
149 2 means #include <...> as well. */
151 static int print_deps = 0;
153 /* Nonzero if missing .h files in -M output are assumed to be generated
154 files and not errors. */
156 static int print_deps_missing_files = 0;
158 /* Nonzero means print names of header files (-H). */
160 static int print_include_names = 0;
162 /* Nonzero means don't output line number information. */
164 static int no_line_directives;
166 /* Nonzero means output the text in failing conditionals,
167 inside #failed ... #endfailed. */
169 static int output_conditionals;
171 /* dump_only means inhibit output of the preprocessed text
172 and instead output the definitions of all user-defined
173 macros in a form suitable for use as input to cccp.
174 dump_names means pass #define and the macro name through to output.
175 dump_definitions means pass the whole definition (plus #define) through
178 static enum {dump_none, dump_only, dump_names, dump_definitions}
179 dump_macros = dump_none;
181 /* Nonzero means pass all #define and #undef directives which we actually
182 process through to the output stream. This feature is used primarily
183 to allow cc1 to record the #defines and #undefs for the sake of
184 debuggers which understand about preprocessor macros, but it may
185 also be useful with -E to figure out how symbols are defined, and
186 where they are defined. */
187 static int debug_output = 0;
189 /* Nonzero means pass #include lines through to the output,
190 even if they are ifdefed out. */
191 static int dump_includes;
193 /* Nonzero indicates special processing used by the pcp program. The
194 special effects of this mode are:
196 Inhibit all macro expansion, except those inside #if directives.
198 Process #define directives normally, and output their contents
199 to the output file.
201 Output preconditions to pcp_outfile indicating all the relevant
202 preconditions for use of this file in a later cpp run.
204 static FILE *pcp_outfile;
206 /* Nonzero means we are inside an IF during a -pcp run. In this mode
207 macro expansion is done, and preconditions are output for all macro
208 uses requiring them. */
209 static int pcp_inside_if;
211 /* Nonzero means never to include precompiled files.
212 This is 1 since there's no way now to make precompiled files,
213 so it's not worth testing for them. */
214 static int no_precomp = 1;
216 /* Nonzero means give all the error messages the ANSI standard requires. */
218 int pedantic;
220 /* Nonzero means try to make failure to fit ANSI C an error. */
222 static int pedantic_errors;
224 /* Nonzero means don't print warning messages. -w. */
226 static int inhibit_warnings = 0;
228 /* Nonzero means warn if slash-star appears in a slash-star comment,
229 or if newline-backslash appears in a slash-slash comment. */
231 static int warn_comments;
233 /* Nonzero means warn if a macro argument is (or would be)
234 stringified with -traditional. */
236 static int warn_stringify;
238 /* Nonzero means warn if there are any trigraphs. */
240 static int warn_trigraphs;
242 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
244 static int warn_undef;
246 /* Nonzero means warn if #import is used. */
248 static int warn_import = 1;
250 /* Nonzero means turn warnings into errors. */
252 static int warnings_are_errors;
254 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
256 int traditional;
258 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
260 int c89;
262 /* Nonzero for the 199x C Standard. */
264 int c9x;
266 /* Nonzero causes output not to be done,
267 but directives such as #define that have side effects
268 are still obeyed. */
270 static int no_output;
272 /* Nonzero means we should look for header.gcc files that remap file names. */
273 static int remap;
275 /* Nonzero means this file was included with a -imacros or -include
276 command line and should not be recorded as an include file. */
278 static int no_record_file;
280 /* Nonzero means that we have finished processing the command line options.
281 This flag is used to decide whether or not to issue certain errors
282 and/or warnings. */
284 static int done_initializing = 0;
286 /* Line where a newline was first seen in a string constant. */
288 static int multiline_string_line = 0;
290 /* I/O buffer structure.
291 The `fname' field is nonzero for source files and #include files
292 and for the dummy text used for -D and -U.
293 It is zero for rescanning results of macro expansion
294 and for expanding macro arguments. */
295 #define INPUT_STACK_MAX 400
296 static struct file_buf {
297 char *fname;
298 /* Filename specified with #line directive. */
299 char *nominal_fname;
300 /* The length of nominal_fname, which may contain embedded NULs. */
301 size_t nominal_fname_len;
302 /* Include file description. */
303 struct include_file *inc;
304 /* Record where in the search path this file was found.
305 For #include_next. */
306 struct file_name_list *dir;
307 int lineno;
308 int length;
309 U_CHAR *buf;
310 U_CHAR *bufp;
311 /* Macro that this level is the expansion of.
312 Included so that we can reenable the macro
313 at the end of this level. */
314 struct hashnode *macro;
315 /* Value of if_stack at start of this file.
316 Used to prohibit unmatched #endif (etc) in an include file. */
317 struct if_stack *if_stack;
318 /* Object to be freed at end of input at this level. */
319 U_CHAR *free_ptr;
320 /* True if this is a system header file; see is_system_include. */
321 char system_header_p;
322 } instack[INPUT_STACK_MAX];
324 static int last_error_tick; /* Incremented each time we print it. */
325 static int input_file_stack_tick; /* Incremented when the status changes. */
327 /* Current nesting level of input sources.
328 `instack[indepth]' is the level currently being read. */
329 static int indepth = -1;
330 #define CHECK_DEPTH(code) \
331 if (indepth >= (INPUT_STACK_MAX - 1)) \
333 error_with_line (line_for_error (instack[indepth].lineno), \
334 "macro or `#include' recursion too deep"); \
335 code; \
338 /* Current depth in #include directives that use <...>. */
339 static int system_include_depth = 0;
341 typedef struct file_buf FILE_BUF;
343 /* The output buffer. Its LENGTH field is the amount of room allocated
344 for the buffer, not the number of chars actually present. To get
345 that, subtract outbuf.buf from outbuf.bufp. */
347 #define OUTBUF_SIZE 10 /* initial size of output buffer */
348 static FILE_BUF outbuf;
350 /* Grow output buffer OBUF points at
351 so it can hold at least NEEDED more chars. */
353 #define check_expand(OBUF, NEEDED) \
354 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
355 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
357 struct file_name_list
359 struct file_name_list *next;
360 /* If the following is 1, it is a C-language system include
361 directory. */
362 int c_system_include_path;
363 /* Mapping of file names for this directory. */
364 struct file_name_map *name_map;
365 /* Non-zero if name_map is valid. */
366 int got_name_map;
367 /* The include directory status. */
368 struct stat st;
369 /* The include prefix: "" denotes the working directory,
370 otherwise fname must end in '/'.
371 The actual size is dynamically allocated. */
372 char fname[1];
375 /* #include "file" looks in source file dir, then stack. */
376 /* #include <file> just looks in the stack. */
377 /* -I directories are added to the end, then the defaults are added. */
378 /* The */
379 static struct default_include {
380 char *fname; /* The name of the directory. */
381 char *component; /* The component containing the directory */
382 int cplusplus; /* Only look here if we're compiling C++. */
383 int cxx_aware; /* Includes in this directory don't need to
384 be wrapped in extern "C" when compiling
385 C++. */
386 int included; /* Set if the directory is acceptable. */
387 } include_defaults_array[]
388 #ifdef INCLUDE_DEFAULTS
389 = INCLUDE_DEFAULTS;
390 #else
392 /* Pick up GNU C++ specific include files. */
393 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1, 0 },
394 #ifdef CROSS_COMPILE
395 /* This is the dir for fixincludes. Put it just before
396 the files that we fix. */
397 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
398 /* For cross-compilation, this dir name is generated
399 automatically in Makefile.in. */
400 { CROSS_INCLUDE_DIR, "GCC", 0, 0, 0 },
401 #ifdef TOOL_INCLUDE_DIR
402 /* This is another place that the target system's headers might be. */
403 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
404 #endif
405 #else /* not CROSS_COMPILE */
406 #ifdef LOCAL_INCLUDE_DIR
407 /* This should be /usr/local/include and should come before
408 the fixincludes-fixed header files. */
409 { LOCAL_INCLUDE_DIR, 0, 0, 1, 0 },
410 #endif
411 #ifdef TOOL_INCLUDE_DIR
412 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
413 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
414 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0, 0 },
415 #endif
416 /* This is the dir for fixincludes. Put it just before
417 the files that we fix. */
418 { GCC_INCLUDE_DIR, "GCC", 0, 0, 0 },
419 /* Some systems have an extra dir of include files. */
420 #ifdef SYSTEM_INCLUDE_DIR
421 { SYSTEM_INCLUDE_DIR, 0, 0, 0, 0 },
422 #endif
423 #ifndef STANDARD_INCLUDE_COMPONENT
424 #define STANDARD_INCLUDE_COMPONENT 0
425 #endif
426 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0, 0 },
427 #endif /* not CROSS_COMPILE */
428 { 0, 0, 0, 0, 0 }
430 #endif /* no INCLUDE_DEFAULTS */
432 /* The code looks at the defaults through this pointer, rather than through
433 the constant structure above. This pointer gets changed if an environment
434 variable specifies other defaults. */
435 static struct default_include *include_defaults = include_defaults_array;
437 static struct file_name_list *include = 0; /* First dir to search */
438 /* First dir to search for <file> */
439 /* This is the first element to use for #include <...>.
440 If it is 0, use the entire chain for such includes. */
441 static struct file_name_list *first_bracket_include = 0;
442 /* This is the first element in the chain that corresponds to
443 a directory of system header files. */
444 static struct file_name_list *first_system_include = 0;
445 static struct file_name_list *last_include = 0; /* Last in chain */
447 /* Chain of include directories to put at the end of the other chain. */
448 static struct file_name_list *after_include = 0;
449 static struct file_name_list *last_after_include = 0; /* Last in chain */
451 /* Chain to put at the start of the system include files. */
452 static struct file_name_list *before_system = 0;
453 static struct file_name_list *last_before_system = 0; /* Last in chain */
455 /* Directory prefix that should replace `/usr' in the standard
456 include file directories. */
457 static char *include_prefix;
459 /* Maintain and search list of included files. */
461 struct include_file {
462 struct include_file *next; /* for include_hashtab */
463 struct include_file *next_ino; /* for include_ino_hashtab */
464 char *fname;
465 /* If the following is the empty string, it means #pragma once
466 was seen in this include file, or #import was applied to the file.
467 Otherwise, if it is nonzero, it is a macro name.
468 Don't include the file again if that macro is defined. */
469 U_CHAR *control_macro;
470 /* Nonzero if the dependency on this include file has been output. */
471 int deps_output;
472 struct stat st;
475 /* Hash tables of files already included with #include or #import.
476 include_hashtab is by full name; include_ino_hashtab is by inode number. */
478 #define INCLUDE_HASHSIZE 61
479 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
480 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
482 /* Global list of strings read in from precompiled files. This list
483 is kept in the order the strings are read in, with new strings being
484 added at the end through stringlist_tailp. We use this list to output
485 the strings at the end of the run.
487 static STRINGDEF *stringlist;
488 static STRINGDEF **stringlist_tailp = &stringlist;
491 /* Structure returned by create_definition */
492 typedef struct macrodef MACRODEF;
493 struct macrodef
495 struct definition *defn;
496 U_CHAR *symnam;
497 int symlen;
500 enum sharp_token_type {
501 NO_SHARP_TOKEN = 0, /* token not present */
503 SHARP_TOKEN = '#', /* token spelled with # only */
504 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
506 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
507 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
510 /* Structure allocated for every #define. For a simple replacement
511 such as
512 #define foo bar ,
513 nargs = -1, the `pattern' list is null, and the expansion is just
514 the replacement text. Nargs = 0 means a functionlike macro with no args,
515 e.g.,
516 #define getchar() getc (stdin) .
517 When there are args, the expansion is the replacement text with the
518 args squashed out, and the reflist is a list describing how to
519 build the output from the input: e.g., "3 chars, then the 1st arg,
520 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
521 The chars here come from the expansion. Whatever is left of the
522 expansion after the last arg-occurrence is copied after that arg.
523 Note that the reflist can be arbitrarily long---
524 its length depends on the number of times the arguments appear in
525 the replacement text, not how many args there are. Example:
526 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
527 pattern list
528 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
529 where (x, y) means (nchars, argno). */
531 typedef struct definition DEFINITION;
532 struct definition {
533 int nargs;
534 int length; /* length of expansion string */
535 int predefined; /* True if the macro was builtin or */
536 /* came from the command line */
537 U_CHAR *expansion;
538 int line; /* Line number of definition */
539 char *file; /* File of definition */
540 size_t file_len; /* Length of file (which can contain NULs) */
541 char rest_args; /* Nonzero if last arg. absorbs the rest */
542 struct reflist {
543 struct reflist *next;
545 enum sharp_token_type stringify; /* set if a # operator before arg */
546 enum sharp_token_type raw_before; /* set if a ## operator before arg */
547 enum sharp_token_type raw_after; /* set if a ## operator after arg */
549 char rest_args; /* Nonzero if this arg. absorbs the rest */
550 int nchars; /* Number of literal chars to copy before
551 this arg occurrence. */
552 int argno; /* Number of arg to substitute (origin-0) */
553 } *pattern;
554 union {
555 /* Names of macro args, concatenated in reverse order
556 with comma-space between them.
557 The only use of this is that we warn on redefinition
558 if this differs between the old and new definitions. */
559 U_CHAR *argnames;
560 } args;
563 /* different kinds of things that can appear in the value field
564 of a hash node. Actually, this may be useless now. */
565 union hashval {
566 char *cpval;
567 DEFINITION *defn;
568 KEYDEF *keydef;
572 * special extension string that can be added to the last macro argument to
573 * allow it to absorb the "rest" of the arguments when expanded. Ex:
574 * #define wow(a, b...) process (b, a, b)
575 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
576 * { wow (one, two); } -> { process (two, one, two); }
577 * if this "rest_arg" is used with the concat token '##' and if it is not
578 * supplied then the token attached to with ## will not be outputted. Ex:
579 * #define wow (a, b...) process (b ## , a, ## b)
580 * { wow (1, 2); } -> { process (2, 1, 2); }
581 * { wow (one); } -> { process (one); {
583 static char rest_extension[] = "...";
584 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
586 /* This is the implicit parameter name when using variable number of
587 parameters for macros using the ISO C 9x extension. */
588 static char va_args_name[] = "__VA_ARGS__";
589 #define VA_ARGS_NAME_LENGTH (sizeof (va_args_name) - 1)
591 /* The structure of a node in the hash table. The hash table
592 has entries for all tokens defined by #define directives (type T_MACRO),
593 plus some special tokens like __LINE__ (these each have their own
594 type, and the appropriate code is run when that type of node is seen.
595 It does not contain control words like "#define", which are recognized
596 by a separate piece of code. */
598 /* different flavors of hash nodes --- also used in keyword table */
599 enum node_type {
600 T_DEFINE = 1, /* the `#define' keyword */
601 T_INCLUDE, /* the `#include' keyword */
602 T_INCLUDE_NEXT, /* the `#include_next' keyword */
603 T_IMPORT, /* the `#import' keyword */
604 T_IFDEF, /* the `#ifdef' keyword */
605 T_IFNDEF, /* the `#ifndef' keyword */
606 T_IF, /* the `#if' keyword */
607 T_ELSE, /* `#else' */
608 T_PRAGMA, /* `#pragma' */
609 T_ELIF, /* `#elif' */
610 T_UNDEF, /* `#undef' */
611 T_LINE, /* `#line' */
612 T_ERROR, /* `#error' */
613 T_WARNING, /* `#warning' */
614 T_ENDIF, /* `#endif' */
615 T_SCCS, /* `#sccs', used on system V. */
616 T_IDENT, /* `#ident', used on system V. */
617 T_ASSERT, /* `#assert', taken from system V. */
618 T_UNASSERT, /* `#unassert', taken from system V. */
619 T_SPECLINE, /* special symbol `__LINE__' */
620 T_DATE, /* `__DATE__' */
621 T_FILE, /* `__FILE__' */
622 T_BASE_FILE, /* `__BASE_FILE__' */
623 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
624 T_VERSION, /* `__VERSION__' */
625 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
626 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
627 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
628 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
629 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
630 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
631 T_TIME, /* `__TIME__' */
632 T_CONST, /* Constant value, used by `__STDC__' */
633 T_MACRO, /* macro defined by `#define' */
634 T_DISABLED, /* macro temporarily turned off for rescan */
635 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
636 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
637 T_UNUSED /* Used for something not defined. */
640 struct hashnode {
641 struct hashnode *next; /* double links for easy deletion */
642 struct hashnode *prev;
643 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
644 chain is kept, in case the node is the head
645 of the chain and gets deleted. */
646 enum node_type type; /* type of special token */
647 int length; /* length of token, for quick comparison */
648 U_CHAR *name; /* the actual name */
649 union hashval value; /* pointer to expansion, or whatever */
652 typedef struct hashnode HASHNODE;
654 /* Some definitions for the hash table. The hash function MUST be
655 computed as shown in hashf () below. That is because the rescan
656 loop computes the hash value `on the fly' for most tokens,
657 in order to avoid the overhead of a lot of procedure calls to
658 the hashf () function. Hashf () only exists for the sake of
659 politeness, for use when speed isn't so important. */
661 #define HASHSIZE 1403
662 static HASHNODE *hashtab[HASHSIZE];
663 #define HASHSTEP(old, c) ((old << 2) + c)
664 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
667 /* We let tm.h override the types used here, to handle trivial differences
668 such as the choice of unsigned int or long unsigned int for size_t.
669 When machines start needing nontrivial differences in the size type,
670 it would be best to do something here to figure out automatically
671 from other information what type to use. */
673 /* The string value for __SIZE_TYPE__. */
675 #ifndef SIZE_TYPE
676 #define SIZE_TYPE "long unsigned int"
677 #endif
679 /* The string value for __PTRDIFF_TYPE__. */
681 #ifndef PTRDIFF_TYPE
682 #define PTRDIFF_TYPE "long int"
683 #endif
685 /* The string value for __WCHAR_TYPE__. */
687 #ifndef WCHAR_TYPE
688 #define WCHAR_TYPE "int"
689 #endif
690 char * wchar_type = WCHAR_TYPE;
691 #undef WCHAR_TYPE
693 /* The string value for __USER_LABEL_PREFIX__ */
695 #ifndef USER_LABEL_PREFIX
696 #define USER_LABEL_PREFIX ""
697 #endif
698 char * user_label_prefix = USER_LABEL_PREFIX;
699 #undef USER_LABEL_PREFIX
701 /* The string value for __REGISTER_PREFIX__ */
703 #ifndef REGISTER_PREFIX
704 #define REGISTER_PREFIX ""
705 #endif
707 /* The string value for __IMMEDIATE_PREFIX__ */
709 #ifndef IMMEDIATE_PREFIX
710 #define IMMEDIATE_PREFIX ""
711 #endif
713 /* In the definition of a #assert name, this structure forms
714 a list of the individual values asserted.
715 Each value is itself a list of "tokens".
716 These are strings that are compared by name. */
718 struct tokenlist_list {
719 struct tokenlist_list *next;
720 struct arglist *tokens;
723 struct assertion_hashnode {
724 struct assertion_hashnode *next; /* double links for easy deletion */
725 struct assertion_hashnode *prev;
726 /* also, a back pointer to this node's hash
727 chain is kept, in case the node is the head
728 of the chain and gets deleted. */
729 struct assertion_hashnode **bucket_hdr;
730 int length; /* length of token, for quick comparison */
731 U_CHAR *name; /* the actual name */
732 /* List of token-sequences. */
733 struct tokenlist_list *value;
736 typedef struct assertion_hashnode ASSERTION_HASHNODE;
738 /* Some definitions for the hash table. The hash function MUST be
739 computed as shown in hashf below. That is because the rescan
740 loop computes the hash value `on the fly' for most tokens,
741 in order to avoid the overhead of a lot of procedure calls to
742 the hashf function. hashf only exists for the sake of
743 politeness, for use when speed isn't so important. */
745 #define ASSERTION_HASHSIZE 37
746 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
748 /* Nonzero means inhibit macroexpansion of what seem to be
749 assertion tests, in rescan. For #if. */
750 static int assertions_flag;
752 /* `struct directive' defines one #-directive, including how to handle it. */
754 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
756 struct directive {
757 int length; /* Length of name */
758 int (*func) DO_PROTO; /* Function to handle directive */
759 char *name; /* Name of directive */
760 enum node_type type; /* Code which describes which directive. */
763 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
764 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
766 /* These functions are declared to return int instead of void since they
767 are going to be placed in the table and some old compilers have trouble with
768 pointers to functions returning void. */
770 static int do_assert DO_PROTO;
771 static int do_define DO_PROTO;
772 static int do_elif DO_PROTO;
773 static int do_else DO_PROTO;
774 static int do_endif DO_PROTO;
775 static int do_error DO_PROTO;
776 static int do_ident DO_PROTO;
777 static int do_if DO_PROTO;
778 static int do_include DO_PROTO;
779 static int do_line DO_PROTO;
780 static int do_pragma DO_PROTO;
781 #ifdef SCCS_DIRECTIVE
782 static int do_sccs DO_PROTO;
783 #endif
784 static int do_unassert DO_PROTO;
785 static int do_undef DO_PROTO;
786 static int do_warning DO_PROTO;
787 static int do_xifdef DO_PROTO;
789 /* Here is the actual list of #-directives, most-often-used first. */
791 static struct directive directive_table[] = {
792 { 6, do_define, "define", T_DEFINE},
793 { 2, do_if, "if", T_IF},
794 { 5, do_xifdef, "ifdef", T_IFDEF},
795 { 6, do_xifdef, "ifndef", T_IFNDEF},
796 { 5, do_endif, "endif", T_ENDIF},
797 { 4, do_else, "else", T_ELSE},
798 { 4, do_elif, "elif", T_ELIF},
799 { 4, do_line, "line", T_LINE},
800 { 7, do_include, "include", T_INCLUDE},
801 { 12, do_include, "include_next", T_INCLUDE_NEXT},
802 { 6, do_include, "import", T_IMPORT},
803 { 5, do_undef, "undef", T_UNDEF},
804 { 5, do_error, "error", T_ERROR},
805 { 7, do_warning, "warning", T_WARNING},
806 #ifdef SCCS_DIRECTIVE
807 { 4, do_sccs, "sccs", T_SCCS},
808 #endif
809 { 6, do_pragma, "pragma", T_PRAGMA},
810 { 5, do_ident, "ident", T_IDENT},
811 { 6, do_assert, "assert", T_ASSERT},
812 { 8, do_unassert, "unassert", T_UNASSERT},
813 { -1, 0, "", T_UNUSED},
816 /* When a directive handler is called,
817 this points to the # (or the : of the %:) that started the directive. */
818 U_CHAR *directive_start;
820 /* table to tell if char can be part of a C identifier. */
821 U_CHAR is_idchar[256];
822 /* table to tell if char can be first char of a c identifier. */
823 U_CHAR is_idstart[256];
824 /* table to tell if c is horizontal space. */
825 static U_CHAR is_hor_space[256];
826 /* table to tell if c is horizontal or vertical space. */
827 U_CHAR is_space[256];
829 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
830 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
832 static int errors = 0; /* Error counter for exit code */
834 /* Name of output file, for error messages. */
835 static char *out_fname;
837 /* Nonzero to ignore \ in string constants. Use to treat #line 1 "A:\file.h
838 as a non-form feed. If you want it to be a form feed, you must use
839 # 1 "\f". */
840 static int ignore_escape_flag = 1;
842 /* Stack of conditionals currently in progress
843 (including both successful and failing conditionals). */
845 struct if_stack {
846 struct if_stack *next; /* for chaining to the next stack frame */
847 char *fname; /* copied from input when frame is made */
848 size_t fname_len; /* similarly */
849 int lineno; /* similarly */
850 int if_succeeded; /* true if a leg of this if-group
851 has been passed through rescan */
852 U_CHAR *control_macro; /* For #ifndef at start of file,
853 this is the macro name tested. */
854 enum node_type type; /* type of last directive seen in this group */
856 typedef struct if_stack IF_STACK_FRAME;
857 static IF_STACK_FRAME *if_stack = NULL;
859 /* Buffer of -M output. */
860 static char *deps_buffer;
862 /* Number of bytes allocated in above. */
863 static int deps_allocated_size;
865 /* Number of bytes used. */
866 static int deps_size;
868 /* Number of bytes since the last newline. */
869 static int deps_column;
871 /* Nonzero means -I- has been seen,
872 so don't look for #include "foo" the source-file directory. */
873 static int ignore_srcdir;
875 static int safe_read PROTO((int, char *, int));
876 static void safe_write PROTO((int, char *, int));
877 static void eprint_string PROTO((const char *, size_t));
879 int main PROTO((int, char **));
881 static void path_include PROTO((char *));
883 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
885 static void trigraph_pcp PROTO((FILE_BUF *));
887 static void newline_fix PROTO((U_CHAR *));
888 static void name_newline_fix PROTO((U_CHAR *));
890 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
892 static void rescan PROTO((FILE_BUF *, int));
894 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
896 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
898 static struct tm *timestamp PROTO((void));
899 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
901 static int is_system_include PROTO((char *));
902 static char *base_name PROTO((char *));
903 static int absolute_filename PROTO((char *));
904 static size_t simplify_filename PROTO((char *));
906 static char *read_filename_string PROTO((int, FILE *));
907 static struct file_name_map *read_name_map PROTO((char *));
908 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
909 static char *remap_include_file PROTO((char *, struct file_name_list *));
910 static int lookup_ino_include PROTO((struct include_file *));
912 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
913 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
915 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
916 static int check_preconditions PROTO((char *));
917 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
918 static void pcstring_used PROTO((HASHNODE *));
919 static void write_output PROTO((void));
920 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
922 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
924 static int check_macro_name PROTO((U_CHAR *, int));
925 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
926 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
928 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
930 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
931 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
933 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
934 static void free_token_list PROTO((struct arglist *));
936 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
937 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
938 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
940 static void do_once PROTO((void));
942 static HOST_WIDEST_INT eval_if_expression PROTO((U_CHAR *, int));
943 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
944 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
945 static void validate_else PROTO((U_CHAR *, U_CHAR *));
947 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
948 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
949 static char *quote_string PROTO((char *, char *, size_t));
950 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
952 /* Last arg to output_line_directive. */
953 enum file_change_code {same_file, enter_file, leave_file};
954 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
956 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
958 struct argdata;
959 static int macarg PROTO((struct argdata *, int));
961 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
963 static int discard_comments PROTO((U_CHAR *, int, int));
965 static int change_newlines PROTO((U_CHAR *, int));
967 static char *my_strerror PROTO((int));
968 static void notice PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
969 static void vnotice PROTO((const char *, va_list));
970 void error PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
971 void verror PROTO((const char *, va_list));
972 static void error_from_errno PROTO((char *));
973 void warning PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
974 static void vwarning PROTO((const char *, va_list));
975 static void error_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
976 static void verror_with_line PROTO((int, const char *, va_list));
977 static void vwarning_with_line PROTO((int, const char *, va_list));
978 static void warning_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
979 void pedwarn PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
980 void pedwarn_with_line PVPROTO((int, const char *, ...)) ATTRIBUTE_PRINTF_2;
981 static void pedwarn_with_file_and_line PVPROTO((const char *, size_t, int, const char *, ...)) ATTRIBUTE_PRINTF_4;
982 static void pedwarn_strange_white_space PROTO((int));
984 static void print_containing_files PROTO((void));
986 static int line_for_error PROTO((int));
987 static int grow_outbuf PROTO((FILE_BUF *, int));
989 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
990 HASHNODE *lookup PROTO((U_CHAR *, int, int));
991 static void delete_macro PROTO((HASHNODE *));
992 static int hashf PROTO((U_CHAR *, int, int));
994 static void dump_single_macro PROTO((HASHNODE *, FILE *));
995 static void dump_all_macros PROTO((void));
996 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
997 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
999 static void initialize_char_syntax PROTO((void));
1000 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1002 static void make_definition PROTO((char *));
1003 static void make_undef PROTO((char *, FILE_BUF *));
1005 static void make_assertion PROTO((const char *, const char *));
1007 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, const char *, const char *, const char *));
1008 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1010 static int quote_string_for_make PROTO((char *, const char *));
1011 static void deps_output PROTO((const char *, int));
1013 void fatal PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
1014 void fancy_abort PROTO((void)) ATTRIBUTE_NORETURN;
1015 static void perror_with_name PROTO((char *));
1016 static void pfatal_with_name PROTO((char *)) ATTRIBUTE_NORETURN;
1017 static void pipe_closed PROTO((int)) ATTRIBUTE_NORETURN;
1019 static void memory_full PROTO((void)) ATTRIBUTE_NORETURN;
1020 static void print_help PROTO((void));
1022 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1023 retrying if necessary. If MAX_READ_LEN is defined, read at most
1024 that bytes at a time. Return a negative value if an error occurs,
1025 otherwise return the actual number of bytes read,
1026 which must be LEN unless end-of-file was reached. */
1028 static int
1029 safe_read (desc, ptr, len)
1030 int desc;
1031 char *ptr;
1032 int len;
1034 int left, rcount, nchars;
1036 left = len;
1037 while (left > 0) {
1038 rcount = left;
1039 #ifdef MAX_READ_LEN
1040 if (rcount > MAX_READ_LEN)
1041 rcount = MAX_READ_LEN;
1042 #endif
1043 nchars = read (desc, ptr, rcount);
1044 if (nchars < 0)
1046 #ifdef EINTR
1047 if (errno == EINTR)
1048 continue;
1049 #endif
1050 return nchars;
1052 if (nchars == 0)
1053 break;
1054 ptr += nchars;
1055 left -= nchars;
1057 return len - left;
1060 /* Write LEN bytes at PTR to descriptor DESC,
1061 retrying if necessary, and treating any real error as fatal.
1062 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1064 static void
1065 safe_write (desc, ptr, len)
1066 int desc;
1067 char *ptr;
1068 int len;
1070 int wcount, written;
1072 while (len > 0) {
1073 wcount = len;
1074 #ifdef MAX_WRITE_LEN
1075 if (wcount > MAX_WRITE_LEN)
1076 wcount = MAX_WRITE_LEN;
1077 #endif
1078 written = write (desc, ptr, wcount);
1079 if (written < 0)
1081 #ifdef EINTR
1082 if (errno == EINTR)
1083 continue;
1084 #endif
1085 pfatal_with_name (out_fname);
1087 ptr += written;
1088 len -= written;
1092 /* Print a string to stderr, with extra handling in case it contains
1093 embedded NUL characters. Any present are written as is.
1095 Using fwrite for this purpose produces undesireable results on VMS
1096 when stderr happens to be a record oriented file, such as a batch log
1097 file, rather than a stream oriented one. */
1099 static void
1100 eprint_string (string, length)
1101 const char *string;
1102 size_t length;
1104 size_t segment_length;
1106 do {
1107 fprintf(stderr, "%s", string);
1108 length -= (segment_length = strlen(string));
1109 if (length > 0)
1111 fputc('\0', stderr);
1112 length -= 1;
1113 /* Advance past the portion which has already been printed. */
1114 string += segment_length + 1;
1116 } while (length > 0);
1120 static void
1121 print_help ()
1123 printf ("Usage: %s [switches] input output\n", progname);
1124 printf ("Switches:\n");
1125 printf (" -include <file> Include the contents of <file> before other files\n");
1126 printf (" -imacros <file> Accept definition of marcos in <file>\n");
1127 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
1128 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
1129 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
1130 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
1131 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
1132 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
1133 printf (" -nostdinc Do not search the system include directories\n");
1134 printf (" -nostdinc++ Do not search the system include directories for C++\n");
1135 printf (" -o <file> Put output into <file>\n");
1136 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
1137 printf (" -traditional Follow K&R pre-processor behaviour\n");
1138 printf (" -trigraphs Support ANSI C trigraphs\n");
1139 printf (" -lang-c Assume that the input sources are in C\n");
1140 printf (" -lang-c89 Assume that the input is C89; depricated\n");
1141 printf (" -lang-c++ Assume that the input sources are in C++\n");
1142 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
1143 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
1144 printf (" -lang-asm Assume that the input sources are in assembler\n");
1145 printf (" -lang-chill Assume that the input sources are in Chill\n");
1146 printf (" -std=<std name> Specify the conformance standard; one of:\n");
1147 printf (" gnu89, gnu9x, c89, c9x, iso9899:1990,\n");
1148 printf (" iso9899:199409, iso9899:199x\n");
1149 printf (" -+ Allow parsing of C++ style features\n");
1150 printf (" -w Inhibit warning messages\n");
1151 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
1152 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
1153 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
1154 printf (" -Wno-comment{s} Do not warn about comments\n");
1155 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
1156 printf (" a string if -traditional is specified\n");
1157 printf (" -Wno-traditional Do not warn about stringification\n");
1158 printf (" -Wundef Warn if an undefined macro is used by #if\n");
1159 printf (" -Wno-undef Do not warn about testing undefined macros\n");
1160 printf (" -Wimport Warn about the use of the #import directive\n");
1161 printf (" -Wno-import Do not warn about the use of #import\n");
1162 printf (" -Werror Treat all warnings as errors\n");
1163 printf (" -Wno-error Do not treat warnings as errors\n");
1164 printf (" -Wall Enable all preprocessor warnings\n");
1165 printf (" -M Generate make dependencies\n");
1166 printf (" -MM As -M, but ignore system header files\n");
1167 printf (" -MD As -M, but put output in a .d file\n");
1168 printf (" -MMD As -MD, but ignore system header files\n");
1169 printf (" -MG Treat missing header file as generated files\n");
1170 printf (" -g Include #define and #undef directives in the output\n");
1171 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
1172 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
1173 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
1174 printf (" -U<macro> Undefine <macro> \n");
1175 printf (" -u or -undef Do not predefine any macros\n");
1176 printf (" -v Display the version number\n");
1177 printf (" -H Print the name of header files as they are used\n");
1178 printf (" -C Do not discard comments\n");
1179 printf (" -dM Display a list of macro definitions active at end\n");
1180 printf (" -dD Preserve macro definitions in output\n");
1181 printf (" -dN As -dD except that only the names are preserved\n");
1182 printf (" -dI Include #include directives in the output\n");
1183 printf (" -ifoutput Describe skipped code blocks in output \n");
1184 printf (" -P Do not generate #line directives\n");
1185 printf (" -$ Do not include '$' in identifiers\n");
1186 printf (" -remap Remap file names when including files.\n");
1187 printf (" -h or --help Display this information\n");
1191 main (argc, argv)
1192 int argc;
1193 char **argv;
1195 struct stat st;
1196 char *in_fname;
1197 char *cp;
1198 int f, i;
1199 FILE_BUF *fp;
1201 char **pend_files;
1202 char **pend_defs;
1203 char **pend_undefs;
1204 char **pend_assertions;
1205 char **pend_includes;
1207 /* Record the option used with each element of pend_assertions.
1208 This is preparation for supporting more than one option for making
1209 an assertion. */
1210 char **pend_assertion_options;
1211 int no_standard_includes = 0;
1212 int no_standard_cplusplus_includes = 0;
1213 int missing_newline = 0;
1215 /* Non-0 means don't output the preprocessed program. */
1216 int inhibit_output = 0;
1217 /* Non-0 means -v, so print the full set of include dirs. */
1218 int verbose = 0;
1220 /* File name which deps are being written to.
1221 This is 0 if deps are being written to stdout. */
1222 char *deps_file = 0;
1223 /* Fopen file mode to open deps_file with. */
1224 char *deps_mode = "a";
1225 /* Stream on which to print the dependency information. */
1226 FILE *deps_stream = 0;
1227 /* Target-name to write with the dependency information. */
1228 char *deps_target = 0;
1230 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1231 /* Get rid of any avoidable limit on stack size. */
1233 struct rlimit rlim;
1235 /* Set the stack limit huge so that alloca (particularly stringtab
1236 in dbxread.c) does not fail. */
1237 getrlimit (RLIMIT_STACK, &rlim);
1238 rlim.rlim_cur = rlim.rlim_max;
1239 setrlimit (RLIMIT_STACK, &rlim);
1241 #endif
1243 #ifdef SIGPIPE
1244 signal (SIGPIPE, pipe_closed);
1245 #endif
1247 #ifdef HAVE_LC_MESSAGES
1248 setlocale (LC_MESSAGES, "");
1249 #endif
1250 (void) bindtextdomain (PACKAGE, localedir);
1251 (void) textdomain (PACKAGE);
1253 progname = base_name (argv[0]);
1255 #ifdef VMS
1257 /* Remove extension from PROGNAME. */
1258 char *p;
1259 char *s = progname = xstrdup (progname);
1261 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1262 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1263 && (p[1] == 'e' || p[1] == 'E')
1264 && (p[2] == 'x' || p[2] == 'X')
1265 && (p[3] == 'e' || p[3] == 'E')
1266 && !p[4])
1267 *p = '\0';
1269 #endif
1271 /* Do not invoke xmalloc before this point, since locale and
1272 progname need to be set first, in case a diagnostic is issued. */
1274 pend_files = (char **) xmalloc (argc * sizeof (char *));
1275 pend_defs = (char **) xmalloc (argc * sizeof (char *));
1276 pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1277 pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1278 pend_includes = (char **) xmalloc (argc * sizeof (char *));
1279 pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1281 in_fname = NULL;
1282 out_fname = NULL;
1284 /* Initialize is_idchar. */
1285 initialize_char_syntax ();
1287 no_line_directives = 0;
1288 no_trigraphs = 1;
1289 dump_macros = dump_none;
1290 no_output = 0;
1291 cplusplus = 0;
1292 cplusplus_comments = 1;
1294 bzero ((char *) pend_files, argc * sizeof (char *));
1295 bzero ((char *) pend_defs, argc * sizeof (char *));
1296 bzero ((char *) pend_undefs, argc * sizeof (char *));
1297 bzero ((char *) pend_assertions, argc * sizeof (char *));
1298 bzero ((char *) pend_includes, argc * sizeof (char *));
1300 #ifdef MULTIBYTE_CHARS
1301 /* Change to the native locale for multibyte conversions. */
1302 setlocale (LC_CTYPE, "");
1303 literal_codeset = getenv ("LANG");
1304 #endif
1306 /* Process switches and find input file name. */
1308 for (i = 1; i < argc; i++) {
1309 if (argv[i][0] != '-') {
1310 if (out_fname != NULL)
1312 print_help ();
1313 fatal ("Too many arguments");
1315 else if (in_fname != NULL)
1316 out_fname = argv[i];
1317 else
1318 in_fname = argv[i];
1319 } else {
1320 switch (argv[i][1]) {
1322 case 'i':
1323 if (!strcmp (argv[i], "-include")) {
1324 int temp = i;
1326 if (i + 1 == argc)
1327 fatal ("Filename missing after `-include' option");
1328 else
1329 simplify_filename (pend_includes[temp] = argv[++i]);
1331 if (!strcmp (argv[i], "-imacros")) {
1332 int temp = i;
1334 if (i + 1 == argc)
1335 fatal ("Filename missing after `-imacros' option");
1336 else
1337 simplify_filename (pend_files[temp] = argv[++i]);
1339 if (!strcmp (argv[i], "-iprefix")) {
1340 if (i + 1 == argc)
1341 fatal ("Filename missing after `-iprefix' option");
1342 else
1343 include_prefix = argv[++i];
1345 if (!strcmp (argv[i], "-ifoutput")) {
1346 output_conditionals = 1;
1348 if (!strcmp (argv[i], "-isystem")) {
1349 struct file_name_list *dirtmp;
1351 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1352 "", argv[++i])))
1353 break;
1354 dirtmp->c_system_include_path = 1;
1356 if (before_system == 0)
1357 before_system = dirtmp;
1358 else
1359 last_before_system->next = dirtmp;
1360 last_before_system = dirtmp; /* Tail follows the last one */
1362 /* Add directory to end of path for includes,
1363 with the default prefix at the front of its name. */
1364 if (!strcmp (argv[i], "-iwithprefix")) {
1365 struct file_name_list *dirtmp;
1366 char *prefix;
1368 if (include_prefix != 0)
1369 prefix = include_prefix;
1370 else {
1371 prefix = xstrdup (GCC_INCLUDE_DIR);
1372 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1373 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1374 prefix[strlen (prefix) - 7] = 0;
1377 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1378 prefix, argv[++i])))
1379 break;
1381 if (after_include == 0)
1382 after_include = dirtmp;
1383 else
1384 last_after_include->next = dirtmp;
1385 last_after_include = dirtmp; /* Tail follows the last one */
1387 /* Add directory to main path for includes,
1388 with the default prefix at the front of its name. */
1389 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1390 struct file_name_list *dirtmp;
1391 char *prefix;
1393 if (include_prefix != 0)
1394 prefix = include_prefix;
1395 else {
1396 prefix = xstrdup (GCC_INCLUDE_DIR);
1397 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1398 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1399 prefix[strlen (prefix) - 7] = 0;
1402 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1403 append_include_chain (dirtmp, dirtmp);
1405 /* Add directory to end of path for includes. */
1406 if (!strcmp (argv[i], "-idirafter")) {
1407 struct file_name_list *dirtmp;
1409 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1410 "", argv[++i])))
1411 break;
1413 if (after_include == 0)
1414 after_include = dirtmp;
1415 else
1416 last_after_include->next = dirtmp;
1417 last_after_include = dirtmp; /* Tail follows the last one */
1419 break;
1421 case 'o':
1422 if (out_fname != NULL)
1423 fatal ("Output filename specified twice");
1424 if (i + 1 == argc)
1425 fatal ("Filename missing after -o option");
1426 out_fname = argv[++i];
1427 if (!strcmp (out_fname, "-"))
1428 out_fname = "";
1429 break;
1431 case 'p':
1432 if (!strcmp (argv[i], "-pedantic"))
1433 pedantic = 1;
1434 else if (!strcmp (argv[i], "-pedantic-errors")) {
1435 pedantic = 1;
1436 pedantic_errors = 1;
1437 } else if (!strcmp (argv[i], "-pcp")) {
1438 char *pcp_fname;
1439 if (i + 1 == argc)
1440 fatal ("Filename missing after -pcp option");
1441 pcp_fname = argv[++i];
1442 pcp_outfile
1443 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1444 ? fopen (pcp_fname, "w")
1445 : stdout);
1446 if (pcp_outfile == 0)
1447 pfatal_with_name (pcp_fname);
1448 no_precomp = 1;
1450 break;
1452 case 't':
1453 if (!strcmp (argv[i], "-traditional")) {
1454 traditional = 1;
1455 cplusplus_comments = 0;
1456 } else if (!strcmp (argv[i], "-trigraphs")) {
1457 no_trigraphs = 0;
1459 break;
1461 case 'l':
1462 if (! strcmp (argv[i], "-lang-c"))
1463 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1464 else if (! strcmp (argv[i], "-lang-c89"))
1465 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1466 else if (! strcmp (argv[i], "-lang-c++"))
1467 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 0;
1468 else if (! strcmp (argv[i], "-lang-objc"))
1469 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1470 else if (! strcmp (argv[i], "-lang-objc++"))
1471 cplusplus = 1, cplusplus_comments = 1, c89 = 0, c9x = 0, objc = 1;
1472 else if (! strcmp (argv[i], "-lang-asm"))
1473 lang_asm = 1;
1474 else if (! strcmp (argv[i], "-lint"))
1475 for_lint = 1;
1476 break;
1478 case '+':
1479 cplusplus = 1, cplusplus_comments = 1;
1480 break;
1482 case 's':
1483 if (!strcmp (argv[i], "-std=iso9899:1990")
1484 || !strcmp (argv[i], "-std=iso9899:199409")
1485 || !strcmp (argv[i], "-std=c89")
1486 || !strcmp (argv[i], "-std=gnu89"))
1487 cplusplus = 0, cplusplus_comments = 0, c89 = 1, c9x = 0, objc = 0;
1488 else if (!strcmp (argv[i], "-std=iso9899:199x")
1489 || !strcmp (argv[i], "-std=c9x")
1490 || !strcmp (argv[i], "-std=gnu9x"))
1491 cplusplus = 0, cplusplus_comments = 1, c89 = 0, c9x = 1, objc = 0;
1492 break;
1494 case 'w':
1495 inhibit_warnings = 1;
1496 break;
1498 case 'W':
1499 if (!strcmp (argv[i], "-Wtrigraphs"))
1500 warn_trigraphs = 1;
1501 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1502 warn_trigraphs = 0;
1503 else if (!strcmp (argv[i], "-Wcomment"))
1504 warn_comments = 1;
1505 else if (!strcmp (argv[i], "-Wno-comment"))
1506 warn_comments = 0;
1507 else if (!strcmp (argv[i], "-Wcomments"))
1508 warn_comments = 1;
1509 else if (!strcmp (argv[i], "-Wno-comments"))
1510 warn_comments = 0;
1511 else if (!strcmp (argv[i], "-Wtraditional"))
1512 warn_stringify = 1;
1513 else if (!strcmp (argv[i], "-Wno-traditional"))
1514 warn_stringify = 0;
1515 else if (!strcmp (argv[i], "-Wundef"))
1516 warn_undef = 1;
1517 else if (!strcmp (argv[i], "-Wno-undef"))
1518 warn_undef = 0;
1519 else if (!strcmp (argv[i], "-Wimport"))
1520 warn_import = 1;
1521 else if (!strcmp (argv[i], "-Wno-import"))
1522 warn_import = 0;
1523 else if (!strcmp (argv[i], "-Werror"))
1524 warnings_are_errors = 1;
1525 else if (!strcmp (argv[i], "-Wno-error"))
1526 warnings_are_errors = 0;
1527 else if (!strcmp (argv[i], "-Wall"))
1529 warn_trigraphs = 1;
1530 warn_comments = 1;
1532 break;
1534 case 'f':
1535 if (!strcmp (argv[i], "-fleading-underscore"))
1536 user_label_prefix = "_";
1537 else if (!strcmp (argv[i], "-fno-leading-underscore"))
1538 user_label_prefix = "";
1539 break;
1541 case 'M':
1542 /* The style of the choices here is a bit mixed.
1543 The chosen scheme is a hybrid of keeping all options in one string
1544 and specifying each option in a separate argument:
1545 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1546 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1547 -M[M][G][D file]. This is awkward to handle in specs, and is not
1548 as extensible. */
1549 /* ??? -MG must be specified in addition to one of -M or -MM.
1550 This can be relaxed in the future without breaking anything.
1551 The converse isn't true. */
1553 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1554 if (!strcmp (argv[i], "-MG"))
1556 print_deps_missing_files = 1;
1557 break;
1559 if (!strcmp (argv[i], "-M"))
1560 print_deps = 2;
1561 else if (!strcmp (argv[i], "-MM"))
1562 print_deps = 1;
1563 else if (!strcmp (argv[i], "-MD"))
1564 print_deps = 2;
1565 else if (!strcmp (argv[i], "-MMD"))
1566 print_deps = 1;
1567 /* For -MD and -MMD options, write deps on file named by next arg. */
1568 if (!strcmp (argv[i], "-MD")
1569 || !strcmp (argv[i], "-MMD")) {
1570 if (i + 1 == argc)
1571 fatal ("Filename missing after %s option", argv[i]);
1572 i++;
1573 deps_file = argv[i];
1574 deps_mode = "w";
1575 } else {
1576 /* For -M and -MM, write deps on standard output
1577 and suppress the usual output. */
1578 deps_stream = stdout;
1579 inhibit_output = 1;
1581 break;
1583 case 'd':
1585 char *p = argv[i] + 2;
1586 char c;
1587 while ((c = *p++)) {
1588 /* Arg to -d specifies what parts of macros to dump */
1589 switch (c) {
1590 case 'M':
1591 dump_macros = dump_only;
1592 no_output = 1;
1593 break;
1594 case 'N':
1595 dump_macros = dump_names;
1596 break;
1597 case 'D':
1598 dump_macros = dump_definitions;
1599 break;
1600 case 'I':
1601 dump_includes = 1;
1602 break;
1606 break;
1608 case 'g':
1609 if (argv[i][2] == '3')
1610 debug_output = 1;
1611 break;
1613 case '-':
1614 if (strcmp (argv[i], "--help") != 0)
1615 return i;
1616 print_help ();
1617 exit (0);
1618 break;
1620 case 'v':
1621 notice ("GNU CPP version %s", version_string);
1622 #ifdef TARGET_VERSION
1623 TARGET_VERSION;
1624 #endif
1625 fprintf (stderr, "\n");
1626 verbose = 1;
1627 break;
1629 case 'H':
1630 print_include_names = 1;
1631 break;
1633 case 'D':
1634 if (argv[i][2] != 0)
1635 pend_defs[i] = argv[i] + 2;
1636 else if (i + 1 == argc)
1637 fatal ("Macro name missing after -D option");
1638 else
1639 i++, pend_defs[i] = argv[i];
1640 break;
1642 case 'A':
1644 char *p;
1646 if (argv[i][2] != 0)
1647 p = argv[i] + 2;
1648 else if (i + 1 == argc)
1649 fatal ("Assertion missing after -A option");
1650 else
1651 p = argv[++i];
1653 if (!strcmp (p, "-")) {
1654 /* -A- eliminates all predefined macros and assertions.
1655 Let's include also any that were specified earlier
1656 on the command line. That way we can get rid of any
1657 that were passed automatically in from GCC. */
1658 int j;
1659 for (j = 0; j < i; j++)
1660 pend_defs[j] = pend_assertions[j] = 0;
1661 } else {
1662 pend_assertions[i] = p;
1663 pend_assertion_options[i] = "-A";
1666 break;
1668 case 'U': /* JF #undef something */
1669 if (argv[i][2] != 0)
1670 pend_undefs[i] = argv[i] + 2;
1671 else if (i + 1 == argc)
1672 fatal ("Macro name missing after -U option");
1673 else
1674 pend_undefs[i] = argv[i+1], i++;
1675 break;
1677 case 'C':
1678 put_out_comments = 1;
1679 break;
1681 case 'E': /* -E comes from cc -E; ignore it. */
1682 break;
1684 case 'P':
1685 no_line_directives = 1;
1686 break;
1688 case '$': /* Don't include $ in identifiers. */
1689 is_idchar['$'] = is_idstart['$'] = 0;
1690 break;
1692 case 'I': /* Add directory to path for includes. */
1694 struct file_name_list *dirtmp;
1696 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1697 ignore_srcdir = 1;
1698 /* Don't use any preceding -I directories for #include <...>. */
1699 first_bracket_include = 0;
1701 else {
1702 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1703 argv[i][2] ? argv[i] + 2 : argv[++i]);
1704 append_include_chain (dirtmp, dirtmp);
1707 break;
1709 case 'n':
1710 if (!strcmp (argv[i], "-nostdinc"))
1711 /* -nostdinc causes no default include directories.
1712 You must specify all include-file directories with -I. */
1713 no_standard_includes = 1;
1714 else if (!strcmp (argv[i], "-nostdinc++"))
1715 /* -nostdinc++ causes no default C++-specific include directories. */
1716 no_standard_cplusplus_includes = 1;
1717 else if (!strcmp (argv[i], "-noprecomp"))
1718 no_precomp = 1;
1719 break;
1721 case 'r':
1722 if (!strcmp (argv[i], "-remap"))
1723 remap = 1;
1724 break;
1726 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1727 if (in_fname == NULL) {
1728 in_fname = "";
1729 break;
1730 } else if (out_fname == NULL) {
1731 out_fname = "";
1732 break;
1733 } /* else fall through into error */
1735 default:
1736 fatal ("Invalid option `%s'", argv[i]);
1741 /* Add dirs from CPATH after dirs from -I. */
1742 /* There seems to be confusion about what CPATH should do,
1743 so for the moment it is not documented. */
1744 /* Some people say that CPATH should replace the standard include dirs,
1745 but that seems pointless: it comes before them, so it overrides them
1746 anyway. */
1747 GET_ENV_PATH_LIST (cp, "CPATH");
1748 if (cp && ! no_standard_includes)
1749 path_include (cp);
1751 /* Initialize output buffer */
1753 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1754 outbuf.bufp = outbuf.buf;
1755 outbuf.length = OUTBUF_SIZE;
1757 /* Do partial setup of input buffer for the sake of generating
1758 early #line directives (when -g is in effect). */
1760 fp = &instack[++indepth];
1761 if (in_fname == NULL)
1762 in_fname = "";
1763 fp->nominal_fname = fp->fname = in_fname;
1764 fp->nominal_fname_len = strlen (in_fname);
1765 fp->lineno = 0;
1767 /* In C++, wchar_t is a distinct basic type, and we can expect
1768 __wchar_t to be defined by cc1plus. */
1769 if (cplusplus)
1770 wchar_type = "__wchar_t";
1772 /* Install __LINE__, etc. Must follow initialize_char_syntax
1773 and option processing. */
1774 initialize_builtins (fp, &outbuf);
1776 /* Now handle the command line options. */
1778 /* Do -U's, -D's and -A's in the order they were seen. */
1779 for (i = 1; i < argc; i++) {
1780 if (pend_undefs[i]) {
1781 if (debug_output)
1782 output_line_directive (fp, &outbuf, 0, same_file);
1783 make_undef (pend_undefs[i], &outbuf);
1785 if (pend_defs[i]) {
1786 if (debug_output)
1787 output_line_directive (fp, &outbuf, 0, same_file);
1788 make_definition (pend_defs[i]);
1790 if (pend_assertions[i])
1791 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1794 done_initializing = 1;
1796 { /* Read the appropriate environment variable and if it exists
1797 replace include_defaults with the listed path. */
1798 char *epath = 0;
1799 switch ((objc << 1) + cplusplus)
1801 case 0:
1802 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
1803 break;
1804 case 1:
1805 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
1806 break;
1807 case 2:
1808 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
1809 break;
1810 case 3:
1811 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
1812 break;
1814 /* If the environment var for this language is set,
1815 add to the default list of include directories. */
1816 if (epath) {
1817 int num_dirs;
1818 char *startp, *endp;
1820 for (num_dirs = 1, startp = epath; *startp; startp++)
1821 if (*startp == PATH_SEPARATOR)
1822 num_dirs++;
1823 include_defaults
1824 = (struct default_include *) xmalloc ((num_dirs
1825 * sizeof (struct default_include))
1826 + sizeof (include_defaults_array));
1827 startp = endp = epath;
1828 num_dirs = 0;
1829 while (1) {
1830 char c = *endp++;
1831 if (c == PATH_SEPARATOR || !c) {
1832 endp[-1] = 0;
1833 include_defaults[num_dirs].fname
1834 = startp == endp ? "." : xstrdup (startp);
1835 endp[-1] = c;
1836 include_defaults[num_dirs].component = 0;
1837 include_defaults[num_dirs].cplusplus = cplusplus;
1838 include_defaults[num_dirs].cxx_aware = 1;
1839 num_dirs++;
1840 if (!c)
1841 break;
1842 startp = endp;
1845 /* Put the usual defaults back in at the end. */
1846 bcopy ((char *) include_defaults_array,
1847 (char *) &include_defaults[num_dirs],
1848 sizeof (include_defaults_array));
1852 append_include_chain (before_system, last_before_system);
1853 first_system_include = before_system;
1855 /* Unless -fnostdinc,
1856 tack on the standard include file dirs to the specified list */
1857 if (!no_standard_includes) {
1858 struct default_include *p = include_defaults;
1859 char *specd_prefix = include_prefix;
1860 char *default_prefix = xstrdup (GCC_INCLUDE_DIR);
1861 int default_len = 0;
1862 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1863 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1864 default_len = strlen (default_prefix) - 7;
1865 default_prefix[default_len] = 0;
1867 /* Search "translated" versions of GNU directories.
1868 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1869 if (specd_prefix != 0 && default_len != 0)
1870 for (p = include_defaults; p->fname; p++) {
1871 /* Some standard dirs are only for C++. */
1872 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1873 /* Does this dir start with the prefix? */
1874 if (!strncmp (p->fname, default_prefix, default_len)) {
1875 /* Yes; change prefix and add to search list. */
1876 struct file_name_list *new
1877 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1878 p->fname + default_len);
1879 if (new) {
1880 new->c_system_include_path = !p->cxx_aware;
1881 append_include_chain (new, new);
1882 if (first_system_include == 0)
1883 first_system_include = new;
1884 p->included = 1;
1889 /* Search ordinary names for GNU include directories. */
1890 for (p = include_defaults; p->fname; p++) {
1891 /* Some standard dirs are only for C++. */
1892 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1893 struct file_name_list *new
1894 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1895 if (new) {
1896 new->c_system_include_path = !p->cxx_aware;
1897 append_include_chain (new, new);
1898 if (first_system_include == 0)
1899 first_system_include = new;
1900 p->included = 1;
1906 /* Tack the after_include chain at the end of the include chain. */
1907 append_include_chain (after_include, last_after_include);
1908 if (first_system_include == 0)
1909 first_system_include = after_include;
1911 /* With -v, print the list of dirs to search. */
1912 if (verbose) {
1913 struct file_name_list *p;
1914 notice ("#include \"...\" search starts here:\n");
1915 for (p = include; p; p = p->next) {
1916 if (p == first_bracket_include)
1917 notice ("#include <...> search starts here:\n");
1918 if (!p->fname[0])
1919 fprintf (stderr, " .\n");
1920 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1921 fprintf (stderr, " %s\n", p->fname);
1922 else
1923 /* Omit trailing '/'. */
1924 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1926 notice ("End of search list.\n");
1928 struct default_include * d;
1929 notice ("The following default directories have been omitted from the search path:\n");
1930 for (d = include_defaults; d->fname; d++)
1931 if (! d->included)
1932 fprintf (stderr, " %s\n", d->fname);
1933 notice ("End of omitted list.\n");
1937 /* -MG doesn't select the form of output and must be specified with one of
1938 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1939 inhibit compilation. */
1940 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1941 fatal ("-MG must be specified with one of -M or -MM");
1943 /* Either of two environment variables can specify output of deps.
1944 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1945 where OUTPUT_FILE is the file to write deps info to
1946 and DEPS_TARGET is the target to mention in the deps. */
1948 if (print_deps == 0
1949 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1950 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1951 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1952 char *s;
1953 char *output_file;
1955 if (spec == 0) {
1956 spec = getenv ("SUNPRO_DEPENDENCIES");
1957 print_deps = 2;
1959 else
1960 print_deps = 1;
1962 s = spec;
1963 /* Find the space before the DEPS_TARGET, if there is one. */
1964 /* This should use index. (mrs) */
1965 while (*s != 0 && *s != ' ') s++;
1966 if (*s != 0) {
1967 deps_target = s + 1;
1968 output_file = xmalloc (s - spec + 1);
1969 bcopy (spec, output_file, s - spec);
1970 output_file[s - spec] = 0;
1972 else {
1973 deps_target = 0;
1974 output_file = spec;
1977 deps_file = output_file;
1978 deps_mode = "a";
1981 /* For -M, print the expected object file name
1982 as the target of this Make-rule. */
1983 if (print_deps) {
1984 deps_allocated_size = 200;
1985 deps_buffer = xmalloc (deps_allocated_size);
1986 deps_buffer[0] = 0;
1987 deps_size = 0;
1988 deps_column = 0;
1990 if (deps_target) {
1991 deps_output (deps_target, ':');
1992 } else if (*in_fname == 0) {
1993 deps_output ("-", ':');
1994 } else {
1995 char *p, *q;
1996 int len;
1998 q = base_name (in_fname);
2000 /* Copy remainder to mungable area. */
2001 p = (char *) alloca (strlen(q) + 8);
2002 strcpy (p, q);
2004 /* Output P, but remove known suffixes. */
2005 len = strlen (p);
2006 q = p + len;
2007 if (len >= 2
2008 && p[len - 2] == '.'
2009 && index("cCsSm", p[len - 1]))
2010 q = p + (len - 2);
2011 else if (len >= 3
2012 && p[len - 3] == '.'
2013 && p[len - 2] == 'c'
2014 && p[len - 1] == 'c')
2015 q = p + (len - 3);
2016 else if (len >= 4
2017 && p[len - 4] == '.'
2018 && p[len - 3] == 'c'
2019 && p[len - 2] == 'x'
2020 && p[len - 1] == 'x')
2021 q = p + (len - 4);
2022 else if (len >= 4
2023 && p[len - 4] == '.'
2024 && p[len - 3] == 'c'
2025 && p[len - 2] == 'p'
2026 && p[len - 1] == 'p')
2027 q = p + (len - 4);
2029 /* Supply our own suffix. */
2030 strcpy (q, OBJECT_SUFFIX);
2032 deps_output (p, ':');
2033 deps_output (in_fname, ' ');
2037 /* Scan the -imacros files before the main input.
2038 Much like #including them, but with no_output set
2039 so that only their macro definitions matter. */
2041 no_output++; no_record_file++;
2042 for (i = 1; i < argc; i++)
2043 if (pend_files[i]) {
2044 struct include_file *inc;
2045 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2046 if (fd < 0) {
2047 perror_with_name (pend_files[i]);
2048 return FATAL_EXIT_CODE;
2050 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2052 no_output--; no_record_file--;
2054 /* Copy the entire contents of the main input file into
2055 the stacked input buffer previously allocated for it. */
2057 /* JF check for stdin */
2058 if (in_fname == NULL || *in_fname == 0) {
2059 in_fname = "";
2060 f = 0;
2061 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2062 goto perror;
2064 if (fstat (f, &st) != 0)
2065 pfatal_with_name (in_fname);
2066 fp->nominal_fname = fp->fname = in_fname;
2067 fp->nominal_fname_len = strlen (in_fname);
2068 fp->lineno = 1;
2069 fp->system_header_p = 0;
2070 /* JF all this is mine about reading pipes and ttys */
2071 if (! S_ISREG (st.st_mode)) {
2072 /* Read input from a file that is not a normal disk file.
2073 We cannot preallocate a buffer with the correct size,
2074 so we must read in the file a piece at the time and make it bigger. */
2075 int size;
2076 int bsize;
2077 int cnt;
2079 if (S_ISDIR (st.st_mode))
2080 fatal ("Input file `%s' is a directory", in_fname);
2082 bsize = 2000;
2083 size = 0;
2084 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2085 for (;;) {
2086 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2087 if (cnt < 0) goto perror; /* error! */
2088 size += cnt;
2089 if (size != bsize) break; /* End of file */
2090 bsize *= 2;
2091 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2093 fp->length = size;
2094 } else {
2095 /* Read a file whose size we can determine in advance.
2096 For the sake of VMS, st.st_size is just an upper bound. */
2097 size_t s = (size_t) st.st_size;
2098 if (s != st.st_size || s + 2 < s)
2099 memory_full ();
2100 fp->buf = (U_CHAR *) xmalloc (s + 2);
2101 fp->length = safe_read (f, (char *) fp->buf, s);
2102 if (fp->length < 0) goto perror;
2104 fp->bufp = fp->buf;
2105 fp->if_stack = if_stack;
2107 /* Make sure data ends with a newline. And put a null after it. */
2109 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2110 /* Backslash-newline at end is not good enough. */
2111 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2112 fp->buf[fp->length++] = '\n';
2113 missing_newline = 1;
2115 fp->buf[fp->length] = '\0';
2117 /* Unless inhibited, convert trigraphs in the input. */
2119 if (!no_trigraphs)
2120 trigraph_pcp (fp);
2122 /* Now that we know the input file is valid, open the output. */
2124 if (!out_fname || !strcmp (out_fname, ""))
2125 out_fname = "stdout";
2126 else if (! freopen (out_fname, "w", stdout))
2127 pfatal_with_name (out_fname);
2129 output_line_directive (fp, &outbuf, 0, same_file);
2131 /* Scan the -include files before the main input. */
2133 no_record_file++;
2134 for (i = 1; i < argc; i++)
2135 if (pend_includes[i]) {
2136 struct include_file *inc;
2137 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2138 if (fd < 0) {
2139 perror_with_name (pend_includes[i]);
2140 return FATAL_EXIT_CODE;
2142 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2144 no_record_file--;
2146 /* Scan the input, processing macros and directives. */
2148 rescan (&outbuf, 0);
2150 if (missing_newline)
2151 fp->lineno--;
2153 if (pedantic && missing_newline)
2154 pedwarn ("file does not end in newline");
2156 /* Now we have processed the entire input
2157 Write whichever kind of output has been requested. */
2159 if (dump_macros == dump_only)
2160 dump_all_macros ();
2161 else if (! inhibit_output) {
2162 write_output ();
2165 if (print_deps) {
2166 /* Don't actually write the deps file if compilation has failed. */
2167 if (errors == 0) {
2168 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2169 pfatal_with_name (deps_file);
2170 fputs (deps_buffer, deps_stream);
2171 putc ('\n', deps_stream);
2172 if (deps_file) {
2173 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2174 fatal ("I/O error on output");
2179 if (pcp_outfile && pcp_outfile != stdout
2180 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2181 fatal ("I/O error on `-pcp' output");
2183 if (ferror (stdout) || fclose (stdout) != 0)
2184 fatal ("I/O error on output");
2186 if (errors)
2187 exit (FATAL_EXIT_CODE);
2188 exit (SUCCESS_EXIT_CODE);
2190 perror:
2191 pfatal_with_name (in_fname);
2192 return 0;
2195 /* Given a colon-separated list of file names PATH,
2196 add all the names to the search path for include files. */
2198 static void
2199 path_include (path)
2200 char *path;
2202 char *p;
2204 p = path;
2206 if (*p)
2207 while (1) {
2208 char *q = p;
2209 char c;
2210 struct file_name_list *dirtmp;
2212 /* Find the end of this name. */
2213 while ((c = *q++) != PATH_SEPARATOR && c)
2214 continue;
2216 q[-1] = 0;
2217 dirtmp = new_include_prefix (last_include, NULL_PTR,
2218 "", p == q ? "." : p);
2219 q[-1] = c;
2220 append_include_chain (dirtmp, dirtmp);
2222 /* Advance past this name. */
2223 p = q;
2224 if (! c)
2225 break;
2229 /* Return the address of the first character in S that equals C.
2230 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2231 Return 0 if there is no such character. Assume that C itself is not '\0'.
2232 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2233 but unfortunately memchr isn't autoconfigured yet. */
2235 static U_CHAR *
2236 index0 (s, c, n)
2237 U_CHAR *s;
2238 int c;
2239 size_t n;
2241 char *p = (char *) s;
2242 for (;;) {
2243 char *q = index (p, c);
2244 if (q)
2245 return (U_CHAR *) q;
2246 else {
2247 size_t l = strlen (p);
2248 if (l == n)
2249 return 0;
2250 l++;
2251 p += l;
2252 n -= l;
2257 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2258 before main CCCP processing. Name `pcp' is also in honor of the
2259 drugs the trigraph designers must have been on.
2261 Using an extra pass through the buffer takes a little extra time,
2262 but is infinitely less hairy than trying to handle trigraphs inside
2263 strings, etc. everywhere, and also makes sure that trigraphs are
2264 only translated in the top level of processing. */
2266 static void
2267 trigraph_pcp (buf)
2268 FILE_BUF *buf;
2270 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2271 int len;
2273 fptr = bptr = sptr = buf->buf;
2274 lptr = fptr + buf->length;
2275 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2276 if (*++sptr != '?')
2277 continue;
2278 switch (*++sptr) {
2279 case '=':
2280 c = '#';
2281 break;
2282 case '(':
2283 c = '[';
2284 break;
2285 case '/':
2286 c = '\\';
2287 break;
2288 case ')':
2289 c = ']';
2290 break;
2291 case '\'':
2292 c = '^';
2293 break;
2294 case '<':
2295 c = '{';
2296 break;
2297 case '!':
2298 c = '|';
2299 break;
2300 case '>':
2301 c = '}';
2302 break;
2303 case '-':
2304 c = '~';
2305 break;
2306 case '?':
2307 sptr--;
2308 continue;
2309 default:
2310 continue;
2312 len = sptr - fptr - 2;
2314 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2315 C, this will be memmove (). */
2316 if (bptr != fptr && len > 0)
2317 bcopy ((char *) fptr, (char *) bptr, len);
2319 bptr += len;
2320 *bptr++ = c;
2321 fptr = ++sptr;
2323 len = buf->length - (fptr - buf->buf);
2324 if (bptr != fptr && len > 0)
2325 bcopy ((char *) fptr, (char *) bptr, len);
2326 buf->length -= fptr - bptr;
2327 buf->buf[buf->length] = '\0';
2328 if (warn_trigraphs && fptr != bptr)
2329 warning_with_line (0, "%lu trigraph(s) encountered",
2330 (unsigned long) (fptr - bptr) / 2);
2333 /* Move all backslash-newline pairs out of embarrassing places.
2334 Exchange all such pairs following BP
2335 with any potentially-embarrassing characters that follow them.
2336 Potentially-embarrassing characters are / and *
2337 (because a backslash-newline inside a comment delimiter
2338 would cause it not to be recognized). */
2340 static void
2341 newline_fix (bp)
2342 U_CHAR *bp;
2344 register U_CHAR *p = bp;
2346 /* First count the backslash-newline pairs here. */
2348 while (p[0] == '\\' && p[1] == '\n')
2349 p += 2;
2351 /* What follows the backslash-newlines is not embarrassing. */
2353 if (*p != '/' && *p != '*')
2354 return;
2356 /* Copy all potentially embarrassing characters
2357 that follow the backslash-newline pairs
2358 down to where the pairs originally started. */
2360 while (*p == '*' || *p == '/')
2361 *bp++ = *p++;
2363 /* Now write the same number of pairs after the embarrassing chars. */
2364 while (bp < p) {
2365 *bp++ = '\\';
2366 *bp++ = '\n';
2370 /* Like newline_fix but for use within a directive-name.
2371 Move any backslash-newlines up past any following symbol constituents. */
2373 static void
2374 name_newline_fix (bp)
2375 U_CHAR *bp;
2377 register U_CHAR *p = bp;
2379 /* First count the backslash-newline pairs here. */
2380 while (p[0] == '\\' && p[1] == '\n')
2381 p += 2;
2383 /* What follows the backslash-newlines is not embarrassing. */
2385 if (!is_idchar[*p])
2386 return;
2388 /* Copy all potentially embarrassing characters
2389 that follow the backslash-newline pairs
2390 down to where the pairs originally started. */
2392 while (is_idchar[*p])
2393 *bp++ = *p++;
2395 /* Now write the same number of pairs after the embarrassing chars. */
2396 while (bp < p) {
2397 *bp++ = '\\';
2398 *bp++ = '\n';
2402 /* Look for lint commands in comments.
2404 When we come in here, ibp points into a comment. Limit is as one expects.
2405 scan within the comment -- it should start, after lwsp, with a lint command.
2406 If so that command is returned as a (constant) string.
2408 Upon return, any arg will be pointed to with argstart and will be
2409 arglen long. Note that we don't parse that arg since it will just
2410 be printed out again. */
2412 static char *
2413 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2414 register U_CHAR *ibp;
2415 register U_CHAR *limit;
2416 U_CHAR **argstart; /* point to command arg */
2417 int *arglen, *cmdlen; /* how long they are */
2419 HOST_WIDEST_INT linsize;
2420 register U_CHAR *numptr; /* temp for arg parsing */
2422 *arglen = 0;
2424 SKIP_WHITE_SPACE (ibp);
2426 if (ibp >= limit) return NULL;
2428 linsize = limit - ibp;
2430 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2431 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2432 *cmdlen = 10;
2433 return "NOTREACHED";
2435 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2436 *cmdlen = 8;
2437 return "ARGSUSED";
2439 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2440 *cmdlen = 11;
2441 return "LINTLIBRARY";
2443 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2444 *cmdlen = 7;
2445 ibp += 7; linsize -= 7;
2446 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2448 /* OK, read a number */
2449 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2450 numptr++);
2451 *arglen = numptr - *argstart;
2452 return "VARARGS";
2454 return NULL;
2458 * The main loop of the program.
2460 * Read characters from the input stack, transferring them to the
2461 * output buffer OP.
2463 * Macros are expanded and push levels on the input stack.
2464 * At the end of such a level it is popped off and we keep reading.
2465 * At the end of any other kind of level, we return.
2466 * #-directives are handled, except within macros.
2468 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2469 * and insert them when appropriate. This is set while scanning macro
2470 * arguments before substitution. It is zero when scanning for final output.
2471 * There are three types of Newline markers:
2472 * * Newline - follows a macro name that was not expanded
2473 * because it appeared inside an expansion of the same macro.
2474 * This marker prevents future expansion of that identifier.
2475 * When the input is rescanned into the final output, these are deleted.
2476 * These are also deleted by ## concatenation.
2477 * * Newline Space (or Newline and any other whitespace character)
2478 * stands for a place that tokens must be separated or whitespace
2479 * is otherwise desirable, but where the ANSI standard specifies there
2480 * is no whitespace. This marker turns into a Space (or whichever other
2481 * whitespace char appears in the marker) in the final output,
2482 * but it turns into nothing in an argument that is stringified with #.
2483 * Such stringified arguments are the only place where the ANSI standard
2484 * specifies with precision that whitespace may not appear.
2486 * During this function, IP->bufp is kept cached in IBP for speed of access.
2487 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2488 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2489 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2490 * explicitly, and before RECACHE, since RECACHE uses OBP.
2493 static void
2494 rescan (op, output_marks)
2495 FILE_BUF *op;
2496 int output_marks;
2498 /* Character being scanned in main loop. */
2499 register U_CHAR c;
2501 /* Length of pending accumulated identifier. */
2502 register int ident_length = 0;
2504 /* Hash code of pending accumulated identifier. */
2505 register int hash = 0;
2507 /* Current input level (&instack[indepth]). */
2508 FILE_BUF *ip;
2510 /* Pointer for scanning input. */
2511 register U_CHAR *ibp;
2513 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2514 register U_CHAR *limit;
2516 /* Pointer for storing output. */
2517 register U_CHAR *obp;
2519 /* REDO_CHAR is nonzero if we are processing an identifier
2520 after backing up over the terminating character.
2521 Sometimes we process an identifier without backing up over
2522 the terminating character, if the terminating character
2523 is not special. Backing up is done so that the terminating character
2524 will be dispatched on again once the identifier is dealt with. */
2525 int redo_char = 0;
2527 /* 1 if within an identifier inside of which a concatenation
2528 marker (Newline -) has been seen. */
2529 int concatenated = 0;
2531 /* While scanning a comment or a string constant,
2532 this records the line it started on, for error messages. */
2533 int start_line;
2535 /* Record position of last `real' newline. */
2536 U_CHAR *beg_of_line;
2538 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2540 #define POPMACRO \
2541 do { ip->macro->type = T_MACRO; \
2542 if (ip->free_ptr) free (ip->free_ptr); \
2543 --indepth; } while (0)
2545 /* Reload `rescan's local variables that describe the current
2546 level of the input stack. */
2548 #define RECACHE \
2549 do { ip = &instack[indepth]; \
2550 ibp = ip->bufp; \
2551 limit = ip->buf + ip->length; \
2552 op->bufp = obp; \
2553 check_expand (op, limit - ibp); \
2554 beg_of_line = 0; \
2555 obp = op->bufp; } while (0)
2557 if (no_output && instack[indepth].fname != 0)
2558 skip_if_group (&instack[indepth], 1, NULL);
2560 obp = op->bufp;
2561 RECACHE;
2563 beg_of_line = ibp;
2565 /* Our caller must always put a null after the end of
2566 the input at each input stack level. */
2567 if (*limit != 0)
2568 abort ();
2570 while (1) {
2571 c = *ibp++;
2572 *obp++ = c;
2574 switch (c) {
2575 case '\\':
2576 if (*ibp == '\n' && !ip->macro) {
2577 /* At the top level, always merge lines ending with backslash-newline,
2578 even in middle of identifier. But do not merge lines in a macro,
2579 since backslash might be followed by a newline-space marker. */
2580 ++ibp;
2581 ++ip->lineno;
2582 --obp; /* remove backslash from obuf */
2583 break;
2585 /* If ANSI, backslash is just another character outside a string. */
2586 if (!traditional)
2587 goto randomchar;
2588 /* Otherwise, backslash suppresses specialness of following char,
2589 so copy it here to prevent the switch from seeing it.
2590 But first get any pending identifier processed. */
2591 if (ident_length > 0)
2592 goto specialchar;
2593 if (ibp < limit)
2594 *obp++ = *ibp++;
2595 break;
2597 case '%':
2598 if (ident_length || ip->macro || traditional)
2599 goto randomchar;
2600 while (*ibp == '\\' && ibp[1] == '\n') {
2601 ibp += 2;
2602 ++ip->lineno;
2604 if (*ibp != ':')
2605 break;
2606 /* Treat this %: digraph as if it were #. */
2607 /* Fall through. */
2609 case '#':
2610 if (assertions_flag) {
2611 if (ident_length)
2612 goto specialchar;
2613 /* Copy #foo (bar lose) without macro expansion. */
2614 obp[-1] = '#'; /* In case it was '%'. */
2615 SKIP_WHITE_SPACE (ibp);
2616 while (is_idchar[*ibp])
2617 *obp++ = *ibp++;
2618 SKIP_WHITE_SPACE (ibp);
2619 if (*ibp == '(') {
2620 ip->bufp = ibp;
2621 skip_paren_group (ip);
2622 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2623 obp += ip->bufp - ibp;
2624 ibp = ip->bufp;
2626 break;
2629 /* If this is expanding a macro definition, don't recognize
2630 preprocessing directives. */
2631 if (ip->macro != 0)
2632 goto randomchar;
2633 /* If this is expand_into_temp_buffer,
2634 don't recognize them either. Warn about them
2635 only after an actual newline at this level,
2636 not at the beginning of the input level. */
2637 if (! ip->fname) {
2638 if (ip->buf != beg_of_line)
2639 warning ("preprocessing directive not recognized within macro arg");
2640 goto randomchar;
2642 if (ident_length)
2643 goto specialchar;
2646 /* # keyword: a # must be first nonblank char on the line */
2647 if (beg_of_line == 0)
2648 goto randomchar;
2650 U_CHAR *bp;
2652 /* Scan from start of line, skipping whitespace, comments
2653 and backslash-newlines, and see if we reach this #.
2654 If not, this # is not special. */
2655 bp = beg_of_line;
2656 /* If -traditional, require # to be at beginning of line. */
2657 if (!traditional) {
2658 while (1) {
2659 if (is_hor_space[*bp])
2660 bp++;
2661 else if (*bp == '\\' && bp[1] == '\n')
2662 bp += 2;
2663 else if (*bp == '/' && bp[1] == '*') {
2664 bp += 2;
2665 while (1)
2667 if (*bp == '*')
2669 if (bp[1] == '/')
2671 bp += 2;
2672 break;
2675 else
2677 #ifdef MULTIBYTE_CHARS
2678 int length;
2679 length = local_mblen (bp, limit - bp);
2680 if (length > 1)
2681 bp += (length - 1);
2682 #endif
2684 bp++;
2687 /* There is no point in trying to deal with C++ // comments here,
2688 because if there is one, then this # must be part of the
2689 comment and we would never reach here. */
2690 else break;
2692 if (c == '%') {
2693 if (bp[0] != '%')
2694 break;
2695 while (bp[1] == '\\' && bp[2] == '\n')
2696 bp += 2;
2697 if (bp + 1 != ibp)
2698 break;
2699 /* %: appears at start of line; skip past the ':' too. */
2700 bp++;
2701 ibp++;
2704 if (bp + 1 != ibp)
2705 goto randomchar;
2708 /* This # can start a directive. */
2710 --obp; /* Don't copy the '#' */
2712 ip->bufp = ibp;
2713 op->bufp = obp;
2714 if (! handle_directive (ip, op)) {
2715 #ifdef USE_C_ALLOCA
2716 alloca (0);
2717 #endif
2718 /* Not a known directive: treat it as ordinary text.
2719 IP, OP, IBP, etc. have not been changed. */
2720 if (no_output && instack[indepth].fname) {
2721 /* If not generating expanded output,
2722 what we do with ordinary text is skip it.
2723 Discard everything until next # directive. */
2724 skip_if_group (&instack[indepth], 1, 0);
2725 RECACHE;
2726 beg_of_line = ibp;
2727 break;
2729 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2730 /* Don't expand an identifier that could be a macro directive.
2731 (Section 3.8.3 of the ANSI C standard) */
2732 SKIP_WHITE_SPACE (ibp);
2733 if (is_idstart[*ibp])
2735 *obp++ = *ibp++;
2736 while (is_idchar[*ibp])
2737 *obp++ = *ibp++;
2739 goto randomchar;
2741 #ifdef USE_C_ALLOCA
2742 alloca (0);
2743 #endif
2744 /* A # directive has been successfully processed. */
2745 /* If not generating expanded output, ignore everything until
2746 next # directive. */
2747 if (no_output && instack[indepth].fname)
2748 skip_if_group (&instack[indepth], 1, 0);
2749 obp = op->bufp;
2750 RECACHE;
2751 beg_of_line = ibp;
2752 break;
2754 case '\"': /* skip quoted string */
2755 case '\'':
2756 /* A single quoted string is treated like a double -- some
2757 programs (e.g., troff) are perverse this way */
2759 /* Handle any pending identifier;
2760 but the L in L'...' or L"..." is not an identifier. */
2761 if (ident_length) {
2762 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2763 goto specialchar;
2764 ident_length = hash = 0;
2767 start_line = ip->lineno;
2769 /* Skip ahead to a matching quote. */
2771 while (1) {
2772 if (ibp >= limit) {
2773 if (ip->macro != 0) {
2774 /* try harder: this string crosses a macro expansion boundary.
2775 This can happen naturally if -traditional.
2776 Otherwise, only -D can make a macro with an unmatched quote. */
2777 POPMACRO;
2778 RECACHE;
2779 continue;
2781 if (!traditional) {
2782 error_with_line (line_for_error (start_line),
2783 "unterminated string or character constant");
2784 if (multiline_string_line) {
2785 error_with_line (multiline_string_line,
2786 "possible real start of unterminated constant");
2787 multiline_string_line = 0;
2790 break;
2792 *obp++ = *ibp;
2793 switch (*ibp++) {
2794 case '\n':
2795 ++ip->lineno;
2796 ++op->lineno;
2797 /* Traditionally, end of line ends a string constant with no error.
2798 So exit the loop and record the new line. */
2799 if (traditional) {
2800 beg_of_line = ibp;
2801 goto while2end;
2803 if (c == '\'') {
2804 error_with_line (line_for_error (start_line),
2805 "unterminated character constant");
2806 goto while2end;
2808 if (multiline_string_line == 0) {
2809 if (pedantic)
2810 pedwarn_with_line (line_for_error (start_line),
2811 "string constant runs past end of line");
2812 multiline_string_line = ip->lineno - 1;
2814 break;
2816 case '\\':
2817 if (*ibp == '\n') {
2818 /* Backslash newline is replaced by nothing at all, but
2819 keep the line counts correct. But if we are reading
2820 from a macro, keep the backslash newline, since backslash
2821 newlines have already been processed. */
2822 if (ip->macro)
2823 *obp++ = '\n';
2824 else
2825 --obp;
2826 ++ibp;
2827 ++ip->lineno;
2828 } else {
2829 /* ANSI stupidly requires that in \\ the second \
2830 is *not* prevented from combining with a newline. */
2831 if (!ip->macro) {
2832 while (*ibp == '\\' && ibp[1] == '\n') {
2833 ibp += 2;
2834 ++ip->lineno;
2837 *obp++ = *ibp++;
2839 break;
2841 case '\"':
2842 case '\'':
2843 if (ibp[-1] == c)
2844 goto while2end;
2845 break;
2846 #ifdef MULTIBYTE_CHARS
2847 default:
2849 int length;
2850 --ibp;
2851 length = local_mblen (ibp, limit - ibp);
2852 if (length > 0)
2854 --obp;
2855 bcopy (ibp, obp, length);
2856 obp += length;
2857 ibp += length;
2859 else
2860 ++ibp;
2862 break;
2863 #endif
2866 while2end:
2867 break;
2869 case '/':
2870 if (ip->macro != 0)
2871 goto randomchar;
2872 if (*ibp == '\\' && ibp[1] == '\n')
2873 newline_fix (ibp);
2874 if (*ibp != '*'
2875 && !(cplusplus_comments && *ibp == '/'))
2876 goto randomchar;
2877 if (ident_length)
2878 goto specialchar;
2880 if (*ibp == '/') {
2881 /* C++ style comment... */
2882 start_line = ip->lineno;
2884 /* Comments are equivalent to spaces. */
2885 if (! put_out_comments)
2886 obp[-1] = ' ';
2889 U_CHAR *before_bp = ibp;
2891 while (++ibp < limit) {
2892 if (*ibp == '\n')
2894 if (put_out_comments) {
2895 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2896 obp += ibp - before_bp;
2898 break;
2900 if (*ibp == '\\')
2902 if (ibp + 1 < limit && ibp[1] == '\n')
2904 if (warn_comments)
2905 warning ("multiline `//' comment");
2906 ++ip->lineno;
2907 /* Copy the newline into the output buffer, in order to
2908 avoid the pain of a #line every time a multiline comment
2909 is seen. */
2910 if (!put_out_comments)
2911 *obp++ = '\n';
2912 ++op->lineno;
2913 ++ibp;
2916 else
2918 #ifdef MULTIBYTE_CHARS
2919 int length;
2920 length = local_mblen (ibp, limit - ibp);
2921 if (length > 1)
2922 ibp += (length - 1);
2923 #endif
2926 break;
2930 /* Ordinary C comment. Skip it, optionally copying it to output. */
2932 start_line = ip->lineno;
2934 ++ibp; /* Skip the star. */
2936 /* If this cpp is for lint, we peek inside the comments: */
2937 if (for_lint) {
2938 U_CHAR *argbp;
2939 int cmdlen, arglen;
2940 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2942 if (lintcmd != NULL) {
2943 op->bufp = obp;
2944 check_expand (op, cmdlen + arglen + 14);
2945 obp = op->bufp;
2946 /* I believe it is always safe to emit this newline: */
2947 obp[-1] = '\n';
2948 bcopy ("#pragma lint ", (char *) obp, 13);
2949 obp += 13;
2950 bcopy (lintcmd, (char *) obp, cmdlen);
2951 obp += cmdlen;
2953 if (arglen != 0) {
2954 *(obp++) = ' ';
2955 bcopy (argbp, (char *) obp, arglen);
2956 obp += arglen;
2959 /* OK, now bring us back to the state we were in before we entered
2960 this branch. We need #line because the #pragma's newline always
2961 messes up the line count. */
2962 op->bufp = obp;
2963 output_line_directive (ip, op, 0, same_file);
2964 check_expand (op, limit - ibp + 2);
2965 obp = op->bufp;
2966 *(obp++) = '/';
2970 /* Comments are equivalent to spaces.
2971 Note that we already output the slash; we might not want it.
2972 For -traditional, a comment is equivalent to nothing. */
2973 if (! put_out_comments) {
2974 if (traditional)
2975 obp--;
2976 else
2977 obp[-1] = ' ';
2979 else
2980 *obp++ = '*';
2983 U_CHAR *before_bp = ibp;
2985 for (;;) {
2986 switch (*ibp++) {
2987 case '*':
2988 if (ibp[-2] == '/' && warn_comments)
2989 warning ("`/*' within comment");
2990 if (*ibp == '\\' && ibp[1] == '\n')
2991 newline_fix (ibp);
2992 if (*ibp == '/')
2993 goto comment_end;
2994 break;
2996 case '\n':
2997 ++ip->lineno;
2998 /* Copy the newline into the output buffer, in order to
2999 avoid the pain of a #line every time a multiline comment
3000 is seen. */
3001 if (!put_out_comments)
3002 *obp++ = '\n';
3003 ++op->lineno;
3004 break;
3006 case 0:
3007 if (limit < ibp) {
3008 error_with_line (line_for_error (start_line),
3009 "unterminated comment");
3010 goto limit_reached;
3012 break;
3013 #ifdef MULTIBYTE_CHARS
3014 default:
3016 int length;
3017 length = local_mblen (ibp, limit - ibp);
3018 if (length > 1)
3019 ibp += (length - 1);
3021 break;
3022 #endif
3025 comment_end:
3027 ibp++;
3028 if (put_out_comments) {
3029 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3030 obp += ibp - before_bp;
3033 break;
3035 case '$':
3036 if (! is_idchar['$'])
3037 goto randomchar;
3038 if (pedantic)
3039 pedwarn ("`$' in identifier");
3040 goto letter;
3042 case '0': case '1': case '2': case '3': case '4':
3043 case '5': case '6': case '7': case '8': case '9':
3044 /* If digit is not part of identifier, it starts a number,
3045 which means that following letters are not an identifier.
3046 "0x5" does not refer to an identifier "x5".
3047 So copy all alphanumerics that follow without accumulating
3048 as an identifier. Periods also, for sake of "3.e7". */
3050 if (ident_length == 0) {
3051 for (;;) {
3052 if (!ip->macro) {
3053 while (ibp[0] == '\\' && ibp[1] == '\n') {
3054 ++ip->lineno;
3055 ibp += 2;
3058 c = *ibp++;
3059 if (!is_idchar[c] && c != '.') {
3060 --ibp;
3061 break;
3063 *obp++ = c;
3064 /* A sign can be part of a preprocessing number
3065 if it follows an `e' or `p'. */
3066 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3067 if (!ip->macro) {
3068 while (ibp[0] == '\\' && ibp[1] == '\n') {
3069 ++ip->lineno;
3070 ibp += 2;
3073 if (*ibp == '+' || *ibp == '-') {
3074 *obp++ = *ibp++;
3075 /* But traditional C does not let the token go past the sign,
3076 and C89 does not allow `p'. */
3077 if (traditional || (c89 && (c == 'p' || c == 'P')))
3078 break;
3082 break;
3084 /* fall through */
3086 case '_':
3087 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3088 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3089 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3090 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3091 case 'y': case 'z':
3092 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3093 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3094 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3095 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3096 case 'Y': case 'Z':
3097 letter:
3098 ident_length++;
3099 /* Compute step of hash function, to avoid a proc call on every token */
3100 hash = HASHSTEP (hash, c);
3101 break;
3103 case '\n':
3104 if (ip->fname == 0 && *ibp == '-') {
3105 /* Newline - inhibits expansion of preceding token.
3106 If expanding a macro arg, we keep the newline -.
3107 In final output, it is deleted.
3108 We recognize Newline - in macro bodies and macro args. */
3109 if (! concatenated) {
3110 ident_length = 0;
3111 hash = 0;
3113 ibp++;
3114 if (!output_marks) {
3115 obp--;
3116 } else {
3117 /* If expanding a macro arg, keep the newline -. */
3118 *obp++ = '-';
3120 break;
3123 /* If reprocessing a macro expansion, newline is a special marker. */
3124 else if (ip->macro != 0) {
3125 /* Newline White is a "funny space" to separate tokens that are
3126 supposed to be separate but without space between.
3127 Here White means any whitespace character.
3128 Newline - marks a recursive macro use that is not
3129 supposed to be expandable. */
3131 if (is_space[*ibp]) {
3132 /* Newline Space does not prevent expansion of preceding token
3133 so expand the preceding token and then come back. */
3134 if (ident_length > 0)
3135 goto specialchar;
3137 /* If generating final output, newline space makes a space. */
3138 if (!output_marks) {
3139 obp[-1] = *ibp++;
3140 /* And Newline Newline makes a newline, so count it. */
3141 if (obp[-1] == '\n')
3142 op->lineno++;
3143 } else {
3144 /* If expanding a macro arg, keep the newline space.
3145 If the arg gets stringified, newline space makes nothing. */
3146 *obp++ = *ibp++;
3148 } else abort (); /* Newline followed by something random? */
3149 break;
3152 /* If there is a pending identifier, handle it and come back here. */
3153 if (ident_length > 0)
3154 goto specialchar;
3156 beg_of_line = ibp;
3158 /* Update the line counts and output a #line if necessary. */
3159 ++ip->lineno;
3160 ++op->lineno;
3161 if (ip->lineno != op->lineno) {
3162 op->bufp = obp;
3163 output_line_directive (ip, op, 1, same_file);
3164 check_expand (op, limit - ibp);
3165 obp = op->bufp;
3167 break;
3169 /* Come here either after (1) a null character that is part of the input
3170 or (2) at the end of the input, because there is a null there. */
3171 case 0:
3172 if (ibp <= limit)
3173 /* Our input really contains a null character. */
3174 goto randomchar;
3176 limit_reached:
3177 /* At end of a macro-expansion level, pop it and read next level. */
3178 if (ip->macro != 0) {
3179 obp--;
3180 ibp--;
3181 /* If traditional, and we have an identifier that ends here,
3182 process it now, so we get the right error for recursion. */
3183 if (traditional && ident_length
3184 && ! is_idchar[*instack[indepth - 1].bufp]) {
3185 redo_char = 1;
3186 goto randomchar;
3188 POPMACRO;
3189 RECACHE;
3190 break;
3193 /* If we don't have a pending identifier,
3194 return at end of input. */
3195 if (ident_length == 0) {
3196 obp--;
3197 ibp--;
3198 op->bufp = obp;
3199 ip->bufp = ibp;
3200 goto ending;
3203 /* If we do have a pending identifier, just consider this null
3204 a special character and arrange to dispatch on it again.
3205 The second time, IDENT_LENGTH will be zero so we will return. */
3207 /* Fall through */
3209 specialchar:
3211 /* Handle the case of a character such as /, ', " or null
3212 seen following an identifier. Back over it so that
3213 after the identifier is processed the special char
3214 will be dispatched on again. */
3216 ibp--;
3217 obp--;
3218 redo_char = 1;
3220 default:
3222 randomchar:
3224 if (ident_length > 0) {
3225 register HASHNODE *hp;
3227 /* We have just seen an identifier end. If it's a macro, expand it.
3229 IDENT_LENGTH is the length of the identifier
3230 and HASH is its hash code.
3232 The identifier has already been copied to the output,
3233 so if it is a macro we must remove it.
3235 If REDO_CHAR is 0, the char that terminated the identifier
3236 has been skipped in the output and the input.
3237 OBP-IDENT_LENGTH-1 points to the identifier.
3238 If the identifier is a macro, we must back over the terminator.
3240 If REDO_CHAR is 1, the terminating char has already been
3241 backed over. OBP-IDENT_LENGTH points to the identifier. */
3243 if (!pcp_outfile || pcp_inside_if) {
3244 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3245 hp = hp->next) {
3247 if (hp->length == ident_length) {
3248 int obufp_before_macroname;
3249 int op_lineno_before_macroname;
3250 register int i = ident_length;
3251 register U_CHAR *p = hp->name;
3252 register U_CHAR *q = obp - i;
3253 int disabled;
3255 if (! redo_char)
3256 q--;
3258 do { /* All this to avoid a strncmp () */
3259 if (*p++ != *q++)
3260 goto hashcollision;
3261 } while (--i);
3263 /* We found a use of a macro name.
3264 see if the context shows it is a macro call. */
3266 /* Back up over terminating character if not already done. */
3267 if (! redo_char) {
3268 ibp--;
3269 obp--;
3272 /* Save this as a displacement from the beginning of the output
3273 buffer. We can not save this as a position in the output
3274 buffer, because it may get realloc'ed by RECACHE. */
3275 obufp_before_macroname = (obp - op->buf) - ident_length;
3276 op_lineno_before_macroname = op->lineno;
3278 if (hp->type == T_PCSTRING) {
3279 pcstring_used (hp); /* Mark the definition of this key
3280 as needed, ensuring that it
3281 will be output. */
3282 break; /* Exit loop, since the key cannot have a
3283 definition any longer. */
3286 /* Record whether the macro is disabled. */
3287 disabled = hp->type == T_DISABLED;
3289 /* This looks like a macro ref, but if the macro was disabled,
3290 just copy its name and put in a marker if requested. */
3292 if (disabled) {
3293 #if 0
3294 /* This error check caught useful cases such as
3295 #define foo(x,y) bar (x (y,0), y)
3296 foo (foo, baz) */
3297 if (traditional)
3298 error ("recursive use of macro `%s'", hp->name);
3299 #endif
3301 if (output_marks) {
3302 check_expand (op, limit - ibp + 2);
3303 *obp++ = '\n';
3304 *obp++ = '-';
3306 break;
3309 /* If macro wants an arglist, verify that a '(' follows.
3310 first skip all whitespace, copying it to the output
3311 after the macro name. Then, if there is no '(',
3312 decide this is not a macro call and leave things that way. */
3313 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3314 && hp->value.defn->nargs >= 0)
3316 U_CHAR *old_ibp = ibp;
3317 U_CHAR *old_obp = obp;
3318 int old_iln = ip->lineno;
3319 int old_oln = op->lineno;
3321 while (1) {
3322 /* Scan forward over whitespace, copying it to the output. */
3323 if (ibp == limit && ip->macro != 0) {
3324 POPMACRO;
3325 RECACHE;
3326 old_ibp = ibp;
3327 old_obp = obp;
3328 old_iln = ip->lineno;
3329 old_oln = op->lineno;
3331 else if (is_space[*ibp]) {
3332 *obp++ = *ibp++;
3333 if (ibp[-1] == '\n') {
3334 if (ip->macro == 0) {
3335 /* Newline in a file. Count it. */
3336 ++ip->lineno;
3337 ++op->lineno;
3338 } else if (!output_marks) {
3339 /* A newline mark, and we don't want marks
3340 in the output. If it is newline-hyphen,
3341 discard it entirely. Otherwise, it is
3342 newline-whitechar, so keep the whitechar. */
3343 obp--;
3344 if (*ibp == '-')
3345 ibp++;
3346 else {
3347 if (*ibp == '\n')
3348 ++op->lineno;
3349 *obp++ = *ibp++;
3351 } else {
3352 /* A newline mark; copy both chars to the output. */
3353 *obp++ = *ibp++;
3357 else if (ip->macro)
3358 break;
3359 else if (*ibp == '/') {
3360 /* If a comment, copy it unchanged or discard it. */
3361 if (ibp[1] == '\\' && ibp[2] == '\n')
3362 newline_fix (ibp + 1);
3363 if (ibp[1] == '*') {
3364 if (put_out_comments) {
3365 *obp++ = '/';
3366 *obp++ = '*';
3367 } else if (! traditional) {
3368 *obp++ = ' ';
3370 for (ibp += 2; ibp < limit; ibp++) {
3371 /* We need not worry about newline-marks,
3372 since they are never found in comments. */
3373 if (ibp[0] == '*') {
3374 if (ibp[1] == '\\' && ibp[2] == '\n')
3375 newline_fix (ibp + 1);
3376 if (ibp[1] == '/') {
3377 ibp += 2;
3378 if (put_out_comments) {
3379 *obp++ = '*';
3380 *obp++ = '/';
3382 break;
3385 else if (*ibp == '\n') {
3386 /* Newline in a file. Count it. */
3387 ++ip->lineno;
3388 ++op->lineno;
3390 else
3392 #ifdef MULTIBYTE_CHARS
3393 int length;
3394 length = local_mblen (ibp, limit - ibp);
3395 if (length > 1)
3397 if (put_out_comments)
3399 bcopy (ibp, obp, length - 1);
3400 obp += length - 1;
3402 ibp += (length - 1);
3404 #endif
3406 if (put_out_comments)
3407 *obp++ = *ibp;
3409 } else if (ibp[1] == '/' && cplusplus_comments) {
3410 if (put_out_comments) {
3411 *obp++ = '/';
3412 *obp++ = '/';
3413 } else if (! traditional) {
3414 *obp++ = ' ';
3416 for (ibp += 2; ; ibp++)
3418 if (*ibp == '\n')
3419 break;
3420 if (*ibp == '\\' && ibp[1] == '\n')
3422 if (put_out_comments)
3423 *obp++ = *ibp++;
3425 else
3427 #ifdef MULTIBYTE_CHARS
3428 int length;
3429 length = local_mblen (ibp, limit - ibp);
3430 if (length > 1)
3432 if (put_out_comments)
3434 bcopy (ibp, obp, length - 1);
3435 obp += length - 1;
3437 ibp += (length - 1);
3439 #endif
3441 if (put_out_comments)
3442 *obp++ = *ibp;
3444 } else
3445 break;
3447 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3448 ibp += 2;
3449 ++ip->lineno;
3451 else break;
3453 if (*ibp != '(') {
3454 /* It isn't a macro call.
3455 Put back the space that we just skipped. */
3456 ibp = old_ibp;
3457 obp = old_obp;
3458 ip->lineno = old_iln;
3459 op->lineno = old_oln;
3460 /* Exit the for loop. */
3461 break;
3465 /* This is now known to be a macro call.
3466 Discard the macro name from the output,
3467 along with any following whitespace just copied,
3468 but preserve newlines if not outputting marks since this
3469 is more likely to do the right thing with line numbers. */
3470 obp = op->buf + obufp_before_macroname;
3471 if (output_marks)
3472 op->lineno = op_lineno_before_macroname;
3473 else {
3474 int newlines = op->lineno - op_lineno_before_macroname;
3475 while (0 < newlines--)
3476 *obp++ = '\n';
3479 /* Prevent accidental token-pasting with a character
3480 before the macro call. */
3481 if (!traditional && obp != op->buf) {
3482 switch (obp[-1]) {
3483 case '!': case '%': case '&': case '*':
3484 case '+': case '-': case '.': case '/':
3485 case ':': case '<': case '=': case '>':
3486 case '^': case '|':
3487 /* If we are expanding a macro arg, make a newline marker
3488 to separate the tokens. If we are making real output,
3489 a plain space will do. */
3490 if (output_marks)
3491 *obp++ = '\n';
3492 *obp++ = ' ';
3496 /* Expand the macro, reading arguments as needed,
3497 and push the expansion on the input stack. */
3498 ip->bufp = ibp;
3499 op->bufp = obp;
3500 macroexpand (hp, op);
3502 /* Reexamine input stack, since macroexpand has pushed
3503 a new level on it. */
3504 obp = op->bufp;
3505 RECACHE;
3506 break;
3508 hashcollision:
3510 } /* End hash-table-search loop */
3512 ident_length = hash = 0; /* Stop collecting identifier */
3513 redo_char = 0;
3514 concatenated = 0;
3515 } /* End if (ident_length > 0) */
3516 } /* End switch */
3517 } /* End per-char loop */
3519 /* Come here to return -- but first give an error message
3520 if there was an unterminated successful conditional. */
3521 ending:
3522 if (if_stack != ip->if_stack)
3524 char *str;
3526 switch (if_stack->type)
3528 case T_IF:
3529 str = "if";
3530 break;
3531 case T_IFDEF:
3532 str = "ifdef";
3533 break;
3534 case T_IFNDEF:
3535 str = "ifndef";
3536 break;
3537 case T_ELSE:
3538 str = "else";
3539 break;
3540 case T_ELIF:
3541 str = "elif";
3542 break;
3543 default:
3544 abort ();
3547 error_with_line (line_for_error (if_stack->lineno),
3548 "unterminated `#%s' conditional", str);
3550 if_stack = ip->if_stack;
3554 * Rescan a string into a temporary buffer and return the result
3555 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3557 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3558 * and insert such markers when appropriate. See `rescan' for details.
3559 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3560 * before substitution; it is 0 for other uses.
3562 static FILE_BUF
3563 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3564 U_CHAR *buf, *limit;
3565 int output_marks, assertions;
3567 register FILE_BUF *ip;
3568 FILE_BUF obuf;
3569 int length = limit - buf;
3570 U_CHAR *buf1;
3571 int odepth = indepth;
3572 int save_assertions_flag = assertions_flag;
3574 assertions_flag = assertions;
3576 if (length < 0)
3577 abort ();
3579 /* Set up the input on the input stack. */
3581 buf1 = (U_CHAR *) alloca (length + 1);
3583 register U_CHAR *p1 = buf;
3584 register U_CHAR *p2 = buf1;
3586 while (p1 != limit)
3587 *p2++ = *p1++;
3589 buf1[length] = 0;
3591 /* Set up to receive the output. */
3593 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3594 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3595 obuf.nominal_fname = 0;
3596 obuf.inc = 0;
3597 obuf.dir = 0;
3598 obuf.fname = 0;
3599 obuf.macro = 0;
3600 obuf.if_stack = 0;
3601 obuf.free_ptr = 0;
3602 obuf.system_header_p = 0;
3604 CHECK_DEPTH ({return obuf;});
3606 ++indepth;
3608 ip = &instack[indepth];
3609 ip->fname = 0;
3610 ip->nominal_fname = 0;
3611 ip->nominal_fname_len = 0;
3612 ip->inc = 0;
3613 ip->system_header_p = 0;
3614 ip->macro = 0;
3615 ip->free_ptr = 0;
3616 ip->length = length;
3617 ip->buf = ip->bufp = buf1;
3618 ip->if_stack = if_stack;
3620 ip->lineno = obuf.lineno = 1;
3622 /* Scan the input, create the output. */
3623 rescan (&obuf, output_marks);
3625 /* Pop input stack to original state. */
3626 --indepth;
3628 if (indepth != odepth)
3629 abort ();
3631 /* Record the output. */
3632 obuf.length = obuf.bufp - obuf.buf;
3634 assertions_flag = save_assertions_flag;
3635 return obuf;
3639 * Process a # directive. Expects IP->bufp to point after the '#', as in
3640 * `#define foo bar'. Passes to the directive handler
3641 * (do_define, do_include, etc.): the addresses of the 1st and
3642 * last chars of the directive (starting immediately after the #
3643 * keyword), plus op and the keyword table pointer. If the directive
3644 * contains comments it is copied into a temporary buffer sans comments
3645 * and the temporary buffer is passed to the directive handler instead.
3646 * Likewise for backslash-newlines.
3648 * Returns nonzero if this was a known # directive.
3649 * Otherwise, returns zero, without advancing the input pointer.
3652 static int
3653 handle_directive (ip, op)
3654 FILE_BUF *ip, *op;
3656 register U_CHAR *bp, *cp;
3657 register struct directive *kt;
3658 register int ident_length;
3659 U_CHAR *resume_p;
3661 /* Nonzero means we must copy the entire directive
3662 to get rid of comments or backslash-newlines. */
3663 int copy_directive = 0;
3665 U_CHAR *ident, *after_ident;
3667 bp = ip->bufp;
3669 /* Record where the directive started. do_xifdef needs this. */
3670 directive_start = bp - 1;
3672 ignore_escape_flag = 1;
3674 /* Skip whitespace and \-newline. */
3675 while (1) {
3676 if (is_hor_space[*bp]) {
3677 if (*bp != ' ' && *bp != '\t' && pedantic)
3678 pedwarn_strange_white_space (*bp);
3679 bp++;
3680 } else if (*bp == '/') {
3681 if (bp[1] == '\\' && bp[2] == '\n')
3682 newline_fix (bp + 1);
3683 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3684 break;
3685 ip->bufp = bp + 2;
3686 skip_to_end_of_comment (ip, &ip->lineno, 0);
3687 bp = ip->bufp;
3688 } else if (*bp == '\\' && bp[1] == '\n') {
3689 bp += 2; ip->lineno++;
3690 } else break;
3693 /* Now find end of directive name.
3694 If we encounter a backslash-newline, exchange it with any following
3695 symbol-constituents so that we end up with a contiguous name. */
3697 cp = bp;
3698 while (1) {
3699 if (is_idchar[*cp])
3700 cp++;
3701 else {
3702 if (*cp == '\\' && cp[1] == '\n')
3703 name_newline_fix (cp);
3704 if (is_idchar[*cp])
3705 cp++;
3706 else break;
3709 ident_length = cp - bp;
3710 ident = bp;
3711 after_ident = cp;
3713 /* A line of just `#' becomes blank. */
3715 if (ident_length == 0 && *after_ident == '\n') {
3716 ip->bufp = after_ident;
3717 return 1;
3720 if (ident_length == 0 || !is_idstart[*ident]) {
3721 U_CHAR *p = ident;
3722 while (is_idchar[*p]) {
3723 if (*p < '0' || *p > '9')
3724 break;
3725 p++;
3727 /* Handle # followed by a line number. */
3728 if (p != ident && !is_idchar[*p]) {
3729 static struct directive line_directive_table[] = {
3730 { 4, do_line, "line", T_LINE},
3732 if (pedantic)
3733 pedwarn ("`#' followed by integer");
3734 after_ident = ident;
3735 kt = line_directive_table;
3736 ignore_escape_flag = 0;
3737 goto old_linenum;
3740 /* Avoid error for `###' and similar cases unless -pedantic. */
3741 if (p == ident) {
3742 while (*p == '#' || is_hor_space[*p]) p++;
3743 if (*p == '\n') {
3744 if (pedantic && !lang_asm)
3745 warning ("invalid preprocessing directive");
3746 return 0;
3750 if (!lang_asm)
3751 error ("invalid preprocessing directive name");
3753 return 0;
3757 * Decode the keyword and call the appropriate expansion
3758 * routine, after moving the input pointer up to the next line.
3760 for (kt = directive_table; kt->length > 0; kt++) {
3761 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3762 register U_CHAR *buf;
3763 register U_CHAR *limit;
3764 int unterminated;
3765 int junk;
3766 int *already_output;
3768 /* Nonzero means do not delete comments within the directive.
3769 #define needs this when -traditional. */
3770 int keep_comments;
3772 old_linenum:
3774 limit = ip->buf + ip->length;
3775 unterminated = 0;
3776 already_output = 0;
3777 keep_comments = traditional && kt->type == T_DEFINE;
3778 /* #import is defined only in Objective C, or when on the NeXT. */
3779 if (kt->type == T_IMPORT
3780 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3781 break;
3783 /* Find the end of this directive (first newline not backslashed
3784 and not in a string or comment).
3785 Set COPY_DIRECTIVE if the directive must be copied
3786 (it contains a backslash-newline or a comment). */
3788 buf = bp = after_ident;
3789 while (bp < limit) {
3790 register U_CHAR c = *bp++;
3791 switch (c) {
3792 case '\\':
3793 if (bp < limit) {
3794 if (*bp == '\n') {
3795 ip->lineno++;
3796 copy_directive = 1;
3797 bp++;
3798 } else if (traditional)
3799 bp++;
3801 break;
3803 case '"':
3804 /* "..." is special for #include. */
3805 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3806 while (bp < limit && *bp != '\n') {
3807 if (*bp == '"') {
3808 bp++;
3809 break;
3811 if (*bp == '\\' && bp[1] == '\n') {
3812 ip->lineno++;
3813 copy_directive = 1;
3814 bp++;
3816 bp++;
3818 break;
3820 /* Fall through. */
3821 case '\'':
3822 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3823 /* Don't bother calling the directive if we already got an error
3824 message due to unterminated string. Skip everything and pretend
3825 we called the directive. */
3826 if (unterminated) {
3827 if (traditional) {
3828 /* Traditional preprocessing permits unterminated strings. */
3829 ip->bufp = bp;
3830 goto endloop1;
3832 ip->bufp = bp;
3833 return 1;
3835 break;
3837 /* <...> is special for #include. */
3838 case '<':
3839 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3840 break;
3841 while (bp < limit && *bp != '>' && *bp != '\n') {
3842 if (*bp == '\\' && bp[1] == '\n') {
3843 ip->lineno++;
3844 copy_directive = 1;
3845 bp++;
3847 bp++;
3849 break;
3851 case '/':
3852 if (*bp == '\\' && bp[1] == '\n')
3853 newline_fix (bp);
3854 if (*bp == '*'
3855 || (cplusplus_comments && *bp == '/')) {
3856 U_CHAR *obp = bp - 1;
3857 ip->bufp = bp + 1;
3858 skip_to_end_of_comment (ip, &ip->lineno, 0);
3859 bp = ip->bufp;
3860 /* No need to copy the directive because of a comment at the end;
3861 just don't include the comment in the directive. */
3862 if (!put_out_comments) {
3863 U_CHAR *p;
3864 for (p = bp; *p == ' ' || *p == '\t'; p++)
3865 continue;
3866 if (*p == '\n') {
3867 bp = obp;
3868 goto endloop1;
3871 /* Don't remove the comments if -traditional. */
3872 if (! keep_comments)
3873 copy_directive++;
3875 break;
3877 case '\f':
3878 case '\r':
3879 case '\v':
3880 if (pedantic)
3881 pedwarn_strange_white_space (c);
3882 break;
3884 case '\n':
3885 --bp; /* Point to the newline */
3886 ip->bufp = bp;
3887 goto endloop1;
3890 ip->bufp = bp;
3892 endloop1:
3893 resume_p = ip->bufp;
3894 /* BP is the end of the directive.
3895 RESUME_P is the next interesting data after the directive.
3896 A comment may come between. */
3898 /* If a directive should be copied through, and -C was given,
3899 pass it through before removing comments. */
3900 if (!no_output && put_out_comments
3901 && ((kt->type == T_DEFINE || kt->type == T_UNDEF)
3902 ? dump_macros == dump_definitions
3903 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3904 : kt->type == T_PRAGMA)) {
3905 int len;
3907 /* Output directive name. */
3908 check_expand (op, kt->length + 2);
3909 /* Make sure # is at the start of a line */
3910 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3911 op->lineno++;
3912 *op->bufp++ = '\n';
3914 *op->bufp++ = '#';
3915 bcopy (kt->name, op->bufp, kt->length);
3916 op->bufp += kt->length;
3918 /* Output arguments. */
3919 len = (bp - buf);
3920 check_expand (op, len);
3921 bcopy (buf, (char *) op->bufp, len);
3922 op->bufp += len;
3923 /* Take account of any (escaped) newlines just output. */
3924 while (--len >= 0)
3925 if (buf[len] == '\n')
3926 op->lineno++;
3928 already_output = &junk;
3929 } /* Don't we need a newline or #line? */
3931 if (copy_directive) {
3932 register U_CHAR *xp = buf;
3933 /* Need to copy entire directive into temp buffer before dispatching */
3935 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3936 some slop */
3937 buf = cp;
3939 /* Copy to the new buffer, deleting comments
3940 and backslash-newlines (and whitespace surrounding the latter). */
3942 while (xp < bp) {
3943 register U_CHAR c = *xp++;
3944 *cp++ = c;
3946 switch (c) {
3947 case '\n':
3948 abort (); /* A bare newline should never part of the line. */
3949 break;
3951 /* <...> is special for #include. */
3952 case '<':
3953 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3954 break;
3955 while (xp < bp && c != '>') {
3956 c = *xp++;
3957 if (c == '\\' && xp < bp && *xp == '\n')
3958 xp++;
3959 else
3960 *cp++ = c;
3962 break;
3964 case '\\':
3965 if (*xp == '\n') {
3966 xp++;
3967 cp--;
3968 if (cp != buf && is_hor_space[cp[-1]]) {
3969 while (cp - 1 != buf && is_hor_space[cp[-2]])
3970 cp--;
3971 SKIP_WHITE_SPACE (xp);
3972 } else if (is_hor_space[*xp]) {
3973 *cp++ = *xp++;
3974 SKIP_WHITE_SPACE (xp);
3976 } else if (traditional && xp < bp) {
3977 *cp++ = *xp++;
3979 break;
3981 case '\'':
3982 case '\"':
3984 int backslash_newlines_p;
3986 register U_CHAR *bp1
3987 = skip_quoted_string (xp - 1, bp, ip->lineno,
3988 NULL_PTR, &backslash_newlines_p,
3989 NULL_PTR);
3990 if (backslash_newlines_p)
3991 while (xp != bp1)
3993 /* With something like:
3995 #define X "a\
3998 we should still remove the backslash-newline
3999 pair as part of phase two. */
4000 if (xp[0] == '\\' && xp[1] == '\n')
4001 xp += 2;
4002 else
4003 *cp++ = *xp++;
4005 else
4006 /* This is the same as the loop above, but taking
4007 advantage of the fact that we know there are no
4008 backslash-newline pairs. */
4009 while (xp != bp1)
4010 *cp++ = *xp++;
4012 break;
4014 case '/':
4015 if (*xp == '*'
4016 || (cplusplus_comments && *xp == '/')) {
4017 ip->bufp = xp + 1;
4018 /* If we already copied the directive through,
4019 already_output != 0 prevents outputting comment now. */
4020 skip_to_end_of_comment (ip, already_output, 0);
4021 if (keep_comments)
4022 while (xp != ip->bufp)
4023 *cp++ = *xp++;
4024 /* Delete or replace the slash. */
4025 else if (traditional)
4026 cp--;
4027 else
4028 cp[-1] = ' ';
4029 xp = ip->bufp;
4034 /* Null-terminate the copy. */
4036 *cp = 0;
4037 } else
4038 cp = bp;
4040 ip->bufp = resume_p;
4042 /* Some directives should be written out for cc1 to process,
4043 just as if they were not defined. And sometimes we're copying
4044 directives through. */
4046 if (!no_output && already_output == 0
4047 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
4048 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4049 : kt->type == T_PRAGMA)) {
4050 int len;
4052 /* Output directive name. */
4053 check_expand (op, kt->length + 1);
4054 *op->bufp++ = '#';
4055 bcopy (kt->name, (char *) op->bufp, kt->length);
4056 op->bufp += kt->length;
4058 if (kt->type == T_DEFINE && dump_macros == dump_names) {
4059 /* Output `#define name' only. */
4060 U_CHAR *xp = buf;
4061 U_CHAR *yp;
4062 SKIP_WHITE_SPACE (xp);
4063 yp = xp;
4064 while (is_idchar[*xp]) xp++;
4065 len = (xp - yp);
4066 check_expand (op, len + 1);
4067 *op->bufp++ = ' ';
4068 bcopy (yp, (char *) op->bufp, len);
4069 } else {
4070 /* Output entire directive. */
4071 len = (cp - buf);
4072 check_expand (op, len);
4073 bcopy (buf, (char *) op->bufp, len);
4075 op->bufp += len;
4076 } /* Don't we need a newline or #line? */
4078 /* Call the appropriate directive handler. buf now points to
4079 either the appropriate place in the input buffer, or to
4080 the temp buffer if it was necessary to make one. cp
4081 points to the first char after the contents of the (possibly
4082 copied) directive, in either case. */
4083 (*kt->func) (buf, cp, op, kt);
4084 check_expand (op, ip->length - (ip->bufp - ip->buf));
4086 return 1;
4090 /* It is deliberate that we don't warn about undefined directives.
4091 That is the responsibility of cc1. */
4092 return 0;
4095 static struct tm *
4096 timestamp ()
4098 static struct tm *timebuf;
4099 if (!timebuf) {
4100 time_t t = time ((time_t *) 0);
4101 timebuf = localtime (&t);
4103 return timebuf;
4106 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4107 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4111 * expand things like __FILE__. Place the expansion into the output
4112 * buffer *without* rescanning.
4115 static void
4116 special_symbol (hp, op)
4117 HASHNODE *hp;
4118 FILE_BUF *op;
4120 char *buf;
4121 int i, len;
4122 int true_indepth;
4123 FILE_BUF *ip = NULL;
4124 struct tm *timebuf;
4126 int paren = 0; /* For special `defined' keyword */
4128 if (pcp_outfile && pcp_inside_if
4129 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4130 error ("Predefined macro `%s' used inside `#if' during precompilation",
4131 hp->name);
4133 for (i = indepth; i >= 0; i--)
4134 if (instack[i].fname != NULL) {
4135 ip = &instack[i];
4136 break;
4138 if (ip == NULL) {
4139 error ("cccp error: not in any file?!");
4140 return; /* the show must go on */
4143 switch (hp->type) {
4144 case T_FILE:
4145 case T_BASE_FILE:
4147 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4148 char *string = p->nominal_fname;
4150 if (string)
4152 size_t string_len = p->nominal_fname_len;
4153 buf = (char *) alloca (3 + 4 * string_len);
4154 quote_string (buf, string, string_len);
4156 else
4157 buf = "\"\"";
4159 break;
4162 case T_INCLUDE_LEVEL:
4163 true_indepth = 0;
4164 for (i = indepth; i >= 0; i--)
4165 if (instack[i].fname != NULL)
4166 true_indepth++;
4168 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4169 sprintf (buf, "%d", true_indepth - 1);
4170 break;
4172 case T_VERSION:
4173 buf = (char *) alloca (3 + strlen (version_string));
4174 sprintf (buf, "\"%s\"", version_string);
4175 break;
4177 #ifndef NO_BUILTIN_SIZE_TYPE
4178 case T_SIZE_TYPE:
4179 buf = SIZE_TYPE;
4180 break;
4181 #endif
4183 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4184 case T_PTRDIFF_TYPE:
4185 buf = PTRDIFF_TYPE;
4186 break;
4187 #endif
4189 case T_WCHAR_TYPE:
4190 buf = wchar_type;
4191 break;
4193 case T_USER_LABEL_PREFIX_TYPE:
4194 buf = user_label_prefix;
4195 break;
4197 case T_REGISTER_PREFIX_TYPE:
4198 buf = REGISTER_PREFIX;
4199 break;
4201 case T_IMMEDIATE_PREFIX_TYPE:
4202 buf = IMMEDIATE_PREFIX;
4203 break;
4205 case T_CONST:
4206 buf = hp->value.cpval;
4207 #ifdef STDC_0_IN_SYSTEM_HEADERS
4208 if (ip->system_header_p
4209 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4210 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4211 buf = "0";
4212 #endif
4213 if (pcp_inside_if && pcp_outfile)
4214 /* Output a precondition for this macro use */
4215 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4216 break;
4218 case T_SPECLINE:
4219 buf = (char *) alloca (10);
4220 sprintf (buf, "%d", ip->lineno);
4221 break;
4223 case T_DATE:
4224 case T_TIME:
4225 buf = (char *) alloca (20);
4226 timebuf = timestamp ();
4227 if (hp->type == T_DATE)
4228 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4229 timebuf->tm_mday, timebuf->tm_year + 1900);
4230 else
4231 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4232 timebuf->tm_sec);
4233 break;
4235 case T_SPEC_DEFINED:
4236 buf = " 0 "; /* Assume symbol is not defined */
4237 ip = &instack[indepth];
4238 SKIP_WHITE_SPACE (ip->bufp);
4239 if (*ip->bufp == '(') {
4240 paren++;
4241 ip->bufp++; /* Skip over the paren */
4242 SKIP_WHITE_SPACE (ip->bufp);
4245 if (!is_idstart[*ip->bufp])
4246 goto oops;
4247 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4248 goto oops;
4249 if ((hp = lookup (ip->bufp, -1, -1))) {
4250 if (pcp_outfile && pcp_inside_if
4251 && (hp->type == T_CONST
4252 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4253 /* Output a precondition for this macro use. */
4254 fprintf (pcp_outfile, "#define %s\n", hp->name);
4255 buf = " 1 ";
4257 else
4258 if (pcp_outfile && pcp_inside_if) {
4259 /* Output a precondition for this macro use */
4260 U_CHAR *cp = ip->bufp;
4261 fprintf (pcp_outfile, "#undef ");
4262 while (is_idchar[*cp]) /* Ick! */
4263 fputc (*cp++, pcp_outfile);
4264 putc ('\n', pcp_outfile);
4266 while (is_idchar[*ip->bufp])
4267 ++ip->bufp;
4268 SKIP_WHITE_SPACE (ip->bufp);
4269 if (paren) {
4270 if (*ip->bufp != ')')
4271 goto oops;
4272 ++ip->bufp;
4274 break;
4276 oops:
4278 error ("`defined' without an identifier");
4279 break;
4281 default:
4282 error ("cccp error: invalid special hash type"); /* time for gdb */
4283 abort ();
4285 len = strlen (buf);
4286 check_expand (op, len);
4287 bcopy (buf, (char *) op->bufp, len);
4288 op->bufp += len;
4290 return;
4294 /* Routines to handle #directives */
4296 /* Handle #include and #import.
4297 This function expects to see "fname" or <fname> on the input. */
4299 static int
4300 do_include (buf, limit, op, keyword)
4301 U_CHAR *buf, *limit;
4302 FILE_BUF *op;
4303 struct directive *keyword;
4305 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4306 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4307 static int import_warning = 0;
4308 char *fname; /* Dynamically allocated fname buffer */
4309 char *pcftry;
4310 char *pcfname;
4311 char *fbeg, *fend; /* Beginning and end of fname */
4312 U_CHAR *fin;
4314 struct file_name_list *search_start = include; /* Chain of dirs to search */
4315 struct file_name_list *dsp; /* First in chain, if #include "..." */
4316 struct file_name_list *searchptr = 0;
4317 size_t flen;
4319 int f = -3; /* file number */
4320 struct include_file *inc = 0;
4322 int retried = 0; /* Have already tried macro
4323 expanding the include line*/
4324 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4325 #ifdef VMS
4326 int vaxc_include = 0; /* 1 for token without punctuation */
4327 #endif
4328 int pcf = -1;
4329 char *pcfbuf;
4330 char *pcfbuflimit;
4331 int pcfnum;
4333 if (pedantic && !instack[indepth].system_header_p)
4335 if (importing)
4336 pedwarn ("ANSI C does not allow `#import'");
4337 if (skip_dirs)
4338 pedwarn ("ANSI C does not allow `#include_next'");
4341 if (importing && warn_import && !inhibit_warnings
4342 && !instack[indepth].system_header_p && !import_warning) {
4343 import_warning = 1;
4344 warning ("using `#import' is not recommended");
4345 notice ("The fact that a certain header file need not be processed more than once\n\
4346 should be indicated in the header file, not where it is used.\n\
4347 The best way to do this is with a conditional of this form:\n\
4349 #ifndef _FOO_H_INCLUDED\n\
4350 #define _FOO_H_INCLUDED\n\
4351 ... <real contents of file> ...\n\
4352 #endif /* Not _FOO_H_INCLUDED */\n\
4354 Then users can use `#include' any number of times.\n\
4355 GNU C automatically avoids processing the file more than once\n\
4356 when it is equipped with such a conditional.\n");
4359 get_filename:
4361 fin = buf;
4362 SKIP_WHITE_SPACE (fin);
4363 /* Discard trailing whitespace so we can easily see
4364 if we have parsed all the significant chars we were given. */
4365 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4366 fbeg = fend = (char *) alloca (limit - fin);
4368 switch (*fin++) {
4369 case '\"':
4371 FILE_BUF *fp;
4372 /* Copy the operand text, concatenating the strings. */
4374 for (;;) {
4375 for (;;) {
4376 if (fin == limit)
4377 goto invalid_include_file_name;
4378 *fend = *fin++;
4379 if (*fend == '"')
4380 break;
4381 fend++;
4383 if (fin == limit)
4384 break;
4385 /* If not at the end, there had better be another string. */
4386 /* Skip just horiz space, and don't go past limit. */
4387 while (fin != limit && is_hor_space[*fin]) fin++;
4388 if (fin != limit && *fin == '\"')
4389 fin++;
4390 else
4391 goto fail;
4395 /* We have "filename". Figure out directory this source
4396 file is coming from and put it on the front of the list. */
4398 /* If -I- was specified, don't search current dir, only spec'd ones. */
4399 if (ignore_srcdir) break;
4401 for (fp = &instack[indepth]; fp >= instack; fp--)
4403 int n;
4404 char *nam;
4406 if ((nam = fp->nominal_fname) != NULL) {
4407 /* Found a named file. Figure out dir of the file,
4408 and put it in front of the search list. */
4409 dsp = ((struct file_name_list *)
4410 alloca (sizeof (struct file_name_list)
4411 + fp->nominal_fname_len));
4412 strcpy (dsp->fname, nam);
4413 simplify_filename (dsp->fname);
4414 nam = base_name (dsp->fname);
4415 *nam = 0;
4416 #ifdef VMS
4417 /* for hack_vms_include_specification(), a local
4418 dir specification must start with "./" on VMS. */
4419 if (nam == dsp->fname)
4421 *nam++ = '.';
4422 *nam++ = '/';
4423 *nam = 0;
4425 #endif
4426 /* But for efficiency's sake, do not insert the dir
4427 if it matches the search list's first dir. */
4428 dsp->next = search_start;
4429 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4430 search_start = dsp;
4431 n = nam - dsp->fname;
4432 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4433 max_include_len = n + INCLUDE_LEN_FUDGE;
4435 dsp[0].got_name_map = 0;
4436 break;
4439 break;
4442 case '<':
4443 while (fin != limit && *fin != '>')
4444 *fend++ = *fin++;
4445 if (*fin == '>' && fin + 1 == limit) {
4446 angle_brackets = 1;
4447 /* If -I-, start with the first -I dir after the -I-. */
4448 search_start = first_bracket_include;
4449 break;
4451 goto fail;
4453 default:
4454 #ifdef VMS
4456 * Support '#include xyz' like VAX-C to allow for easy use of all the
4457 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4458 * code from case '<' is repeated here) and generates a warning.
4459 * (Note: macro expansion of `xyz' takes precedence.)
4461 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4462 the pre-decrement outside of the macro. */
4463 if (retried && (--fin, ISALPHA(*(U_CHAR *) (fin)))) {
4464 while (fin != limit && (!ISSPACE(*fin)))
4465 *fend++ = *fin++;
4466 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4467 vaxc_include = 1;
4468 if (fin == limit) {
4469 angle_brackets = 1;
4470 /* If -I-, start with the first -I dir after the -I-. */
4471 search_start = first_bracket_include;
4472 break;
4475 #endif
4477 fail:
4478 if (! retried) {
4479 /* Expand buffer and then remove any newline markers.
4480 We can't just tell expand_to_temp_buffer to omit the markers,
4481 since it would put extra spaces in include file names. */
4482 FILE_BUF trybuf;
4483 U_CHAR *src;
4484 int errors_before_expansion = errors;
4485 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4486 if (errors != errors_before_expansion) {
4487 free (trybuf.buf);
4488 goto invalid_include_file_name;
4490 src = trybuf.buf;
4491 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4492 limit = buf;
4493 while (src != trybuf.bufp) {
4494 switch ((*limit++ = *src++)) {
4495 case '\n':
4496 limit--;
4497 src++;
4498 break;
4500 case '\'':
4501 case '\"':
4503 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4504 NULL_PTR, NULL_PTR, NULL_PTR);
4505 while (src != src1)
4506 *limit++ = *src++;
4508 break;
4511 *limit = 0;
4512 free (trybuf.buf);
4513 retried = 1;
4514 goto get_filename;
4517 invalid_include_file_name:
4518 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4519 return 0;
4522 /* For #include_next, skip in the search path
4523 past the dir in which the containing file was found. */
4524 if (skip_dirs) {
4525 FILE_BUF *fp;
4526 for (fp = &instack[indepth]; fp >= instack; fp--)
4527 if (fp->fname != NULL) {
4528 /* fp->dir is null if the containing file was specified
4529 with an absolute file name. In that case, don't skip anything. */
4530 if (fp->dir)
4531 search_start = fp->dir->next;
4532 break;
4536 *fend = 0;
4537 flen = simplify_filename (fbeg);
4539 if (flen == 0)
4541 error ("empty file name in `#%s'", keyword->name);
4542 return 0;
4545 /* Allocate this permanently, because it gets stored in the definitions
4546 of macros. */
4547 fname = xmalloc (max_include_len + flen + 1);
4548 /* + 1 above for terminating null. */
4550 system_include_depth += angle_brackets;
4552 /* If specified file name is absolute, just open it. */
4554 if (absolute_filename (fbeg)) {
4555 strcpy (fname, fbeg);
4556 f = open_include_file (fname, NULL_PTR, importing, &inc);
4557 } else {
4559 struct bypass_dir {
4560 struct bypass_dir *next;
4561 char *fname;
4562 struct file_name_list *searchptr;
4563 } **bypass_slot = 0;
4565 /* Search directory path, trying to open the file.
4566 Copy each filename tried into FNAME. */
4568 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4570 if (searchptr == first_bracket_include) {
4571 /* Go to bypass directory if we know we've seen this file before. */
4572 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4573 struct bypass_dir *p;
4574 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4575 INCLUDE_HASHSIZE)];
4576 for (p = *bypass_slot; p; p = p->next)
4577 if (!strcmp (fbeg, p->fname)) {
4578 searchptr = p->searchptr;
4579 bypass_slot = 0;
4580 break;
4584 #ifdef VMS
4585 /* Change this 1/2 Unix 1/2 VMS file specification into a
4586 full VMS file specification */
4587 if (searchptr->fname[0])
4589 strcpy (fname, searchptr->fname);
4590 if (fname[strlen (fname) - 1] == ':')
4592 char *slashp;
4593 slashp = strchr (fbeg, '/');
4595 /* start at root-dir of logical device if no path given. */
4596 if (slashp == 0)
4597 strcat (fname, "[000000]");
4599 strcat (fname, fbeg);
4601 /* Fix up the filename */
4602 hack_vms_include_specification (fname, vaxc_include);
4604 else
4606 /* This is a normal VMS filespec, so use it unchanged. */
4607 strcpy (fname, fbeg);
4608 /* if it's '#include filename', add the missing .h */
4609 if (vaxc_include && index(fname,'.')==NULL)
4610 strcat (fname, ".h");
4612 #else
4613 strcpy (fname, searchptr->fname);
4614 strcat (fname, fbeg);
4615 #endif /* VMS */
4616 f = open_include_file (fname, searchptr, importing, &inc);
4617 if (f != -1) {
4618 if (bypass_slot && searchptr != first_bracket_include) {
4619 /* This is the first time we found this include file,
4620 and we found it after first_bracket_include.
4621 Record its location so that we can bypass to here next time. */
4622 struct bypass_dir *p
4623 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4624 p->next = *bypass_slot;
4625 p->fname = fname + strlen (searchptr->fname);
4626 p->searchptr = searchptr;
4627 *bypass_slot = p;
4629 break;
4631 #ifdef VMS
4632 /* Our VMS hacks can produce invalid filespecs, so don't worry
4633 about errors other than EACCES. */
4634 if (errno == EACCES)
4635 break;
4636 #else
4637 if (errno != ENOENT && errno != ENOTDIR)
4638 break;
4639 #endif
4644 if (f < 0) {
4646 if (f == -2) {
4647 /* The file was already included. */
4649 /* If generating dependencies and -MG was specified, we assume missing
4650 files are leaf files, living in the same directory as the source file
4651 or other similar place; these missing files may be generated from
4652 other files and may not exist yet (eg: y.tab.h). */
4653 } else if (print_deps_missing_files
4654 && (system_include_depth != 0) < print_deps)
4656 /* If it was requested as a system header file,
4657 then assume it belongs in the first place to look for such. */
4658 if (angle_brackets)
4660 if (search_start) {
4661 char *p = (char *) alloca (strlen (search_start->fname)
4662 + strlen (fbeg) + 1);
4663 strcpy (p, search_start->fname);
4664 strcat (p, fbeg);
4665 deps_output (p, ' ');
4668 else
4670 /* Otherwise, omit the directory, as if the file existed
4671 in the directory with the source. */
4672 deps_output (fbeg, ' ');
4675 /* If -M was specified, and this header file won't be added to the
4676 dependency list, then don't count this as an error, because we can
4677 still produce correct output. Otherwise, we can't produce correct
4678 output, because there may be dependencies we need inside the missing
4679 file, and we don't know what directory this missing file exists in. */
4680 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4681 warning ("No include path in which to find %s", fbeg);
4682 else if (f != -3)
4683 error_from_errno (fbeg);
4684 else
4685 error ("No include path in which to find %s", fbeg);
4687 } else {
4689 /* Actually process the file. */
4691 pcftry = (char *) alloca (strlen (fname) + 30);
4692 pcfbuf = 0;
4693 pcfnum = 0;
4695 if (!no_precomp)
4697 do {
4698 sprintf (pcftry, "%s%d", fname, pcfnum++);
4700 pcf = open (pcftry, O_RDONLY, 0666);
4701 if (pcf != -1)
4703 struct stat s;
4705 if (fstat (pcf, &s) != 0)
4706 pfatal_with_name (pcftry);
4707 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4708 || inc->st.st_dev != s.st_dev)
4710 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4711 /* Don't need it any more. */
4712 close (pcf);
4714 else
4716 /* Don't need it at all. */
4717 close (pcf);
4718 break;
4721 } while (pcf != -1 && !pcfbuf);
4724 /* Actually process the file */
4725 if (pcfbuf) {
4726 pcfname = xmalloc (strlen (pcftry) + 1);
4727 strcpy (pcfname, pcftry);
4728 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) fname, op);
4730 else
4731 finclude (f, inc, op, is_system_include (fname), searchptr);
4734 system_include_depth -= angle_brackets;
4736 return 0;
4739 /* Return nonzero if the given FILENAME is an absolute pathname which
4740 designates a file within one of the known "system" include file
4741 directories. We assume here that if the given FILENAME looks like
4742 it is the name of a file which resides either directly in a "system"
4743 include file directory, or within any subdirectory thereof, then the
4744 given file must be a "system" include file. This function tells us
4745 if we should suppress pedantic errors/warnings for the given FILENAME.
4747 The value is 2 if the file is a C-language system header file
4748 for which C++ should (on most systems) assume `extern "C"'. */
4750 static int
4751 is_system_include (filename)
4752 register char *filename;
4754 struct file_name_list *searchptr;
4756 for (searchptr = first_system_include; searchptr;
4757 searchptr = searchptr->next)
4758 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4759 return searchptr->c_system_include_path + 1;
4760 return 0;
4763 /* Yield the non-directory suffix of a file name. */
4765 static char *
4766 base_name (fname)
4767 char *fname;
4769 char *s = fname;
4770 char *p;
4771 #if defined (__MSDOS__) || defined (_WIN32)
4772 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4773 #endif
4774 #ifdef VMS
4775 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4776 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4777 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4778 if (s != fname)
4779 return s;
4780 #endif
4781 if ((p = rindex (s, '/'))) s = p + 1;
4782 #ifdef DIR_SEPARATOR
4783 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4784 #endif
4785 return s;
4788 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4790 static int
4791 absolute_filename (filename)
4792 char *filename;
4794 #if defined (__MSDOS__) \
4795 || (defined (_WIN32) && !defined (__CYGWIN__) && !defined (_UWIN))
4796 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4797 #endif
4798 #if defined (__CYGWIN__)
4799 /* At present, any path that begins with a drive spec is absolute. */
4800 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4801 #endif
4802 #ifdef VMS
4803 if (index (filename, ':') != 0) return 1;
4804 #endif
4805 if (filename[0] == '/') return 1;
4806 #ifdef DIR_SEPARATOR
4807 if (filename[0] == DIR_SEPARATOR) return 1;
4808 #endif
4809 return 0;
4812 /* Returns whether or not a given character is a directory separator.
4813 Used by simplify_filename. */
4814 static inline
4816 is_dir_separator(ch)
4817 char ch;
4819 return (ch == DIR_SEPARATOR)
4820 #if defined (DIR_SEPARATOR_2)
4821 || (ch == DIR_SEPARATOR_2)
4822 #endif
4826 /* Remove unnecessary characters from FILENAME in place,
4827 to avoid unnecessary filename aliasing.
4828 Return the length of the resulting string.
4830 Do only the simplifications allowed by Posix.
4831 It is OK to miss simplifications on non-Posix hosts,
4832 since this merely leads to suboptimal results. */
4834 static size_t
4835 simplify_filename (filename)
4836 char *filename;
4838 register char *from = filename;
4839 register char *to = filename;
4840 char *to0;
4842 /* Remove redundant initial /s. */
4843 if (is_dir_separator (*from))
4845 *to++ = DIR_SEPARATOR;
4846 if (is_dir_separator (*++from))
4848 if (is_dir_separator (*++from))
4850 /* 3 or more initial /s are equivalent to 1 /. */
4851 while (is_dir_separator (*++from))
4852 continue;
4854 else
4856 /* On some hosts // differs from /; Posix allows this. */
4857 *to++ = DIR_SEPARATOR;
4862 to0 = to;
4864 for (;;)
4866 #ifndef VMS
4867 if (from[0] == '.' && from[1] == '/')
4868 from += 2;
4869 else
4870 #endif
4872 /* Copy this component and trailing DIR_SEPARATOR, if any. */
4873 while (!is_dir_separator (*to++ = *from++))
4875 if (!to[-1])
4877 /* Trim . component at end of nonempty name. */
4878 to -= filename <= to - 3 && to[-3] == DIR_SEPARATOR && to[-2] == '.';
4880 /* Trim unnecessary trailing /s. */
4881 while (to0 < --to && to[-1] == DIR_SEPARATOR)
4882 continue;
4884 *to = 0;
4885 return to - filename;
4888 #if defined(DIR_SEPARATOR_2)
4889 /* Simplify to one directory separator. */
4890 to[-1] = DIR_SEPARATOR;
4891 #endif
4894 /* Skip /s after a /. */
4895 while (is_dir_separator (*from))
4896 from++;
4900 /* The file_name_map structure holds a mapping of file names for a
4901 particular directory. This mapping is read from the file named
4902 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4903 map filenames on a file system with severe filename restrictions,
4904 such as DOS. The format of the file name map file is just a series
4905 of lines with two tokens on each line. The first token is the name
4906 to map, and the second token is the actual name to use. */
4908 struct file_name_map
4910 struct file_name_map *map_next;
4911 char *map_from;
4912 char *map_to;
4915 #define FILE_NAME_MAP_FILE "header.gcc"
4917 /* Read a space delimited string of unlimited length from a stdio
4918 file. */
4920 static char *
4921 read_filename_string (ch, f)
4922 int ch;
4923 FILE *f;
4925 char *alloc, *set;
4926 int len;
4928 len = 20;
4929 set = alloc = xmalloc (len + 1);
4930 if (! is_space[ch])
4932 *set++ = ch;
4933 while ((ch = getc (f)) != EOF && ! is_space[ch])
4935 if (set - alloc == len)
4937 len *= 2;
4938 alloc = xrealloc (alloc, len + 1);
4939 set = alloc + len / 2;
4941 *set++ = ch;
4944 *set = '\0';
4945 ungetc (ch, f);
4946 return alloc;
4949 /* Read the file name map file for DIRNAME.
4950 If DIRNAME is empty, read the map file for the working directory;
4951 otherwise DIRNAME must end in '/'. */
4953 static struct file_name_map *
4954 read_name_map (dirname)
4955 char *dirname;
4957 /* This structure holds a linked list of file name maps, one per
4958 directory. */
4959 struct file_name_map_list
4961 struct file_name_map_list *map_list_next;
4962 char *map_list_name;
4963 struct file_name_map *map_list_map;
4965 static struct file_name_map_list *map_list;
4966 register struct file_name_map_list *map_list_ptr;
4967 char *name;
4968 FILE *f;
4969 size_t dirlen;
4971 for (map_list_ptr = map_list; map_list_ptr;
4972 map_list_ptr = map_list_ptr->map_list_next)
4973 if (! strcmp (map_list_ptr->map_list_name, dirname))
4974 return map_list_ptr->map_list_map;
4976 map_list_ptr = ((struct file_name_map_list *)
4977 xmalloc (sizeof (struct file_name_map_list)));
4978 map_list_ptr->map_list_name = xstrdup (dirname);
4979 map_list_ptr->map_list_map = NULL;
4981 dirlen = strlen (dirname);
4982 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4983 strcpy (name, dirname);
4984 strcat (name, FILE_NAME_MAP_FILE);
4985 f = fopen (name, "r");
4986 if (!f)
4987 map_list_ptr->map_list_map = NULL;
4988 else
4990 int ch;
4992 while ((ch = getc (f)) != EOF)
4994 char *from, *to;
4995 struct file_name_map *ptr;
4996 size_t tolen;
4998 if (is_space[ch])
4999 continue;
5000 from = read_filename_string (ch, f);
5001 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5003 to = read_filename_string (ch, f);
5005 simplify_filename (from);
5006 tolen = simplify_filename (to);
5008 ptr = ((struct file_name_map *)
5009 xmalloc (sizeof (struct file_name_map)));
5010 ptr->map_from = from;
5012 /* Make the real filename absolute. */
5013 if (absolute_filename (to))
5014 ptr->map_to = to;
5015 else
5017 ptr->map_to = xmalloc (dirlen + tolen + 1);
5018 strcpy (ptr->map_to, dirname);
5019 strcat (ptr->map_to, to);
5020 free (to);
5023 ptr->map_next = map_list_ptr->map_list_map;
5024 map_list_ptr->map_list_map = ptr;
5026 while ((ch = getc (f)) != '\n')
5027 if (ch == EOF)
5028 break;
5030 fclose (f);
5033 map_list_ptr->map_list_next = map_list;
5034 map_list = map_list_ptr;
5036 return map_list_ptr->map_list_map;
5039 /* Try to open include file FILENAME. SEARCHPTR is the directory
5040 being tried from the include file search path.
5041 IMPORTING is "" if we are importing, null otherwise.
5042 Return -2 if found, either a matching name or a matching inode.
5043 Otherwise, open the file and return a file descriptor if successful
5044 or -1 if unsuccessful.
5045 Unless unsuccessful, put a descriptor of the included file into *PINC.
5046 This function maps filenames on file systems based on information read by
5047 read_name_map. */
5049 static int
5050 open_include_file (filename, searchptr, importing, pinc)
5051 char *filename;
5052 struct file_name_list *searchptr;
5053 U_CHAR *importing;
5054 struct include_file **pinc;
5056 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
5057 int fd = -2;
5059 /* Look up FNAME in include_hashtab. */
5060 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
5061 strlen (fname),
5062 INCLUDE_HASHSIZE)];
5063 struct include_file *inc, *head = *phead;
5064 for (inc = head; inc; inc = inc->next)
5065 if (!strcmp (fname, inc->fname))
5066 break;
5068 if (!inc
5069 || ! inc->control_macro
5070 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
5072 fd = open (fname, O_RDONLY, 0);
5074 if (fd < 0)
5076 #ifdef VMS
5077 /* if #include <dir/file> fails, try again with hacked spec. */
5078 if (!hack_vms_include_specification (fname, 0))
5079 return fd;
5080 fd = open (fname, O_RDONLY, 0);
5081 if (fd < 0)
5082 #endif
5083 return fd;
5086 if (!inc) {
5087 /* FNAME was not in include_hashtab; insert a new entry. */
5088 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
5089 inc->next = head;
5090 inc->fname = fname;
5091 inc->control_macro = 0;
5092 inc->deps_output = 0;
5093 if (fstat (fd, &inc->st) != 0)
5094 pfatal_with_name (fname);
5095 *phead = inc;
5097 /* Look for another file with the same inode and device. */
5098 if (lookup_ino_include (inc)
5099 && inc->control_macro
5100 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
5101 close (fd);
5102 fd = -2;
5106 /* For -M, add this file to the dependencies. */
5107 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
5108 inc->deps_output = 1;
5109 deps_output (fname, ' ');
5112 /* Handle -H option. */
5113 if (print_include_names)
5114 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5117 if (importing)
5118 inc->control_macro = importing;
5120 *pinc = inc;
5121 return fd;
5124 /* Return the remapped name of the include file FILENAME.
5125 SEARCHPTR is the directory being tried from the include file path. */
5127 static char *
5128 remap_include_file (filename, searchptr)
5129 char *filename;
5130 struct file_name_list *searchptr;
5132 register struct file_name_map *map;
5133 register char *from;
5135 if (searchptr)
5137 if (! searchptr->got_name_map)
5139 searchptr->name_map = read_name_map (searchptr->fname);
5140 searchptr->got_name_map = 1;
5143 /* Check the mapping for the directory we are using. */
5144 from = filename + strlen (searchptr->fname);
5145 for (map = searchptr->name_map; map; map = map->map_next)
5146 if (! strcmp (map->map_from, from))
5147 return map->map_to;
5150 from = base_name (filename);
5152 if (from != filename || !searchptr)
5154 /* Try to find a mapping file for the particular directory we are
5155 looking in. Thus #include <sys/types.h> will look up sys/types.h
5156 in /usr/include/header.gcc and look up types.h in
5157 /usr/include/sys/header.gcc. */
5159 char *dir = (char *) alloca (from - filename + 1);
5160 bcopy (filename, dir, from - filename);
5161 dir[from - filename] = '\0';
5163 for (map = read_name_map (dir); map; map = map->map_next)
5164 if (! strcmp (map->map_from, from))
5165 return map->map_to;
5168 return filename;
5171 /* Insert INC into the include file table, hashed by device and inode number.
5172 If a file with different name but same dev+ino was already in the table,
5173 return 1 and set INC's control macro to the already-known macro. */
5175 static int
5176 lookup_ino_include (inc)
5177 struct include_file *inc;
5179 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5180 % INCLUDE_HASHSIZE);
5181 struct include_file *i = include_ino_hashtab[hash];
5182 inc->next_ino = i;
5183 include_ino_hashtab[hash] = inc;
5185 for (; i; i = i->next_ino)
5186 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5187 && inc->st.st_dev == i->st.st_dev) {
5188 inc->control_macro = i->control_macro;
5189 return 1;
5192 return 0;
5195 /* Process file descriptor F, which corresponds to include file INC,
5196 with output to OP.
5197 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5198 "system" include directories (as decided by the `is_system_include'
5199 function above).
5200 DIRPTR is the link in the dir path through which this file was found,
5201 or 0 if the file name was absolute. */
5203 static void
5204 finclude (f, inc, op, system_header_p, dirptr)
5205 int f;
5206 struct include_file *inc;
5207 FILE_BUF *op;
5208 int system_header_p;
5209 struct file_name_list *dirptr;
5211 char *fname = inc->fname;
5212 int i;
5213 FILE_BUF *fp; /* For input stack frame */
5214 int missing_newline = 0;
5216 CHECK_DEPTH (return;);
5218 fp = &instack[indepth + 1];
5219 bzero ((char *) fp, sizeof (FILE_BUF));
5220 fp->nominal_fname = fp->fname = fname;
5221 fp->nominal_fname_len = strlen (fname);
5222 fp->inc = inc;
5223 fp->length = 0;
5224 fp->lineno = 1;
5225 fp->if_stack = if_stack;
5226 fp->system_header_p = system_header_p;
5227 fp->dir = dirptr;
5229 if (S_ISREG (inc->st.st_mode)) {
5230 size_t s = (size_t) inc->st.st_size;
5231 if (s != inc->st.st_size || s + 2 < s)
5232 memory_full ();
5233 fp->buf = (U_CHAR *) xmalloc (s + 2);
5234 fp->bufp = fp->buf;
5236 /* Read the file contents, knowing that s is an upper bound
5237 on the number of bytes we can read. */
5238 fp->length = safe_read (f, (char *) fp->buf, s);
5239 if (fp->length < 0) goto nope;
5241 else if (S_ISDIR (inc->st.st_mode)) {
5242 error ("directory `%s' specified in #include", fname);
5243 close (f);
5244 return;
5245 } else {
5246 /* Cannot count its file size before reading.
5247 First read the entire file into heap and
5248 copy them into buffer on stack. */
5250 int bsize = 2000;
5251 int st_size = 0;
5253 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5255 for (;;) {
5256 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5257 if (i < 0)
5258 goto nope; /* error! */
5259 st_size += i;
5260 if (st_size != bsize)
5261 break; /* End of file */
5262 bsize *= 2;
5263 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5265 fp->bufp = fp->buf;
5266 fp->length = st_size;
5269 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5270 /* Backslash-newline at end is not good enough. */
5271 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5272 fp->buf[fp->length++] = '\n';
5273 missing_newline = 1;
5275 fp->buf[fp->length] = '\0';
5277 /* Close descriptor now, so nesting does not use lots of descriptors. */
5278 close (f);
5280 /* Must do this before calling trigraph_pcp, so that the correct file name
5281 will be printed in warning messages. */
5283 indepth++;
5284 input_file_stack_tick++;
5286 if (!no_trigraphs)
5287 trigraph_pcp (fp);
5289 output_line_directive (fp, op, 0, enter_file);
5290 rescan (op, 0);
5292 if (missing_newline)
5293 fp->lineno--;
5295 if (pedantic && missing_newline)
5296 pedwarn ("file does not end in newline");
5298 indepth--;
5299 input_file_stack_tick++;
5300 output_line_directive (&instack[indepth], op, 0, leave_file);
5301 free (fp->buf);
5302 return;
5304 nope:
5306 perror_with_name (fname);
5307 close (f);
5308 free (fp->buf);
5311 /* Record that inclusion of the include file INC
5312 should be controlled by the macro named MACRO_NAME.
5313 This means that trying to include the file again
5314 will do something if that macro is defined. */
5316 static void
5317 record_control_macro (inc, macro_name)
5318 struct include_file *inc;
5319 U_CHAR *macro_name;
5321 if (!inc->control_macro || inc->control_macro[0])
5322 inc->control_macro = macro_name;
5325 /* Load the specified precompiled header into core, and verify its
5326 preconditions. PCF indicates the file descriptor to read, which must
5327 be a regular file. *ST is its file status.
5328 FNAME indicates the file name of the original header.
5329 *LIMIT will be set to an address one past the end of the file.
5330 If the preconditions of the file are not satisfied, the buffer is
5331 freed and we return 0. If the preconditions are satisfied, return
5332 the address of the buffer following the preconditions. The buffer, in
5333 this case, should never be freed because various pieces of it will
5334 be referred to until all precompiled strings are output at the end of
5335 the run. */
5337 static char *
5338 check_precompiled (pcf, st, fname, limit)
5339 int pcf;
5340 struct stat *st;
5341 char *fname ATTRIBUTE_UNUSED;
5342 char **limit;
5344 int length = 0;
5345 char *buf;
5346 char *cp;
5348 if (pcp_outfile)
5349 return 0;
5351 if (S_ISREG (st->st_mode))
5353 size_t s = (size_t) st->st_size;
5354 if (s != st->st_size || s + 2 < s)
5355 memory_full ();
5356 buf = xmalloc (s + 2);
5357 length = safe_read (pcf, buf, s);
5358 if (length < 0)
5359 goto nope;
5361 else
5362 abort ();
5364 if (length > 0 && buf[length-1] != '\n')
5365 buf[length++] = '\n';
5366 buf[length] = '\0';
5368 *limit = buf + length;
5370 /* File is in core. Check the preconditions. */
5371 if (!check_preconditions (buf))
5372 goto nope;
5373 for (cp = buf; *cp; cp++)
5375 #ifdef DEBUG_PCP
5376 fprintf (stderr, "Using preinclude %s\n", fname);
5377 #endif
5378 return cp + 1;
5380 nope:
5381 #ifdef DEBUG_PCP
5382 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5383 #endif
5384 free (buf);
5385 return 0;
5388 /* PREC (null terminated) points to the preconditions of a
5389 precompiled header. These are a series of #define and #undef
5390 lines which must match the current contents of the hash
5391 table. */
5393 static int
5394 check_preconditions (prec)
5395 char *prec;
5397 MACRODEF mdef;
5398 char *lineend;
5400 while (*prec) {
5401 lineend = index (prec, '\n');
5403 if (*prec++ != '#') {
5404 error ("Bad format encountered while reading precompiled file");
5405 return 0;
5407 if (!strncmp (prec, "define", 6)) {
5408 HASHNODE *hp;
5410 prec += 6;
5411 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5413 if (mdef.defn == 0)
5414 abort ();
5416 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5417 || (hp->type != T_MACRO && hp->type != T_CONST)
5418 || (hp->type == T_MACRO
5419 && !compare_defs (mdef.defn, hp->value.defn)
5420 && (mdef.defn->length != 2
5421 || mdef.defn->expansion[0] != '\n'
5422 || mdef.defn->expansion[1] != ' ')))
5423 return 0;
5424 } else if (!strncmp (prec, "undef", 5)) {
5425 char *name;
5426 int len;
5428 prec += 5;
5429 while (is_hor_space[(U_CHAR) *prec])
5430 prec++;
5431 name = prec;
5432 while (is_idchar[(U_CHAR) *prec])
5433 prec++;
5434 len = prec - name;
5436 if (lookup ((U_CHAR *) name, len, -1))
5437 return 0;
5438 } else {
5439 error ("Bad format encountered while reading precompiled file");
5440 return 0;
5442 prec = lineend + 1;
5444 /* They all passed successfully */
5445 return 1;
5448 /* Process the main body of a precompiled file. BUF points to the
5449 string section of the file, following the preconditions. LIMIT is one
5450 character past the end. NAME is the name of the file being read
5451 in. OP is the main output buffer. */
5453 static void
5454 pcfinclude (buf, name, op)
5455 U_CHAR *buf, *name;
5456 FILE_BUF *op;
5458 FILE_BUF tmpbuf;
5459 int nstrings;
5460 U_CHAR *cp = buf;
5462 /* First in the file comes 4 bytes indicating the number of strings, */
5463 /* in network byte order. (MSB first). */
5464 nstrings = *cp++;
5465 nstrings = (nstrings << 8) | *cp++;
5466 nstrings = (nstrings << 8) | *cp++;
5467 nstrings = (nstrings << 8) | *cp++;
5469 /* Looping over each string... */
5470 while (nstrings--) {
5471 U_CHAR *string_start;
5472 U_CHAR *endofthiskey;
5473 STRINGDEF *str;
5474 int nkeys;
5476 /* Each string starts with a STRINGDEF structure (str), followed */
5477 /* by the text of the string (string_start) */
5479 /* First skip to a longword boundary */
5480 /* ??? Why a 4-byte boundary? On all machines? */
5481 /* NOTE: This works correctly even if size_t
5482 is narrower than a pointer.
5483 Do not try risky measures here to get another type to use!
5484 Do not include stddef.h--it will fail! */
5485 if ((size_t) cp & 3)
5486 cp += 4 - ((size_t) cp & 3);
5488 /* Now get the string. */
5489 str = (STRINGDEF *) (GENERIC_PTR) cp;
5490 string_start = cp += sizeof (STRINGDEF);
5492 for (; *cp; cp++) /* skip the string */
5495 /* We need to macro expand the string here to ensure that the
5496 proper definition environment is in place. If it were only
5497 expanded when we find out it is needed, macros necessary for
5498 its proper expansion might have had their definitions changed. */
5499 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5500 /* Lineno is already set in the precompiled file */
5501 str->contents = tmpbuf.buf;
5502 str->len = tmpbuf.length;
5503 str->writeflag = 0;
5504 str->filename = name;
5505 str->output_mark = outbuf.bufp - outbuf.buf;
5507 str->chain = 0;
5508 *stringlist_tailp = str;
5509 stringlist_tailp = &str->chain;
5511 /* Next comes a fourbyte number indicating the number of keys
5512 for this string. */
5513 nkeys = *cp++;
5514 nkeys = (nkeys << 8) | *cp++;
5515 nkeys = (nkeys << 8) | *cp++;
5516 nkeys = (nkeys << 8) | *cp++;
5518 /* If this number is -1, then the string is mandatory. */
5519 if (nkeys == -1)
5520 str->writeflag = 1;
5521 else
5522 /* Otherwise, for each key, */
5523 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5524 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5525 HASHNODE *hp;
5527 /* It starts with a KEYDEF structure */
5528 cp += sizeof (KEYDEF);
5530 /* Find the end of the key. At the end of this for loop we
5531 advance CP to the start of the next key using this variable. */
5532 endofthiskey = cp + strlen ((char *) cp);
5533 kp->str = str;
5535 /* Expand the key, and enter it into the hash table. */
5536 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5537 tmpbuf.bufp = tmpbuf.buf;
5539 while (is_hor_space[*tmpbuf.bufp])
5540 tmpbuf.bufp++;
5541 if (!is_idstart[*tmpbuf.bufp]
5542 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5543 str->writeflag = 1;
5544 continue;
5547 hp = lookup (tmpbuf.bufp, -1, -1);
5548 if (hp == NULL) {
5549 kp->chain = 0;
5550 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5552 else if (hp->type == T_PCSTRING) {
5553 kp->chain = hp->value.keydef;
5554 hp->value.keydef = kp;
5556 else
5557 str->writeflag = 1;
5560 /* This output_line_directive serves to switch us back to the current
5561 input file in case some of these strings get output (which will
5562 result in line directives for the header file being output). */
5563 output_line_directive (&instack[indepth], op, 0, enter_file);
5566 /* Called from rescan when it hits a key for strings. Mark them all
5567 used and clean up. */
5569 static void
5570 pcstring_used (hp)
5571 HASHNODE *hp;
5573 KEYDEF *kp;
5575 for (kp = hp->value.keydef; kp; kp = kp->chain)
5576 kp->str->writeflag = 1;
5577 delete_macro (hp);
5580 /* Write the output, interspersing precompiled strings in their
5581 appropriate places. */
5583 static void
5584 write_output ()
5586 STRINGDEF *next_string;
5587 U_CHAR *cur_buf_loc;
5588 int line_directive_len = 80;
5589 char *line_directive = xmalloc (line_directive_len);
5590 int len;
5592 /* In each run through the loop, either cur_buf_loc ==
5593 next_string_loc, in which case we print a series of strings, or
5594 it is less than next_string_loc, in which case we write some of
5595 the buffer. */
5596 cur_buf_loc = outbuf.buf;
5597 next_string = stringlist;
5599 while (cur_buf_loc < outbuf.bufp || next_string) {
5600 if (next_string
5601 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5602 if (next_string->writeflag) {
5603 len = 4 * strlen ((char *) next_string->filename) + 32;
5604 while (len > line_directive_len)
5605 line_directive = xrealloc (line_directive,
5606 line_directive_len *= 2);
5607 sprintf (line_directive, "\n# %d ", next_string->lineno);
5608 strcpy (quote_string (line_directive + strlen (line_directive),
5609 (char *) next_string->filename,
5610 strlen ((char *) next_string->filename)),
5611 "\n");
5612 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5613 safe_write (fileno (stdout),
5614 (char *) next_string->contents, next_string->len);
5616 next_string = next_string->chain;
5618 else {
5619 len = (next_string
5620 ? (next_string->output_mark
5621 - (cur_buf_loc - outbuf.buf))
5622 : outbuf.bufp - cur_buf_loc);
5624 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5625 cur_buf_loc += len;
5628 free (line_directive);
5631 /* Pass a directive through to the output file.
5632 BUF points to the contents of the directive, as a contiguous string.
5633 LIMIT points to the first character past the end of the directive.
5634 KEYWORD is the keyword-table entry for the directive. */
5636 static void
5637 pass_thru_directive (buf, limit, op, keyword)
5638 U_CHAR *buf, *limit;
5639 FILE_BUF *op;
5640 struct directive *keyword;
5642 register int keyword_length = keyword->length;
5644 check_expand (op, 1 + keyword_length + (limit - buf));
5645 *op->bufp++ = '#';
5646 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5647 op->bufp += keyword_length;
5648 if (limit != buf && buf[0] != ' ')
5649 *op->bufp++ = ' ';
5650 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5651 op->bufp += (limit - buf);
5652 #if 0
5653 *op->bufp++ = '\n';
5654 /* Count the line we have just made in the output,
5655 to get in sync properly. */
5656 op->lineno++;
5657 #endif
5660 /* The arglist structure is built by do_define to tell
5661 collect_definition where the argument names begin. That
5662 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5663 would contain pointers to the strings x, y, and z.
5664 Collect_definition would then build a DEFINITION node,
5665 with reflist nodes pointing to the places x, y, and z had
5666 appeared. So the arglist is just convenience data passed
5667 between these two routines. It is not kept around after
5668 the current #define has been processed and entered into the
5669 hash table. */
5671 struct arglist {
5672 struct arglist *next;
5673 U_CHAR *name;
5674 int length;
5675 int argno;
5676 char rest_args;
5679 /* Create a DEFINITION node from a #define directive. Arguments are
5680 as for do_define. */
5682 static MACRODEF
5683 create_definition (buf, limit, op)
5684 U_CHAR *buf, *limit;
5685 FILE_BUF *op;
5687 U_CHAR *bp; /* temp ptr into input buffer */
5688 U_CHAR *symname; /* remember where symbol name starts */
5689 int sym_length; /* and how long it is */
5690 int line = instack[indepth].lineno;
5691 char *file = instack[indepth].nominal_fname;
5692 size_t file_len = instack[indepth].nominal_fname_len;
5693 int rest_args = 0;
5695 DEFINITION *defn;
5696 int arglengths = 0; /* Accumulate lengths of arg names
5697 plus number of args. */
5698 MACRODEF mdef;
5700 bp = buf;
5702 while (is_hor_space[*bp])
5703 bp++;
5705 symname = bp; /* remember where it starts */
5706 sym_length = check_macro_name (bp, 0);
5707 bp += sym_length;
5709 /* Lossage will occur if identifiers or control keywords are broken
5710 across lines using backslash. This is not the right place to take
5711 care of that. */
5713 if (*bp == '(') {
5714 struct arglist *arg_ptrs = NULL;
5715 int argno = 0;
5717 bp++; /* skip '(' */
5718 SKIP_WHITE_SPACE (bp);
5720 /* Loop over macro argument names. */
5721 while (*bp != ')') {
5722 struct arglist *temp;
5724 temp = (struct arglist *) alloca (sizeof (struct arglist));
5725 temp->name = bp;
5726 temp->next = arg_ptrs;
5727 temp->argno = argno++;
5728 temp->rest_args = 0;
5729 arg_ptrs = temp;
5731 if (rest_args)
5732 pedwarn ("another parameter follows `%s'",
5733 rest_extension);
5735 if (!is_idstart[*bp])
5737 if (c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5738 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)
5740 /* This is the ISO C 9x way to write macros with variable
5741 number of arguments. */
5742 rest_args = 1;
5743 temp->rest_args = 1;
5745 else
5746 pedwarn ("invalid character in macro parameter name");
5749 /* Find the end of the arg name. */
5750 while (is_idchar[*bp]) {
5751 bp++;
5752 /* do we have a "special" rest-args extension here? */
5753 if (limit - bp > (long) REST_EXTENSION_LENGTH
5754 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5755 if (pedantic && !instack[indepth].system_header_p)
5756 pedwarn ("ANSI C does not allow macro with variable arguments");
5757 rest_args = 1;
5758 temp->rest_args = 1;
5759 break;
5762 if (bp == temp->name && rest_args == 1)
5764 /* This is the ISO C 9x style. */
5765 temp->name = (U_CHAR *) va_args_name;
5766 temp->length = VA_ARGS_NAME_LENGTH;
5768 else
5769 temp->length = bp - temp->name;
5770 if (rest_args == 1)
5771 bp += REST_EXTENSION_LENGTH;
5772 arglengths += temp->length + 2;
5773 SKIP_WHITE_SPACE (bp);
5774 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5775 error ("badly punctuated parameter list in `#define'");
5776 goto nope;
5778 if (*bp == ',') {
5779 bp++;
5780 SKIP_WHITE_SPACE (bp);
5781 /* A comma at this point can only be followed by an identifier. */
5782 if (!is_idstart[*bp]
5783 && !(c9x && limit - bp > (long) REST_EXTENSION_LENGTH
5784 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0)) {
5785 error ("badly punctuated parameter list in `#define'");
5786 goto nope;
5789 if (bp >= limit) {
5790 error ("unterminated parameter list in `#define'");
5791 goto nope;
5794 struct arglist *otemp;
5796 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5797 if (temp->length == otemp->length
5798 && bcmp (temp->name, otemp->name, temp->length) == 0)
5800 error ("duplicate argument name `%.*s' in `#define'",
5801 temp->length, temp->name);
5802 goto nope;
5804 if (rest_args == 0 && temp->length == VA_ARGS_NAME_LENGTH
5805 && bcmp (temp->name, va_args_name, VA_ARGS_NAME_LENGTH) == 0)
5807 error ("\
5808 reserved name `%s' used as argument name in `#define'", va_args_name);
5809 goto nope;
5814 ++bp; /* skip paren */
5815 SKIP_WHITE_SPACE (bp);
5816 /* now everything from bp before limit is the definition. */
5817 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5818 defn->rest_args = rest_args;
5820 /* Now set defn->args.argnames to the result of concatenating
5821 the argument names in reverse order
5822 with comma-space between them. */
5823 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5825 struct arglist *temp;
5826 int i = 0;
5827 for (temp = arg_ptrs; temp; temp = temp->next) {
5828 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5829 i += temp->length;
5830 if (temp->next != 0) {
5831 defn->args.argnames[i++] = ',';
5832 defn->args.argnames[i++] = ' ';
5835 defn->args.argnames[i] = 0;
5837 } else {
5838 /* Simple expansion or empty definition. */
5840 if (bp < limit)
5842 if (is_hor_space[*bp]) {
5843 bp++;
5844 SKIP_WHITE_SPACE (bp);
5845 } else if (sym_length) {
5846 switch (*bp) {
5847 case '!': case '"': case '#': case '%': case '&': case '\'':
5848 case ')': case '*': case '+': case ',': case '-': case '.':
5849 case '/': case ':': case ';': case '<': case '=': case '>':
5850 case '?': case '[': case '\\': case ']': case '^': case '{':
5851 case '|': case '}': case '~':
5852 warning ("missing white space after `#define %.*s'",
5853 sym_length, symname);
5854 break;
5856 default:
5857 pedwarn ("missing white space after `#define %.*s'",
5858 sym_length, symname);
5859 break;
5863 /* Now everything from bp before limit is the definition. */
5864 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5865 defn->args.argnames = (U_CHAR *) "";
5868 defn->line = line;
5869 defn->file = file;
5870 defn->file_len = file_len;
5872 /* OP is null if this is a predefinition */
5873 defn->predefined = !op;
5874 mdef.defn = defn;
5875 mdef.symnam = symname;
5876 mdef.symlen = sym_length;
5878 return mdef;
5880 nope:
5881 mdef.defn = 0;
5882 return mdef;
5885 /* Process a #define directive.
5886 BUF points to the contents of the #define directive, as a contiguous string.
5887 LIMIT points to the first character past the end of the definition.
5888 KEYWORD is the keyword-table entry for #define. */
5890 static int
5891 do_define (buf, limit, op, keyword)
5892 U_CHAR *buf, *limit;
5893 FILE_BUF *op;
5894 struct directive *keyword;
5896 int hashcode;
5897 MACRODEF mdef;
5899 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5900 if (pcp_outfile && op)
5901 pass_thru_directive (buf, limit, op, keyword);
5903 mdef = create_definition (buf, limit, op);
5904 if (mdef.defn == 0)
5905 goto nope;
5907 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5910 HASHNODE *hp;
5911 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5912 int ok = 0;
5913 /* Redefining a precompiled key is ok. */
5914 if (hp->type == T_PCSTRING)
5915 ok = 1;
5916 /* Redefining a macro is ok if the definitions are the same. */
5917 else if (hp->type == T_MACRO)
5918 ok = ! compare_defs (mdef.defn, hp->value.defn);
5919 /* Redefining a constant is ok with -D. */
5920 else if (hp->type == T_CONST)
5921 ok = ! done_initializing;
5922 /* Print the warning if it's not ok. */
5923 if (!ok) {
5924 /* If we are passing through #define and #undef directives, do
5925 that for this re-definition now. */
5926 if (debug_output && op)
5927 pass_thru_directive (buf, limit, op, keyword);
5929 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5930 if (hp->type == T_MACRO)
5931 pedwarn_with_file_and_line (hp->value.defn->file,
5932 hp->value.defn->file_len,
5933 hp->value.defn->line,
5934 "this is the location of the previous definition");
5936 /* Replace the old definition. */
5937 hp->type = T_MACRO;
5938 hp->value.defn = mdef.defn;
5939 } else {
5940 /* If we are passing through #define and #undef directives, do
5941 that for this new definition now. */
5942 if (debug_output && op)
5943 pass_thru_directive (buf, limit, op, keyword);
5944 install (mdef.symnam, mdef.symlen, T_MACRO,
5945 (char *) mdef.defn, hashcode);
5949 return 0;
5951 nope:
5953 return 1;
5956 /* Check a purported macro name SYMNAME, and yield its length.
5957 ASSERTION is nonzero if this is really for an assertion name. */
5959 static int
5960 check_macro_name (symname, assertion)
5961 U_CHAR *symname;
5962 int assertion;
5964 U_CHAR *p;
5965 int sym_length;
5967 for (p = symname; is_idchar[*p]; p++)
5969 sym_length = p - symname;
5970 if (sym_length == 0
5971 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5972 error (assertion ? "invalid assertion name" : "invalid macro name");
5973 else if (!is_idstart[*symname]
5974 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5975 error ((assertion
5976 ? "invalid assertion name `%.*s'"
5977 : "invalid macro name `%.*s'"),
5978 sym_length, symname);
5979 return sym_length;
5982 /* Return zero if two DEFINITIONs are isomorphic. */
5984 static int
5985 compare_defs (d1, d2)
5986 DEFINITION *d1, *d2;
5988 register struct reflist *a1, *a2;
5989 register U_CHAR *p1 = d1->expansion;
5990 register U_CHAR *p2 = d2->expansion;
5991 int first = 1;
5993 if (d1->nargs != d2->nargs)
5994 return 1;
5995 if (pedantic
5996 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5997 return 1;
5998 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5999 a1 = a1->next, a2 = a2->next) {
6000 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
6001 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
6002 || a1->argno != a2->argno
6003 || a1->stringify != a2->stringify
6004 || a1->raw_before != a2->raw_before
6005 || a1->raw_after != a2->raw_after)
6006 return 1;
6007 first = 0;
6008 p1 += a1->nchars;
6009 p2 += a2->nchars;
6011 if (a1 != a2)
6012 return 1;
6013 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
6014 p2, d2->length - (p2 - d2->expansion), 1))
6015 return 1;
6016 return 0;
6019 /* Return 1 if two parts of two macro definitions are effectively different.
6020 One of the parts starts at BEG1 and has LEN1 chars;
6021 the other has LEN2 chars at BEG2.
6022 Any sequence of whitespace matches any other sequence of whitespace.
6023 FIRST means these parts are the first of a macro definition;
6024 so ignore leading whitespace entirely.
6025 LAST means these parts are the last of a macro definition;
6026 so ignore trailing whitespace entirely. */
6028 static int
6029 comp_def_part (first, beg1, len1, beg2, len2, last)
6030 int first;
6031 U_CHAR *beg1, *beg2;
6032 int len1, len2;
6033 int last;
6035 register U_CHAR *end1 = beg1 + len1;
6036 register U_CHAR *end2 = beg2 + len2;
6037 if (first) {
6038 while (beg1 != end1 && is_space[*beg1]) beg1++;
6039 while (beg2 != end2 && is_space[*beg2]) beg2++;
6041 if (last) {
6042 while (beg1 != end1 && is_space[end1[-1]]) end1--;
6043 while (beg2 != end2 && is_space[end2[-1]]) end2--;
6045 while (beg1 != end1 && beg2 != end2) {
6046 if (is_space[*beg1] && is_space[*beg2]) {
6047 while (beg1 != end1 && is_space[*beg1]) beg1++;
6048 while (beg2 != end2 && is_space[*beg2]) beg2++;
6049 } else if (*beg1 == *beg2) {
6050 beg1++; beg2++;
6051 } else break;
6053 return (beg1 != end1) || (beg2 != end2);
6056 /* Read a replacement list for a macro with parameters.
6057 Build the DEFINITION structure.
6058 Reads characters of text starting at BUF until END.
6059 ARGLIST specifies the formal parameters to look for
6060 in the text of the definition; NARGS is the number of args
6061 in that list, or -1 for a macro name that wants no argument list.
6062 MACRONAME is the macro name itself (so we can avoid recursive expansion)
6063 and NAMELEN is its length in characters.
6065 Note that comments, backslash-newlines, and leading white space
6066 have already been deleted from the argument. */
6068 /* If there is no trailing whitespace, a Newline Space is added at the end
6069 to prevent concatenation that would be contrary to the standard. */
6071 static DEFINITION *
6072 collect_expansion (buf, end, nargs, arglist)
6073 U_CHAR *buf, *end;
6074 int nargs;
6075 struct arglist *arglist;
6077 DEFINITION *defn;
6078 register U_CHAR *p, *limit, *lastp, *exp_p;
6079 struct reflist *endpat = NULL;
6080 /* Pointer to first nonspace after last ## seen. */
6081 U_CHAR *concat = 0;
6082 /* Pointer to first nonspace after last single-# seen. */
6083 U_CHAR *stringify = 0;
6084 /* How those tokens were spelled. */
6085 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
6086 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
6087 int maxsize;
6088 int expected_delimiter = '\0';
6090 /* Scan thru the replacement list, ignoring comments and quoted
6091 strings, picking up on the macro calls. It does a linear search
6092 thru the arg list on every potential symbol. Profiling might say
6093 that something smarter should happen. */
6095 if (end < buf)
6096 abort ();
6098 /* Find the beginning of the trailing whitespace. */
6099 limit = end;
6100 p = buf;
6101 while (p < limit && is_space[limit[-1]]) limit--;
6103 /* Allocate space for the text in the macro definition.
6104 Each input char may or may not need 1 byte,
6105 so this is an upper bound.
6106 The extra 3 are for invented trailing newline-marker and final null. */
6107 maxsize = (sizeof (DEFINITION)
6108 + (limit - p) + 3);
6109 defn = (DEFINITION *) xcalloc (1, maxsize);
6111 defn->nargs = nargs;
6112 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6113 lastp = exp_p;
6115 if (p[0] == '#'
6116 ? p[1] == '#'
6117 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6118 error ("`##' at start of macro definition");
6119 p += p[0] == '#' ? 2 : 4;
6122 /* Process the main body of the definition. */
6123 while (p < limit) {
6124 int skipped_arg = 0;
6125 register U_CHAR c = *p++;
6127 *exp_p++ = c;
6129 if (!traditional) {
6130 switch (c) {
6131 case '\'':
6132 case '\"':
6133 if (expected_delimiter != '\0') {
6134 if (c == expected_delimiter)
6135 expected_delimiter = '\0';
6136 } else
6137 expected_delimiter = c;
6138 break;
6140 case '\\':
6141 if (p < limit && expected_delimiter) {
6142 /* In a string, backslash goes through
6143 and makes next char ordinary. */
6144 *exp_p++ = *p++;
6146 break;
6148 case '%':
6149 if (!expected_delimiter && *p == ':') {
6150 /* %: is not a digraph if preceded by an odd number of '<'s. */
6151 U_CHAR *p0 = p - 1;
6152 while (buf < p0 && p0[-1] == '<')
6153 p0--;
6154 if ((p - p0) & 1) {
6155 /* Treat %:%: as ## and %: as #. */
6156 if (p[1] == '%' && p[2] == ':') {
6157 p += 2;
6158 goto sharp_sharp_token;
6160 if (nargs >= 0) {
6161 p++;
6162 goto sharp_token;
6166 break;
6168 case '#':
6169 /* # is ordinary inside a string. */
6170 if (expected_delimiter)
6171 break;
6172 if (*p == '#') {
6173 sharp_sharp_token:
6174 /* ##: concatenate preceding and following tokens. */
6175 /* Take out the first #, discard preceding whitespace. */
6176 exp_p--;
6177 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6178 --exp_p;
6179 /* Skip the second #. */
6180 p++;
6181 concat_sharp_token_type = c;
6182 if (is_hor_space[*p]) {
6183 concat_sharp_token_type = c + 1;
6184 p++;
6185 SKIP_WHITE_SPACE (p);
6187 concat = p;
6188 if (p == limit)
6189 error ("`##' at end of macro definition");
6190 } else if (nargs >= 0) {
6191 /* Single #: stringify following argument ref.
6192 Don't leave the # in the expansion. */
6193 sharp_token:
6194 exp_p--;
6195 stringify_sharp_token_type = c;
6196 if (is_hor_space[*p]) {
6197 stringify_sharp_token_type = c + 1;
6198 p++;
6199 SKIP_WHITE_SPACE (p);
6201 if (! is_idstart[*p] || nargs == 0
6202 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6203 error ("`#' operator is not followed by a macro argument name");
6204 else
6205 stringify = p;
6207 break;
6209 } else {
6210 /* In -traditional mode, recognize arguments inside strings and
6211 character constants, and ignore special properties of #.
6212 Arguments inside strings are considered "stringified", but no
6213 extra quote marks are supplied. */
6214 switch (c) {
6215 case '\'':
6216 case '\"':
6217 if (expected_delimiter != '\0') {
6218 if (c == expected_delimiter)
6219 expected_delimiter = '\0';
6220 } else
6221 expected_delimiter = c;
6222 break;
6224 case '\\':
6225 /* Backslash quotes delimiters and itself, but not macro args. */
6226 if (expected_delimiter != 0 && p < limit
6227 && (*p == expected_delimiter || *p == '\\')) {
6228 *exp_p++ = *p++;
6229 continue;
6231 break;
6233 case '/':
6234 if (expected_delimiter != '\0') /* No comments inside strings. */
6235 break;
6236 if (*p == '*') {
6237 /* If we find a comment that wasn't removed by handle_directive,
6238 this must be -traditional. So replace the comment with
6239 nothing at all. */
6240 exp_p--;
6241 while (++p < limit) {
6242 if (p[0] == '*' && p[1] == '/') {
6243 p += 2;
6244 break;
6247 #if 0
6248 /* Mark this as a concatenation-point, as if it had been ##. */
6249 concat = p;
6250 #endif
6252 break;
6256 #ifdef MULTIBYTE_CHARS
6257 /* Handle multibyte characters inside string and character literals. */
6258 if (expected_delimiter != '\0')
6260 int length;
6261 --p;
6262 length = local_mblen (p, limit - p);
6263 if (length > 1)
6265 --exp_p;
6266 bcopy (p, exp_p, length);
6267 p += length;
6268 exp_p += length;
6269 continue;
6271 ++p;
6273 #endif
6275 /* Handle the start of a symbol. */
6276 if (is_idchar[c] && nargs > 0) {
6277 U_CHAR *id_beg = p - 1;
6278 int id_len;
6280 --exp_p;
6281 while (p != limit && is_idchar[*p]) p++;
6282 id_len = p - id_beg;
6284 if (is_idstart[c]
6285 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6286 register struct arglist *arg;
6288 for (arg = arglist; arg != NULL; arg = arg->next) {
6289 struct reflist *tpat;
6291 if (arg->name[0] == c
6292 && arg->length == id_len
6293 && bcmp (arg->name, id_beg, id_len) == 0) {
6294 enum sharp_token_type tpat_stringify;
6295 if (expected_delimiter) {
6296 if (warn_stringify) {
6297 if (traditional) {
6298 warning ("macro argument `%.*s' is stringified.",
6299 id_len, arg->name);
6300 } else {
6301 warning ("macro arg `%.*s' would be stringified with -traditional.",
6302 id_len, arg->name);
6305 /* If ANSI, don't actually substitute inside a string. */
6306 if (!traditional)
6307 break;
6308 tpat_stringify = SHARP_TOKEN;
6309 } else {
6310 tpat_stringify
6311 = (stringify == id_beg
6312 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6314 /* make a pat node for this arg and append it to the end of
6315 the pat list */
6316 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6317 tpat->next = NULL;
6318 tpat->raw_before
6319 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6320 tpat->raw_after = NO_SHARP_TOKEN;
6321 tpat->rest_args = arg->rest_args;
6322 tpat->stringify = tpat_stringify;
6324 if (endpat == NULL)
6325 defn->pattern = tpat;
6326 else
6327 endpat->next = tpat;
6328 endpat = tpat;
6330 tpat->argno = arg->argno;
6331 tpat->nchars = exp_p - lastp;
6333 register U_CHAR *p1 = p;
6334 SKIP_WHITE_SPACE (p1);
6335 if (p1[0]=='#'
6336 ? p1[1]=='#'
6337 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6338 tpat->raw_after = p1[0] + (p != p1);
6340 lastp = exp_p; /* place to start copying from next time */
6341 skipped_arg = 1;
6342 break;
6347 /* If this was not a macro arg, copy it into the expansion. */
6348 if (! skipped_arg) {
6349 register U_CHAR *lim1 = p;
6350 p = id_beg;
6351 while (p != lim1)
6352 *exp_p++ = *p++;
6353 if (stringify == id_beg)
6354 error ("`#' operator should be followed by a macro argument name");
6359 if (!traditional && expected_delimiter == 0) {
6360 /* If ANSI, put in a newline-space marker to prevent token pasting.
6361 But not if "inside a string" (which in ANSI mode happens only for
6362 -D option). */
6363 *exp_p++ = '\n';
6364 *exp_p++ = ' ';
6367 *exp_p = '\0';
6369 defn->length = exp_p - defn->expansion;
6371 /* Crash now if we overrun the allocated size. */
6372 if (defn->length + 1 > maxsize)
6373 abort ();
6375 #if 0
6376 /* This isn't worth the time it takes. */
6377 /* give back excess storage */
6378 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6379 #endif
6381 return defn;
6384 static int
6385 do_assert (buf, limit, op, keyword)
6386 U_CHAR *buf, *limit;
6387 FILE_BUF *op ATTRIBUTE_UNUSED;
6388 struct directive *keyword ATTRIBUTE_UNUSED;
6390 U_CHAR *bp; /* temp ptr into input buffer */
6391 U_CHAR *symname; /* remember where symbol name starts */
6392 int sym_length; /* and how long it is */
6393 struct arglist *tokens = NULL;
6395 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6396 pedwarn ("ANSI C does not allow `#assert'");
6398 bp = buf;
6400 while (is_hor_space[*bp])
6401 bp++;
6403 symname = bp; /* remember where it starts */
6404 sym_length = check_macro_name (bp, 1);
6405 bp += sym_length;
6406 /* #define doesn't do this, but we should. */
6407 SKIP_WHITE_SPACE (bp);
6409 /* Lossage will occur if identifiers or control tokens are broken
6410 across lines using backslash. This is not the right place to take
6411 care of that. */
6413 if (*bp != '(') {
6414 error ("missing token-sequence in `#assert'");
6415 return 1;
6419 int error_flag = 0;
6421 bp++; /* skip '(' */
6422 SKIP_WHITE_SPACE (bp);
6424 tokens = read_token_list (&bp, limit, &error_flag);
6425 if (error_flag)
6426 return 1;
6427 if (tokens == 0) {
6428 error ("empty token-sequence in `#assert'");
6429 return 1;
6432 ++bp; /* skip paren */
6433 SKIP_WHITE_SPACE (bp);
6436 /* If this name isn't already an assertion name, make it one.
6437 Error if it was already in use in some other way. */
6440 ASSERTION_HASHNODE *hp;
6441 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6442 struct tokenlist_list *value
6443 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6445 hp = assertion_lookup (symname, sym_length, hashcode);
6446 if (hp == NULL) {
6447 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6448 error ("`defined' redefined as assertion");
6449 hp = assertion_install (symname, sym_length, hashcode);
6452 /* Add the spec'd token-sequence to the list of such. */
6453 value->tokens = tokens;
6454 value->next = hp->value;
6455 hp->value = value;
6458 return 0;
6461 static int
6462 do_unassert (buf, limit, op, keyword)
6463 U_CHAR *buf, *limit;
6464 FILE_BUF *op ATTRIBUTE_UNUSED;
6465 struct directive *keyword ATTRIBUTE_UNUSED;
6467 U_CHAR *bp; /* temp ptr into input buffer */
6468 U_CHAR *symname; /* remember where symbol name starts */
6469 int sym_length; /* and how long it is */
6471 struct arglist *tokens = NULL;
6472 int tokens_specified = 0;
6474 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6475 pedwarn ("ANSI C does not allow `#unassert'");
6477 bp = buf;
6479 while (is_hor_space[*bp])
6480 bp++;
6482 symname = bp; /* remember where it starts */
6483 sym_length = check_macro_name (bp, 1);
6484 bp += sym_length;
6485 /* #define doesn't do this, but we should. */
6486 SKIP_WHITE_SPACE (bp);
6488 /* Lossage will occur if identifiers or control tokens are broken
6489 across lines using backslash. This is not the right place to take
6490 care of that. */
6492 if (*bp == '(') {
6493 int error_flag = 0;
6495 bp++; /* skip '(' */
6496 SKIP_WHITE_SPACE (bp);
6498 tokens = read_token_list (&bp, limit, &error_flag);
6499 if (error_flag)
6500 return 1;
6501 if (tokens == 0) {
6502 error ("empty token list in `#unassert'");
6503 return 1;
6506 tokens_specified = 1;
6508 ++bp; /* skip paren */
6509 SKIP_WHITE_SPACE (bp);
6513 ASSERTION_HASHNODE *hp;
6514 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6515 struct tokenlist_list *tail, *prev;
6517 hp = assertion_lookup (symname, sym_length, hashcode);
6518 if (hp == NULL)
6519 return 1;
6521 /* If no token list was specified, then eliminate this assertion
6522 entirely. */
6523 if (! tokens_specified) {
6524 struct tokenlist_list *next;
6525 for (tail = hp->value; tail; tail = next) {
6526 next = tail->next;
6527 free_token_list (tail->tokens);
6528 free (tail);
6530 delete_assertion (hp);
6531 } else {
6532 /* If a list of tokens was given, then delete any matching list. */
6534 tail = hp->value;
6535 prev = 0;
6536 while (tail) {
6537 struct tokenlist_list *next = tail->next;
6538 if (compare_token_lists (tail->tokens, tokens)) {
6539 if (prev)
6540 prev->next = next;
6541 else
6542 hp->value = tail->next;
6543 free_token_list (tail->tokens);
6544 free (tail);
6545 } else {
6546 prev = tail;
6548 tail = next;
6553 return 0;
6556 /* Test whether there is an assertion named NAME
6557 and optionally whether it has an asserted token list TOKENS.
6558 NAME is not null terminated; its length is SYM_LENGTH.
6559 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6562 check_assertion (name, sym_length, tokens_specified, tokens)
6563 U_CHAR *name;
6564 int sym_length;
6565 int tokens_specified;
6566 struct arglist *tokens;
6568 ASSERTION_HASHNODE *hp;
6569 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6571 if (pedantic && !instack[indepth].system_header_p)
6572 pedwarn ("ANSI C does not allow testing assertions");
6574 hp = assertion_lookup (name, sym_length, hashcode);
6575 if (hp == NULL)
6576 /* It is not an assertion; just return false. */
6577 return 0;
6579 /* If no token list was specified, then value is 1. */
6580 if (! tokens_specified)
6581 return 1;
6584 struct tokenlist_list *tail;
6586 tail = hp->value;
6588 /* If a list of tokens was given,
6589 then succeed if the assertion records a matching list. */
6591 while (tail) {
6592 if (compare_token_lists (tail->tokens, tokens))
6593 return 1;
6594 tail = tail->next;
6597 /* Fail if the assertion has no matching list. */
6598 return 0;
6602 /* Compare two lists of tokens for equality including order of tokens. */
6604 static int
6605 compare_token_lists (l1, l2)
6606 struct arglist *l1, *l2;
6608 while (l1 && l2) {
6609 if (l1->length != l2->length)
6610 return 0;
6611 if (bcmp (l1->name, l2->name, l1->length))
6612 return 0;
6613 l1 = l1->next;
6614 l2 = l2->next;
6617 /* Succeed if both lists end at the same time. */
6618 return l1 == l2;
6621 /* Read a space-separated list of tokens ending in a close parenthesis.
6622 Return a list of strings, in the order they were written.
6623 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6624 Parse the text starting at *BPP, and update *BPP.
6625 Don't parse beyond LIMIT. */
6627 static struct arglist *
6628 read_token_list (bpp, limit, error_flag)
6629 U_CHAR **bpp;
6630 U_CHAR *limit;
6631 int *error_flag;
6633 struct arglist *token_ptrs = 0;
6634 U_CHAR *bp = *bpp;
6635 int depth = 1;
6637 *error_flag = 0;
6639 /* Loop over the assertion value tokens. */
6640 while (depth > 0) {
6641 struct arglist *temp;
6642 int eofp = 0;
6643 U_CHAR *beg = bp;
6645 /* Find the end of the token. */
6646 if (*bp == '(') {
6647 bp++;
6648 depth++;
6649 } else if (*bp == ')') {
6650 depth--;
6651 if (depth == 0)
6652 break;
6653 bp++;
6654 } else if (*bp == '"' || *bp == '\'')
6655 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6656 else
6657 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6658 && *bp != '"' && *bp != '\'' && bp != limit)
6659 bp++;
6661 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6662 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6663 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6664 temp->name[bp - beg] = 0;
6665 temp->next = token_ptrs;
6666 token_ptrs = temp;
6667 temp->length = bp - beg;
6669 SKIP_WHITE_SPACE (bp);
6671 if (bp >= limit) {
6672 error ("unterminated token sequence in `#assert' or `#unassert'");
6673 *error_flag = -1;
6674 return 0;
6677 *bpp = bp;
6679 /* We accumulated the names in reverse order.
6680 Now reverse them to get the proper order. */
6682 register struct arglist *prev = 0, *this, *next;
6683 for (this = token_ptrs; this; this = next) {
6684 next = this->next;
6685 this->next = prev;
6686 prev = this;
6688 return prev;
6692 static void
6693 free_token_list (tokens)
6694 struct arglist *tokens;
6696 while (tokens) {
6697 struct arglist *next = tokens->next;
6698 free (tokens->name);
6699 free (tokens);
6700 tokens = next;
6704 /* Install a name in the assertion hash table.
6706 If LEN is >= 0, it is the length of the name.
6707 Otherwise, compute the length by scanning the entire name.
6709 If HASH is >= 0, it is the precomputed hash code.
6710 Otherwise, compute the hash code. */
6712 static ASSERTION_HASHNODE *
6713 assertion_install (name, len, hash)
6714 U_CHAR *name;
6715 int len;
6716 int hash;
6718 register ASSERTION_HASHNODE *hp;
6719 register int i, bucket;
6720 register U_CHAR *p, *q;
6722 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6723 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6724 bucket = hash;
6725 hp->bucket_hdr = &assertion_hashtab[bucket];
6726 hp->next = assertion_hashtab[bucket];
6727 assertion_hashtab[bucket] = hp;
6728 hp->prev = NULL;
6729 if (hp->next != NULL)
6730 hp->next->prev = hp;
6731 hp->length = len;
6732 hp->value = 0;
6733 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6734 p = hp->name;
6735 q = name;
6736 for (i = 0; i < len; i++)
6737 *p++ = *q++;
6738 hp->name[len] = 0;
6739 return hp;
6742 /* Find the most recent hash node for name "name" (ending with first
6743 non-identifier char) installed by install
6745 If LEN is >= 0, it is the length of the name.
6746 Otherwise, compute the length by scanning the entire name.
6748 If HASH is >= 0, it is the precomputed hash code.
6749 Otherwise, compute the hash code. */
6751 static ASSERTION_HASHNODE *
6752 assertion_lookup (name, len, hash)
6753 U_CHAR *name;
6754 int len;
6755 int hash;
6757 register ASSERTION_HASHNODE *bucket;
6759 bucket = assertion_hashtab[hash];
6760 while (bucket) {
6761 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6762 return bucket;
6763 bucket = bucket->next;
6765 return NULL;
6768 static void
6769 delete_assertion (hp)
6770 ASSERTION_HASHNODE *hp;
6773 if (hp->prev != NULL)
6774 hp->prev->next = hp->next;
6775 if (hp->next != NULL)
6776 hp->next->prev = hp->prev;
6778 /* Make sure that the bucket chain header that the deleted guy was
6779 on points to the right thing afterwards. */
6780 if (hp == *hp->bucket_hdr)
6781 *hp->bucket_hdr = hp->next;
6783 free (hp);
6787 * interpret #line directive. Remembers previously seen fnames
6788 * in its very own hash table.
6790 #define FNAME_HASHSIZE 37
6792 static int
6793 do_line (buf, limit, op, keyword)
6794 U_CHAR *buf, *limit;
6795 FILE_BUF *op;
6796 struct directive *keyword ATTRIBUTE_UNUSED;
6798 register U_CHAR *bp;
6799 FILE_BUF *ip = &instack[indepth];
6800 FILE_BUF tem;
6801 int new_lineno;
6802 enum file_change_code file_change = same_file;
6804 /* Expand any macros. */
6805 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6807 /* Point to macroexpanded line, which is null-terminated now. */
6808 bp = tem.buf;
6809 SKIP_WHITE_SPACE (bp);
6811 if (!ISDIGIT (*bp)) {
6812 error ("invalid format `#line' directive");
6813 return 0;
6816 /* The Newline at the end of this line remains to be processed.
6817 To put the next line at the specified line number,
6818 we must store a line number now that is one less. */
6819 new_lineno = atoi ((char *) bp) - 1;
6821 /* NEW_LINENO is one less than the actual line number here. */
6822 if (pedantic && new_lineno < 0)
6823 pedwarn ("line number out of range in `#line' directive");
6825 /* skip over the line number. */
6826 while (ISDIGIT (*bp))
6827 bp++;
6829 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6830 if (*bp && !is_space[*bp]) {
6831 error ("invalid format `#line' directive");
6832 return;
6834 #endif
6836 SKIP_WHITE_SPACE (bp);
6838 if (*bp == '\"') {
6839 static HASHNODE *fname_table[FNAME_HASHSIZE];
6840 HASHNODE *hp, **hash_bucket;
6841 U_CHAR *fname, *p;
6842 int fname_length;
6844 fname = ++bp;
6846 /* Turn the file name, which is a character string literal,
6847 into a null-terminated string. Do this in place. */
6848 p = bp;
6849 for (;;)
6850 switch ((*p++ = *bp++)) {
6851 case '\0':
6852 error ("invalid format `#line' directive");
6853 return 0;
6855 case '\\':
6856 if (! ignore_escape_flag)
6858 char *bpc = (char *) bp;
6859 HOST_WIDEST_INT c = parse_escape (&bpc, (HOST_WIDEST_INT) (U_CHAR) (-1));
6860 bp = (U_CHAR *) bpc;
6861 if (c < 0)
6862 p--;
6863 else
6864 p[-1] = c;
6866 break;
6868 case '\"':
6869 *--p = 0;
6870 goto fname_done;
6872 fname_done:
6873 fname_length = p - fname;
6875 SKIP_WHITE_SPACE (bp);
6876 if (*bp) {
6877 if (pedantic)
6878 pedwarn ("garbage at end of `#line' directive");
6879 if (*bp == '1')
6880 file_change = enter_file;
6881 else if (*bp == '2')
6882 file_change = leave_file;
6883 else if (*bp == '3')
6884 ip->system_header_p = 1;
6885 else if (*bp == '4')
6886 ip->system_header_p = 2;
6887 else {
6888 error ("invalid format `#line' directive");
6889 return 0;
6892 bp++;
6893 SKIP_WHITE_SPACE (bp);
6894 if (*bp == '3') {
6895 ip->system_header_p = 1;
6896 bp++;
6897 SKIP_WHITE_SPACE (bp);
6899 if (*bp == '4') {
6900 ip->system_header_p = 2;
6901 bp++;
6902 SKIP_WHITE_SPACE (bp);
6904 if (*bp) {
6905 error ("invalid format `#line' directive");
6906 return 0;
6910 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6911 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6912 if (hp->length == fname_length &&
6913 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6914 ip->nominal_fname = hp->value.cpval;
6915 ip->nominal_fname_len = fname_length;
6916 break;
6918 if (hp == 0) {
6919 /* Didn't find it; cons up a new one. */
6920 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6921 hp->next = *hash_bucket;
6922 *hash_bucket = hp;
6924 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6925 ip->nominal_fname_len = hp->length = fname_length;
6926 bcopy (fname, hp->value.cpval, fname_length + 1);
6928 } else if (*bp) {
6929 error ("invalid format `#line' directive");
6930 return 0;
6933 ip->lineno = new_lineno;
6934 output_line_directive (ip, op, 0, file_change);
6935 check_expand (op, ip->length - (ip->bufp - ip->buf));
6936 return 0;
6939 /* Remove the definition of a symbol from the symbol table.
6940 according to un*x /lib/cpp, it is not an error to undef
6941 something that has no definitions, so it isn't one here either. */
6943 static int
6944 do_undef (buf, limit, op, keyword)
6945 U_CHAR *buf, *limit;
6946 FILE_BUF *op;
6947 struct directive *keyword;
6949 int sym_length;
6950 HASHNODE *hp;
6951 U_CHAR *orig_buf = buf;
6953 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6954 if (pcp_outfile && op)
6955 pass_thru_directive (buf, limit, op, keyword);
6957 SKIP_WHITE_SPACE (buf);
6958 sym_length = check_macro_name (buf, 0);
6960 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6961 /* If we are generating additional info for debugging (with -g) we
6962 need to pass through all effective #undef directives. */
6963 if (debug_output && op)
6964 pass_thru_directive (orig_buf, limit, op, keyword);
6965 if (hp->type != T_MACRO)
6966 warning ("undefining `%s'", hp->name);
6967 delete_macro (hp);
6970 if (pedantic) {
6971 buf += sym_length;
6972 SKIP_WHITE_SPACE (buf);
6973 if (buf != limit)
6974 pedwarn ("garbage after `#undef' directive");
6976 return 0;
6979 /* Report an error detected by the program we are processing.
6980 Use the text of the line in the error message.
6981 (We use error because it prints the filename & line#.) */
6983 static int
6984 do_error (buf, limit, op, keyword)
6985 U_CHAR *buf, *limit;
6986 FILE_BUF *op ATTRIBUTE_UNUSED;
6987 struct directive *keyword ATTRIBUTE_UNUSED;
6989 int length = limit - buf;
6990 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6991 bcopy ((char *) buf, (char *) copy, length);
6992 copy[length] = 0;
6993 SKIP_WHITE_SPACE (copy);
6994 error ("#error %s", copy);
6995 return 0;
6998 /* Report a warning detected by the program we are processing.
6999 Use the text of the line in the warning message, then continue.
7000 (We use error because it prints the filename & line#.) */
7002 static int
7003 do_warning (buf, limit, op, keyword)
7004 U_CHAR *buf, *limit;
7005 FILE_BUF *op ATTRIBUTE_UNUSED;
7006 struct directive *keyword ATTRIBUTE_UNUSED;
7008 int length = limit - buf;
7009 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7010 bcopy ((char *) buf, (char *) copy, length);
7011 copy[length] = 0;
7012 SKIP_WHITE_SPACE (copy);
7014 if (pedantic && !instack[indepth].system_header_p)
7015 pedwarn ("ANSI C does not allow `#warning'");
7017 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
7018 if -pedantic-errors is given, #warning should cause an error. */
7019 pedwarn ("#warning %s", copy);
7020 return 0;
7023 /* Remember the name of the current file being read from so that we can
7024 avoid ever including it again. */
7026 static void
7027 do_once ()
7029 int i;
7031 for (i = indepth; i >= 0; i--)
7032 if (instack[i].inc) {
7033 record_control_macro (instack[i].inc, (U_CHAR *) "");
7034 break;
7038 /* Report program identification. */
7040 static int
7041 do_ident (buf, limit, op, keyword)
7042 U_CHAR *buf, *limit;
7043 FILE_BUF *op;
7044 struct directive *keyword ATTRIBUTE_UNUSED;
7046 FILE_BUF trybuf;
7047 int len;
7049 /* Allow #ident in system headers, since that's not user's fault. */
7050 if (pedantic && !instack[indepth].system_header_p)
7051 pedwarn ("ANSI C does not allow `#ident'");
7053 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
7054 buf = trybuf.buf;
7055 len = trybuf.bufp - buf;
7057 /* Output expanded directive. */
7058 check_expand (op, 7 + len);
7059 bcopy ("#ident ", (char *) op->bufp, 7);
7060 op->bufp += 7;
7061 bcopy ((char *) buf, (char *) op->bufp, len);
7062 op->bufp += len;
7064 free (buf);
7065 return 0;
7068 /* #pragma and its argument line have already been copied to the output file.
7069 Just check for some recognized pragmas that need validation here. */
7071 static int
7072 do_pragma (buf, limit, op, keyword)
7073 U_CHAR *buf, *limit ATTRIBUTE_UNUSED;
7074 FILE_BUF *op ATTRIBUTE_UNUSED;
7075 struct directive *keyword ATTRIBUTE_UNUSED;
7077 SKIP_WHITE_SPACE (buf);
7078 if (!strncmp ((char *) buf, "once", 4)) {
7079 /* Allow #pragma once in system headers, since that's not the user's
7080 fault. */
7081 if (!instack[indepth].system_header_p)
7082 warning ("`#pragma once' is obsolete");
7083 do_once ();
7086 if (!strncmp ((char *) buf, "implementation", 14)) {
7087 /* Be quiet about `#pragma implementation' for a file only if it hasn't
7088 been included yet. */
7090 int h;
7091 U_CHAR *p = buf + 14, *fname;
7092 SKIP_WHITE_SPACE (p);
7093 if (*p != '\"')
7094 return 0;
7096 fname = p + 1;
7097 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
7098 *p = '\0';
7100 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
7101 struct include_file *inc;
7102 for (inc = include_hashtab[h]; inc; inc = inc->next) {
7103 if (!strcmp (base_name (inc->fname), (char *) fname)) {
7104 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
7105 return 0;
7110 return 0;
7113 #if 0
7114 /* This was a fun hack, but #pragma seems to start to be useful.
7115 By failing to recognize it, we pass it through unchanged to cc1. */
7117 /* The behavior of the #pragma directive is implementation defined.
7118 this implementation defines it as follows. */
7120 static int
7121 do_pragma ()
7123 close (0);
7124 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7125 goto nope;
7126 close (1);
7127 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7128 goto nope;
7129 execl ("/usr/games/hack", "#pragma", 0);
7130 execl ("/usr/games/rogue", "#pragma", 0);
7131 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7132 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7133 nope:
7134 fatal ("You are in a maze of twisty compiler features, all different");
7136 #endif
7138 #ifdef SCCS_DIRECTIVE
7140 /* Just ignore #sccs, on systems where we define it at all. */
7142 static int
7143 do_sccs (buf, limit, op, keyword)
7144 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7145 FILE_BUF *op ATTRIBUTE_UNUSED;
7146 struct directive *keyword ATTRIBUTE_UNUSED;
7148 if (pedantic)
7149 pedwarn ("ANSI C does not allow `#sccs'");
7150 return 0;
7153 #endif /* defined (SCCS_DIRECTIVE) */
7155 /* Handle #if directive by
7156 1) inserting special `defined' keyword into the hash table
7157 that gets turned into 0 or 1 by special_symbol (thus,
7158 if the luser has a symbol called `defined' already, it won't
7159 work inside the #if directive)
7160 2) rescan the input into a temporary output buffer
7161 3) pass the output buffer to the yacc parser and collect a value
7162 4) clean up the mess left from steps 1 and 2.
7163 5) call conditional_skip to skip til the next #endif (etc.),
7164 or not, depending on the value from step 3. */
7166 static int
7167 do_if (buf, limit, op, keyword)
7168 U_CHAR *buf, *limit;
7169 FILE_BUF *op;
7170 struct directive *keyword ATTRIBUTE_UNUSED;
7172 HOST_WIDEST_INT value;
7173 FILE_BUF *ip = &instack[indepth];
7175 value = eval_if_expression (buf, limit - buf);
7176 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7177 return 0;
7180 /* Handle a #elif directive by not changing if_stack either.
7181 see the comment above do_else. */
7183 static int
7184 do_elif (buf, limit, op, keyword)
7185 U_CHAR *buf, *limit;
7186 FILE_BUF *op;
7187 struct directive *keyword ATTRIBUTE_UNUSED;
7189 HOST_WIDEST_INT value;
7190 FILE_BUF *ip = &instack[indepth];
7192 if (if_stack == instack[indepth].if_stack) {
7193 error ("`#elif' not within a conditional");
7194 return 0;
7195 } else {
7196 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7197 error ("`#elif' after `#else'");
7198 fprintf (stderr, " (matches line %d", if_stack->lineno);
7199 if (! (if_stack->fname_len == ip->nominal_fname_len
7200 && !bcmp (if_stack->fname, ip->nominal_fname,
7201 if_stack->fname_len))) {
7202 fprintf (stderr, ", file ");
7203 eprint_string (if_stack->fname, if_stack->fname_len);
7205 fprintf (stderr, ")\n");
7207 if_stack->type = T_ELIF;
7210 if (if_stack->if_succeeded)
7211 skip_if_group (ip, 0, op);
7212 else {
7213 value = eval_if_expression (buf, limit - buf);
7214 if (value == 0)
7215 skip_if_group (ip, 0, op);
7216 else {
7217 ++if_stack->if_succeeded; /* continue processing input */
7218 output_line_directive (ip, op, 1, same_file);
7221 return 0;
7224 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7225 result as a C expression and return the value as an int. */
7227 static HOST_WIDEST_INT
7228 eval_if_expression (buf, length)
7229 U_CHAR *buf;
7230 int length;
7232 FILE_BUF temp_obuf;
7233 HASHNODE *save_defined;
7234 HOST_WIDEST_INT value;
7236 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7237 NULL_PTR, -1);
7238 pcp_inside_if = 1;
7239 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7240 pcp_inside_if = 0;
7241 delete_macro (save_defined); /* clean up special symbol */
7243 temp_obuf.buf[temp_obuf.length] = '\n';
7244 value = parse_c_expression ((char *) temp_obuf.buf,
7245 warn_undef && !instack[indepth].system_header_p);
7247 free (temp_obuf.buf);
7249 return value;
7252 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7253 or don't skip to the #endif/#else/#elif depending on what directive
7254 is actually being processed. */
7256 static int
7257 do_xifdef (buf, limit, op, keyword)
7258 U_CHAR *buf, *limit;
7259 FILE_BUF *op;
7260 struct directive *keyword;
7262 int skip;
7263 FILE_BUF *ip = &instack[indepth];
7264 U_CHAR *end;
7265 int start_of_file = 0;
7266 U_CHAR *control_macro = 0;
7268 /* Detect a #ifndef at start of file (not counting comments). */
7269 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7270 U_CHAR *p = ip->buf;
7271 while (p != directive_start) {
7272 U_CHAR c = *p++;
7273 if (is_space[c])
7275 /* Make no special provision for backslash-newline here; this is
7276 slower if backslash-newlines are present, but it's correct,
7277 and it's not worth it to tune for the rare backslash-newline. */
7278 else if (c == '/'
7279 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7280 /* Skip this comment. */
7281 int junk = 0;
7282 U_CHAR *save_bufp = ip->bufp;
7283 ip->bufp = p + 1;
7284 p = skip_to_end_of_comment (ip, &junk, 1);
7285 ip->bufp = save_bufp;
7286 } else {
7287 goto fail;
7290 /* If we get here, this conditional is the beginning of the file. */
7291 start_of_file = 1;
7292 fail: ;
7295 /* Discard leading and trailing whitespace. */
7296 SKIP_WHITE_SPACE (buf);
7297 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7299 /* Find the end of the identifier at the beginning. */
7300 for (end = buf; is_idchar[*end]; end++);
7302 if (end == buf) {
7303 skip = (keyword->type == T_IFDEF);
7304 if (! traditional)
7305 pedwarn (end == limit ? "`#%s' with no argument"
7306 : "`#%s' argument starts with punctuation",
7307 keyword->name);
7308 } else {
7309 HASHNODE *hp;
7311 if (! traditional) {
7312 if (ISDIGIT (buf[0]))
7313 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7314 else if (end != limit)
7315 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7318 hp = lookup (buf, end-buf, -1);
7320 if (pcp_outfile) {
7321 /* Output a precondition for this macro. */
7322 if (hp
7323 && (hp->type == T_CONST
7324 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7325 fprintf (pcp_outfile, "#define %s\n", hp->name);
7326 else {
7327 U_CHAR *cp = buf;
7328 fprintf (pcp_outfile, "#undef ");
7329 while (is_idchar[*cp]) /* Ick! */
7330 fputc (*cp++, pcp_outfile);
7331 putc ('\n', pcp_outfile);
7335 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7336 if (start_of_file && !skip) {
7337 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7338 bcopy ((char *) buf, (char *) control_macro, end - buf);
7339 control_macro[end - buf] = 0;
7343 conditional_skip (ip, skip, T_IF, control_macro, op);
7344 return 0;
7347 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7348 If this is a #ifndef starting at the beginning of a file,
7349 CONTROL_MACRO is the macro name tested by the #ifndef.
7350 Otherwise, CONTROL_MACRO is 0. */
7352 static void
7353 conditional_skip (ip, skip, type, control_macro, op)
7354 FILE_BUF *ip;
7355 int skip;
7356 enum node_type type;
7357 U_CHAR *control_macro;
7358 FILE_BUF *op;
7360 IF_STACK_FRAME *temp;
7362 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7363 temp->fname = ip->nominal_fname;
7364 temp->fname_len = ip->nominal_fname_len;
7365 temp->lineno = ip->lineno;
7366 temp->next = if_stack;
7367 temp->control_macro = control_macro;
7368 if_stack = temp;
7370 if_stack->type = type;
7372 if (skip != 0) {
7373 skip_if_group (ip, 0, op);
7374 return;
7375 } else {
7376 ++if_stack->if_succeeded;
7377 output_line_directive (ip, &outbuf, 1, same_file);
7381 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7382 Leaves input ptr at the sharp sign found.
7383 If ANY is nonzero, return at next directive of any sort. */
7385 static void
7386 skip_if_group (ip, any, op)
7387 FILE_BUF *ip;
7388 int any;
7389 FILE_BUF *op;
7391 register U_CHAR *bp = ip->bufp, *cp;
7392 register U_CHAR *endb = ip->buf + ip->length;
7393 struct directive *kt;
7394 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7395 U_CHAR *beg_of_line = bp;
7396 register int ident_length;
7397 U_CHAR *ident, *after_ident;
7398 /* Save info about where the group starts. */
7399 U_CHAR *beg_of_group = bp;
7400 int beg_lineno = ip->lineno;
7401 int skipping_include_directive = 0;
7403 if (output_conditionals && op != 0) {
7404 char *ptr = "#failed\n";
7405 int len = strlen (ptr);
7407 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7409 *op->bufp++ = '\n';
7410 op->lineno++;
7412 check_expand (op, len);
7413 bcopy (ptr, (char *) op->bufp, len);
7414 op->bufp += len;
7415 op->lineno++;
7416 output_line_directive (ip, op, 1, 0);
7419 while (bp < endb) {
7420 switch (*bp++) {
7421 case '/': /* possible comment */
7422 if (*bp == '\\' && bp[1] == '\n')
7423 newline_fix (bp);
7424 if (*bp == '*'
7425 || (cplusplus_comments && *bp == '/')) {
7426 ip->bufp = ++bp;
7427 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7429 break;
7430 case '<':
7431 if (skipping_include_directive) {
7432 while (bp < endb && *bp != '>' && *bp != '\n') {
7433 if (*bp == '\\' && bp[1] == '\n') {
7434 ip->lineno++;
7435 bp++;
7437 bp++;
7440 break;
7441 case '\"':
7442 if (skipping_include_directive) {
7443 while (bp < endb && *bp != '\n') {
7444 if (*bp == '"') {
7445 bp++;
7446 break;
7448 if (*bp == '\\' && bp[1] == '\n') {
7449 ip->lineno++;
7450 bp++;
7452 bp++;
7454 break;
7456 /* Fall through. */
7457 case '\'':
7458 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7459 NULL_PTR, NULL_PTR);
7460 break;
7461 case '\\':
7462 /* Char after backslash loses its special meaning in some cases. */
7463 if (*bp == '\n') {
7464 ++ip->lineno;
7465 bp++;
7466 } else if (traditional && bp < endb)
7467 bp++;
7468 break;
7469 case '\n':
7470 ++ip->lineno;
7471 beg_of_line = bp;
7472 skipping_include_directive = 0;
7473 break;
7474 case '%':
7475 if (beg_of_line == 0 || traditional)
7476 break;
7477 ip->bufp = bp - 1;
7478 while (bp[0] == '\\' && bp[1] == '\n')
7479 bp += 2;
7480 if (*bp == ':')
7481 goto sharp_token;
7482 break;
7483 case '#':
7484 /* # keyword: a # must be first nonblank char on the line */
7485 if (beg_of_line == 0)
7486 break;
7487 ip->bufp = bp - 1;
7488 sharp_token:
7489 /* Scan from start of line, skipping whitespace, comments
7490 and backslash-newlines, and see if we reach this #.
7491 If not, this # is not special. */
7492 bp = beg_of_line;
7493 /* If -traditional, require # to be at beginning of line. */
7494 if (!traditional) {
7495 while (1) {
7496 if (is_hor_space[*bp])
7497 bp++;
7498 else if (*bp == '\\' && bp[1] == '\n')
7499 bp += 2;
7500 else if (*bp == '/' && bp[1] == '*') {
7501 bp += 2;
7502 while (1)
7504 if (*bp == '*')
7506 if (bp[1] == '/')
7508 bp += 2;
7509 break;
7512 else
7514 #ifdef MULTIBYTE_CHARS
7515 int length;
7516 length = local_mblen (bp, endb - bp);
7517 if (length > 1)
7518 bp += (length - 1);
7519 #endif
7521 bp++;
7524 /* There is no point in trying to deal with C++ // comments here,
7525 because if there is one, then this # must be part of the
7526 comment and we would never reach here. */
7527 else break;
7530 if (bp != ip->bufp) {
7531 bp = ip->bufp + 1; /* Reset bp to after the #. */
7532 break;
7535 bp = ip->bufp + 1; /* Point after the '#' */
7536 if (ip->bufp[0] == '%') {
7537 /* Skip past the ':' again. */
7538 while (*bp == '\\') {
7539 ip->lineno++;
7540 bp += 2;
7542 bp++;
7545 /* Skip whitespace and \-newline. */
7546 while (1) {
7547 if (is_hor_space[*bp])
7548 bp++;
7549 else if (*bp == '\\' && bp[1] == '\n')
7550 bp += 2;
7551 else if (*bp == '/') {
7552 if (bp[1] == '\\' && bp[2] == '\n')
7553 newline_fix (bp + 1);
7554 if (bp[1] == '*') {
7555 for (bp += 2; ; bp++) {
7556 if (*bp == '\n')
7557 ip->lineno++;
7558 else if (*bp == '*') {
7559 if (bp[-1] == '/' && warn_comments)
7560 warning ("`/*' within comment");
7561 if (bp[1] == '\\' && bp[2] == '\n')
7562 newline_fix (bp + 1);
7563 if (bp[1] == '/')
7564 break;
7566 else
7568 #ifdef MULTIBYTE_CHARS
7569 int length;
7570 length = local_mblen (bp, endb - bp);
7571 if (length > 1)
7572 bp += (length - 1);
7573 #endif
7576 bp += 2;
7577 } else if (bp[1] == '/' && cplusplus_comments) {
7578 for (bp += 2; ; bp++) {
7579 if (*bp == '\n')
7580 break;
7581 if (*bp == '\\' && bp[1] == '\n')
7583 if (warn_comments)
7584 warning ("multiline `//' comment");
7585 ip->lineno++;
7586 bp++;
7588 else
7590 #ifdef MULTIBYTE_CHARS
7591 int length;
7592 length = local_mblen (bp, endb - bp);
7593 if (length > 1)
7594 bp += (length - 1);
7595 #endif
7598 } else
7599 break;
7600 } else
7601 break;
7604 cp = bp;
7606 /* Now find end of directive name.
7607 If we encounter a backslash-newline, exchange it with any following
7608 symbol-constituents so that we end up with a contiguous name. */
7610 while (1) {
7611 if (is_idchar[*bp])
7612 bp++;
7613 else {
7614 if (*bp == '\\' && bp[1] == '\n')
7615 name_newline_fix (bp);
7616 if (is_idchar[*bp])
7617 bp++;
7618 else break;
7621 ident_length = bp - cp;
7622 ident = cp;
7623 after_ident = bp;
7625 /* A line of just `#' becomes blank. */
7627 if (ident_length == 0 && *after_ident == '\n') {
7628 continue;
7631 if (ident_length == 0 || !is_idstart[*ident]) {
7632 U_CHAR *p = ident;
7633 while (is_idchar[*p]) {
7634 if (*p < '0' || *p > '9')
7635 break;
7636 p++;
7638 /* Handle # followed by a line number. */
7639 if (p != ident && !is_idchar[*p]) {
7640 if (pedantic)
7641 pedwarn ("`#' followed by integer");
7642 continue;
7645 /* Avoid error for `###' and similar cases unless -pedantic. */
7646 if (p == ident) {
7647 while (*p == '#' || is_hor_space[*p]) p++;
7648 if (*p == '\n') {
7649 if (pedantic && !lang_asm)
7650 pedwarn ("invalid preprocessing directive");
7651 continue;
7655 if (!lang_asm && pedantic)
7656 pedwarn ("invalid preprocessing directive name");
7657 continue;
7660 for (kt = directive_table; kt->length >= 0; kt++) {
7661 IF_STACK_FRAME *temp;
7662 if (ident_length == kt->length
7663 && bcmp (cp, kt->name, kt->length) == 0) {
7664 /* If we are asked to return on next directive, do so now. */
7665 if (any)
7666 goto done;
7668 switch (kt->type) {
7669 case T_IF:
7670 case T_IFDEF:
7671 case T_IFNDEF:
7672 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7673 temp->next = if_stack;
7674 if_stack = temp;
7675 temp->lineno = ip->lineno;
7676 temp->fname = ip->nominal_fname;
7677 temp->fname_len = ip->nominal_fname_len;
7678 temp->type = kt->type;
7679 break;
7680 case T_ELSE:
7681 case T_ENDIF:
7682 if (pedantic && if_stack != save_if_stack)
7683 validate_else (bp, endb);
7684 case T_ELIF:
7685 if (if_stack == instack[indepth].if_stack) {
7686 error ("`#%s' not within a conditional", kt->name);
7687 break;
7689 else if (if_stack == save_if_stack)
7690 goto done; /* found what we came for */
7692 if (kt->type != T_ENDIF) {
7693 if (if_stack->type == T_ELSE)
7694 error ("`#else' or `#elif' after `#else'");
7695 if_stack->type = kt->type;
7696 break;
7699 temp = if_stack;
7700 if_stack = if_stack->next;
7701 free (temp);
7702 break;
7704 case T_INCLUDE:
7705 case T_INCLUDE_NEXT:
7706 case T_IMPORT:
7707 skipping_include_directive = 1;
7708 break;
7710 default:
7711 break;
7713 break;
7716 /* Don't let erroneous code go by. */
7717 if (kt->length < 0 && !lang_asm && pedantic)
7718 pedwarn ("invalid preprocessing directive name");
7722 ip->bufp = bp;
7723 /* after this returns, rescan will exit because ip->bufp
7724 now points to the end of the buffer.
7725 rescan is responsible for the error message also. */
7727 done:
7728 if (output_conditionals && op != 0) {
7729 char *ptr = "#endfailed\n";
7730 int len = strlen (ptr);
7732 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7734 *op->bufp++ = '\n';
7735 op->lineno++;
7737 check_expand (op, beg_of_line - beg_of_group);
7738 bcopy ((char *) beg_of_group, (char *) op->bufp,
7739 beg_of_line - beg_of_group);
7740 op->bufp += beg_of_line - beg_of_group;
7741 op->lineno += ip->lineno - beg_lineno;
7742 check_expand (op, len);
7743 bcopy (ptr, (char *) op->bufp, len);
7744 op->bufp += len;
7745 op->lineno++;
7749 /* Handle a #else directive. Do this by just continuing processing
7750 without changing if_stack ; this is so that the error message
7751 for missing #endif's etc. will point to the original #if. It
7752 is possible that something different would be better. */
7754 static int
7755 do_else (buf, limit, op, keyword)
7756 U_CHAR *buf, *limit;
7757 FILE_BUF *op;
7758 struct directive *keyword ATTRIBUTE_UNUSED;
7760 FILE_BUF *ip = &instack[indepth];
7762 if (pedantic) {
7763 SKIP_WHITE_SPACE (buf);
7764 if (buf != limit)
7765 pedwarn ("text following `#else' violates ANSI standard");
7768 if (if_stack == instack[indepth].if_stack) {
7769 error ("`#else' not within a conditional");
7770 return 0;
7771 } else {
7772 /* #ifndef can't have its special treatment for containing the whole file
7773 if it has a #else clause. */
7774 if_stack->control_macro = 0;
7776 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7777 error ("`#else' after `#else'");
7778 fprintf (stderr, " (matches line %d", if_stack->lineno);
7779 if (! (if_stack->fname_len == ip->nominal_fname_len
7780 && !bcmp (if_stack->fname, ip->nominal_fname,
7781 if_stack->fname_len))) {
7782 fprintf (stderr, ", file ");
7783 eprint_string (if_stack->fname, if_stack->fname_len);
7785 fprintf (stderr, ")\n");
7787 if_stack->type = T_ELSE;
7790 if (if_stack->if_succeeded)
7791 skip_if_group (ip, 0, op);
7792 else {
7793 ++if_stack->if_succeeded; /* continue processing input */
7794 output_line_directive (ip, op, 1, same_file);
7796 return 0;
7799 /* Unstack after #endif directive. */
7801 static int
7802 do_endif (buf, limit, op, keyword)
7803 U_CHAR *buf, *limit;
7804 FILE_BUF *op;
7805 struct directive *keyword ATTRIBUTE_UNUSED;
7807 if (pedantic) {
7808 SKIP_WHITE_SPACE (buf);
7809 if (buf != limit)
7810 pedwarn ("text following `#endif' violates ANSI standard");
7813 if (if_stack == instack[indepth].if_stack)
7814 error ("unbalanced `#endif'");
7815 else {
7816 IF_STACK_FRAME *temp = if_stack;
7817 if_stack = if_stack->next;
7818 if (temp->control_macro != 0) {
7819 /* This #endif matched a #ifndef at the start of the file.
7820 See if it is at the end of the file. */
7821 FILE_BUF *ip = &instack[indepth];
7822 U_CHAR *p = ip->bufp;
7823 U_CHAR *ep = ip->buf + ip->length;
7825 while (p != ep) {
7826 U_CHAR c = *p++;
7827 if (!is_space[c]) {
7828 if (c == '/'
7829 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7830 /* Skip this comment. */
7831 int junk = 0;
7832 U_CHAR *save_bufp = ip->bufp;
7833 ip->bufp = p + 1;
7834 p = skip_to_end_of_comment (ip, &junk, 1);
7835 ip->bufp = save_bufp;
7836 } else
7837 goto fail;
7840 /* If we get here, this #endif ends a #ifndef
7841 that contains all of the file (aside from whitespace).
7842 Arrange not to include the file again
7843 if the macro that was tested is defined.
7845 Do not do this for the top-level file in a -include or any
7846 file in a -imacros. */
7847 if (indepth != 0
7848 && ! (indepth == 1 && no_record_file)
7849 && ! (no_record_file && no_output))
7850 record_control_macro (ip->inc, temp->control_macro);
7851 fail: ;
7853 free (temp);
7854 output_line_directive (&instack[indepth], op, 1, same_file);
7856 return 0;
7859 /* When an #else or #endif is found while skipping failed conditional,
7860 if -pedantic was specified, this is called to warn about text after
7861 the directive name. P points to the first char after the directive
7862 name. */
7864 static void
7865 validate_else (p, limit)
7866 register U_CHAR *p;
7867 register U_CHAR *limit;
7869 /* Advance P over whitespace and comments. */
7870 while (1) {
7871 while (*p == '\\' && p[1] == '\n')
7872 p += 2;
7873 if (is_hor_space[*p])
7874 p++;
7875 else if (*p == '/') {
7876 while (p[1] == '\\' && p[2] == '\n')
7877 p += 2;
7878 if (p[1] == '*') {
7879 /* Don't bother warning about unterminated comments
7880 since that will happen later. Just be sure to exit. */
7881 for (p += 2; ; p++) {
7882 if (p == limit)
7883 return;
7884 if (*p == '*') {
7885 while (p[1] == '\\' && p[2] == '\n')
7886 p += 2;
7887 if (p[1] == '/') {
7888 p += 2;
7889 break;
7892 else
7894 #ifdef MULTIBYTE_CHARS
7895 int length;
7896 length = local_mblen (p, limit - p);
7897 if (length > 1)
7898 p += (length - 1);
7899 #endif
7903 else if (cplusplus_comments && p[1] == '/')
7904 return;
7905 else break;
7906 } else break;
7908 if (*p != '\n')
7909 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7912 /* Skip a comment, assuming the input ptr immediately follows the
7913 initial slash-star. Bump *LINE_COUNTER for each newline.
7914 (The canonical line counter is &ip->lineno.)
7915 Don't use this routine (or the next one) if bumping the line
7916 counter is not sufficient to deal with newlines in the string.
7918 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7919 This feature is useful when processing a comment that is going to
7920 be processed or was processed at another point in the preprocessor,
7921 to avoid a duplicate warning. Likewise for unterminated comment
7922 errors. */
7924 static U_CHAR *
7925 skip_to_end_of_comment (ip, line_counter, nowarn)
7926 register FILE_BUF *ip;
7927 int *line_counter; /* place to remember newlines, or NULL */
7928 int nowarn;
7930 register U_CHAR *limit = ip->buf + ip->length;
7931 register U_CHAR *bp = ip->bufp;
7932 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7933 int start_line = line_counter ? *line_counter : 0;
7935 /* JF this line_counter stuff is a crock to make sure the
7936 comment is only put out once, no matter how many times
7937 the comment is skipped. It almost works */
7938 if (op) {
7939 *op->bufp++ = '/';
7940 *op->bufp++ = bp[-1];
7942 if (cplusplus_comments && bp[-1] == '/') {
7943 for (; bp < limit; bp++) {
7944 if (*bp == '\n')
7945 break;
7946 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
7948 if (!nowarn && warn_comments)
7949 warning ("multiline `//' comment");
7950 if (line_counter)
7951 ++*line_counter;
7952 if (op)
7954 ++op->lineno;
7955 *op->bufp++ = *bp;
7957 ++bp;
7959 else
7961 #ifdef MULTIBYTE_CHARS
7962 int length;
7963 length = local_mblen (bp, limit - bp);
7964 if (length > 1)
7966 if (op)
7968 bcopy (bp, op->bufp, length - 1);
7969 op->bufp += (length - 1);
7971 bp += (length - 1);
7973 #endif
7975 if (op)
7976 *op->bufp++ = *bp;
7978 ip->bufp = bp;
7979 return bp;
7981 while (bp < limit) {
7982 if (op)
7983 *op->bufp++ = *bp;
7984 switch (*bp++) {
7985 case '\n':
7986 /* If this is the end of the file, we have an unterminated comment.
7987 Don't swallow the newline. We are guaranteed that there will be a
7988 trailing newline and various pieces assume it's there. */
7989 if (bp == limit)
7991 --bp;
7992 --limit;
7993 break;
7995 if (line_counter != NULL)
7996 ++*line_counter;
7997 if (op)
7998 ++op->lineno;
7999 break;
8000 case '*':
8001 if (bp[-2] == '/' && !nowarn && warn_comments)
8002 warning ("`/*' within comment");
8003 if (*bp == '\\' && bp[1] == '\n')
8004 newline_fix (bp);
8005 if (*bp == '/') {
8006 if (op)
8007 *op->bufp++ = '/';
8008 ip->bufp = ++bp;
8009 return bp;
8011 break;
8012 #ifdef MULTIBYTE_CHARS
8013 default:
8015 int length;
8016 bp--;
8017 length = local_mblen (bp, limit - bp);
8018 if (length <= 0)
8019 length = 1;
8020 if (op)
8022 op->bufp--;
8023 bcopy (bp, op->bufp, length);
8024 op->bufp += length;
8026 bp += length;
8028 #endif
8032 if (!nowarn)
8033 error_with_line (line_for_error (start_line), "unterminated comment");
8034 ip->bufp = bp;
8035 return bp;
8038 /* Skip over a quoted string. BP points to the opening quote.
8039 Returns a pointer after the closing quote. Don't go past LIMIT.
8040 START_LINE is the line number of the starting point (but it need
8041 not be valid if the starting point is inside a macro expansion).
8043 The input stack state is not changed.
8045 If COUNT_NEWLINES is nonzero, it points to an int to increment
8046 for each newline passed.
8048 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
8049 if we pass a backslash-newline.
8051 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
8053 static U_CHAR *
8054 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
8055 register U_CHAR *bp;
8056 register U_CHAR *limit;
8057 int start_line;
8058 int *count_newlines;
8059 int *backslash_newlines_p;
8060 int *eofp;
8062 register U_CHAR c, match;
8064 match = *bp++;
8065 while (1) {
8066 if (bp >= limit) {
8067 error_with_line (line_for_error (start_line),
8068 "unterminated string or character constant");
8069 error_with_line (multiline_string_line,
8070 "possible real start of unterminated constant");
8071 multiline_string_line = 0;
8072 if (eofp)
8073 *eofp = 1;
8074 break;
8076 c = *bp++;
8077 if (c == '\\') {
8078 while (*bp == '\\' && bp[1] == '\n') {
8079 if (backslash_newlines_p)
8080 *backslash_newlines_p = 1;
8081 if (count_newlines)
8082 ++*count_newlines;
8083 bp += 2;
8085 if (*bp == '\n') {
8086 if (backslash_newlines_p)
8087 *backslash_newlines_p = 1;
8088 if (count_newlines)
8089 ++*count_newlines;
8091 bp++;
8092 } else if (c == '\n') {
8093 if (traditional) {
8094 /* Unterminated strings and character constants are 'valid'. */
8095 bp--; /* Don't consume the newline. */
8096 if (eofp)
8097 *eofp = 1;
8098 break;
8100 if (match == '\'') {
8101 error_with_line (line_for_error (start_line),
8102 "unterminated string or character constant");
8103 bp--;
8104 if (eofp)
8105 *eofp = 1;
8106 break;
8108 /* If not traditional, then allow newlines inside strings. */
8109 if (count_newlines)
8110 ++*count_newlines;
8111 if (multiline_string_line == 0) {
8112 if (pedantic)
8113 pedwarn_with_line (line_for_error (start_line),
8114 "string constant runs past end of line");
8115 multiline_string_line = start_line;
8117 } else if (c == match)
8118 break;
8119 #ifdef MULTIBYTE_CHARS
8121 int length;
8122 --bp;
8123 length = local_mblen (bp, limit - bp);
8124 if (length <= 0)
8125 length = 1;
8126 bp += length;
8128 #endif
8130 return bp;
8133 /* Place into DST a quoted string representing the string SRC.
8134 SRCLEN is the length of SRC; SRC may contain null bytes.
8135 Return the address of DST's terminating null. */
8137 static char *
8138 quote_string (dst, src, srclen)
8139 char *dst, *src;
8140 size_t srclen;
8142 U_CHAR c;
8143 char *srclim = src + srclen;
8145 *dst++ = '\"';
8146 while (src != srclim)
8147 switch ((c = *src++))
8149 default:
8150 if (ISPRINT (c))
8151 *dst++ = c;
8152 else
8154 sprintf (dst, "\\%03o", c);
8155 dst += 4;
8157 break;
8159 case '\"':
8160 case '\\':
8161 *dst++ = '\\';
8162 *dst++ = c;
8163 break;
8166 *dst++ = '\"';
8167 *dst = '\0';
8168 return dst;
8171 /* Skip across a group of balanced parens, starting from IP->bufp.
8172 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
8174 This does not handle newlines, because it's used for the arg of #if,
8175 where there aren't any newlines. Also, backslash-newline can't appear. */
8177 static U_CHAR *
8178 skip_paren_group (ip)
8179 register FILE_BUF *ip;
8181 U_CHAR *limit = ip->buf + ip->length;
8182 U_CHAR *p = ip->bufp;
8183 int depth = 0;
8184 int lines_dummy = 0;
8186 while (p != limit) {
8187 int c = *p++;
8188 switch (c) {
8189 case '(':
8190 depth++;
8191 break;
8193 case ')':
8194 depth--;
8195 if (depth == 0)
8196 return ip->bufp = p;
8197 break;
8199 case '/':
8200 if (*p == '*') {
8201 ip->bufp = p;
8202 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
8203 p = ip->bufp;
8206 case '"':
8207 case '\'':
8209 int eofp = 0;
8210 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
8211 if (eofp)
8212 return ip->bufp = p;
8214 break;
8218 ip->bufp = p;
8219 return p;
8222 /* Write out a #line directive, for instance, after an #include file.
8223 If CONDITIONAL is nonzero, we can omit the #line if it would
8224 appear to be a no-op, and we can output a few newlines instead
8225 if we want to increase the line number by a small amount.
8226 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
8228 static void
8229 output_line_directive (ip, op, conditional, file_change)
8230 FILE_BUF *ip, *op;
8231 int conditional;
8232 enum file_change_code file_change;
8234 int len;
8235 char *line_directive_buf, *line_end;
8237 if (no_line_directives
8238 || ip->fname == NULL
8239 || no_output) {
8240 op->lineno = ip->lineno;
8241 return;
8244 if (conditional) {
8245 if (ip->lineno == op->lineno)
8246 return;
8248 /* If the inherited line number is a little too small,
8249 output some newlines instead of a #line directive. */
8250 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8251 check_expand (op, 10);
8252 while (ip->lineno > op->lineno) {
8253 *op->bufp++ = '\n';
8254 op->lineno++;
8256 return;
8260 /* Output a positive line number if possible. */
8261 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8262 && *ip->bufp == '\n') {
8263 ip->lineno++;
8264 ip->bufp++;
8267 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8268 sprintf (line_directive_buf, "# %d ", ip->lineno);
8269 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8270 ip->nominal_fname, ip->nominal_fname_len);
8271 if (file_change != same_file) {
8272 *line_end++ = ' ';
8273 *line_end++ = file_change == enter_file ? '1' : '2';
8275 /* Tell cc1 if following text comes from a system header file. */
8276 if (ip->system_header_p) {
8277 *line_end++ = ' ';
8278 *line_end++ = '3';
8280 #ifndef NO_IMPLICIT_EXTERN_C
8281 /* Tell cc1plus if following text should be treated as C. */
8282 if (ip->system_header_p == 2 && cplusplus) {
8283 *line_end++ = ' ';
8284 *line_end++ = '4';
8286 #endif
8287 *line_end++ = '\n';
8288 len = line_end - line_directive_buf;
8289 check_expand (op, len + 1);
8290 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8291 *op->bufp++ = '\n';
8292 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8293 op->bufp += len;
8294 op->lineno = ip->lineno;
8297 /* This structure represents one parsed argument in a macro call.
8298 `raw' points to the argument text as written (`raw_length' is its length).
8299 `expanded' points to the argument's macro-expansion
8300 (its length is `expand_length').
8301 `stringified_length' is the length the argument would have
8302 if stringified.
8303 `use_count' is the number of times this macro arg is substituted
8304 into the macro. If the actual use count exceeds 10,
8305 the value stored is 10.
8306 `free1' and `free2', if nonzero, point to blocks to be freed
8307 when the macro argument data is no longer needed. */
8309 struct argdata {
8310 U_CHAR *raw, *expanded;
8311 int raw_length, expand_length;
8312 int stringified_length;
8313 U_CHAR *free1, *free2;
8314 char newlines;
8315 char use_count;
8318 /* Expand a macro call.
8319 HP points to the symbol that is the macro being called.
8320 Put the result of expansion onto the input stack
8321 so that subsequent input by our caller will use it.
8323 If macro wants arguments, caller has already verified that
8324 an argument list follows; arguments come from the input stack. */
8326 static void
8327 macroexpand (hp, op)
8328 HASHNODE *hp;
8329 FILE_BUF *op;
8331 int nargs;
8332 DEFINITION *defn = hp->value.defn;
8333 register U_CHAR *xbuf;
8334 int xbuf_len;
8335 int start_line = instack[indepth].lineno;
8336 int rest_args, rest_zero;
8338 CHECK_DEPTH (return;);
8340 /* it might not actually be a macro. */
8341 if (hp->type != T_MACRO) {
8342 special_symbol (hp, op);
8343 return;
8346 /* This macro is being used inside a #if, which means it must be */
8347 /* recorded as a precondition. */
8348 if (pcp_inside_if && pcp_outfile && defn->predefined)
8349 dump_single_macro (hp, pcp_outfile);
8351 nargs = defn->nargs;
8353 if (nargs >= 0) {
8354 register int i;
8355 struct argdata *args;
8356 int parse_error = 0;
8358 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8360 for (i = 0; i < nargs; i++) {
8361 args[i].raw = (U_CHAR *) "";
8362 args[i].expanded = 0;
8363 args[i].raw_length = args[i].expand_length
8364 = args[i].stringified_length = 0;
8365 args[i].free1 = args[i].free2 = 0;
8366 args[i].use_count = 0;
8369 /* Parse all the macro args that are supplied. I counts them.
8370 The first NARGS args are stored in ARGS.
8371 The rest are discarded.
8372 If rest_args is set then we assume macarg absorbed the rest of the args.
8374 i = 0;
8375 rest_args = 0;
8376 do {
8377 /* Discard the open-parenthesis or comma before the next arg. */
8378 ++instack[indepth].bufp;
8379 if (rest_args)
8380 continue;
8381 if (i < nargs || (nargs == 0 && i == 0)) {
8382 /* If we are working on last arg which absorbs rest of args... */
8383 if (i == nargs - 1 && defn->rest_args)
8384 rest_args = 1;
8385 parse_error = macarg (&args[i], rest_args);
8387 else
8388 parse_error = macarg (NULL_PTR, 0);
8389 if (parse_error) {
8390 error_with_line (line_for_error (start_line),
8391 "unterminated macro call");
8392 break;
8394 i++;
8395 } while (*instack[indepth].bufp != ')');
8397 /* If we got one arg but it was just whitespace, call that 0 args. */
8398 if (i == 1) {
8399 register U_CHAR *bp = args[0].raw;
8400 register U_CHAR *lim = bp + args[0].raw_length;
8401 /* cpp.texi says for foo ( ) we provide one argument.
8402 However, if foo wants just 0 arguments, treat this as 0. */
8403 if (nargs == 0)
8404 while (bp != lim && is_space[*bp]) bp++;
8405 if (bp == lim)
8406 i = 0;
8409 /* Don't output an error message if we have already output one for
8410 a parse error above. */
8411 rest_zero = 0;
8412 if (nargs == 0 && i > 0) {
8413 if (! parse_error)
8414 error ("arguments given to macro `%s'", hp->name);
8415 } else if (i < nargs) {
8416 /* traditional C allows foo() if foo wants one argument. */
8417 if (nargs == 1 && i == 0 && traditional)
8419 /* the rest args token is allowed to absorb 0 tokens */
8420 else if (i == nargs - 1 && defn->rest_args)
8421 rest_zero = 1;
8422 else if (parse_error)
8424 else if (i == 0)
8425 error ("macro `%s' used without args", hp->name);
8426 else if (i == 1)
8427 error ("macro `%s' used with just one arg", hp->name);
8428 else
8429 error ("macro `%s' used with only %d args", hp->name, i);
8430 } else if (i > nargs) {
8431 if (! parse_error)
8432 error ("macro `%s' used with too many (%d) args", hp->name, i);
8435 /* Swallow the closeparen. */
8436 ++instack[indepth].bufp;
8438 /* If macro wants zero args, we parsed the arglist for checking only.
8439 Read directly from the macro definition. */
8440 if (nargs == 0) {
8441 xbuf = defn->expansion;
8442 xbuf_len = defn->length;
8443 } else {
8444 register U_CHAR *exp = defn->expansion;
8445 register int offset; /* offset in expansion,
8446 copied a piece at a time */
8447 register int totlen; /* total amount of exp buffer filled so far */
8449 register struct reflist *ap, *last_ap;
8451 /* Macro really takes args. Compute the expansion of this call. */
8453 /* Compute length in characters of the macro's expansion.
8454 Also count number of times each arg is used. */
8455 xbuf_len = defn->length;
8456 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8457 if (ap->stringify)
8458 xbuf_len += args[ap->argno].stringified_length;
8459 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8460 /* Add 4 for two newline-space markers to prevent
8461 token concatenation. */
8462 xbuf_len += args[ap->argno].raw_length + 4;
8463 else {
8464 /* We have an ordinary (expanded) occurrence of the arg.
8465 So compute its expansion, if we have not already. */
8466 if (args[ap->argno].expanded == 0) {
8467 FILE_BUF obuf;
8468 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8469 args[ap->argno].raw + args[ap->argno].raw_length,
8470 1, 0);
8472 args[ap->argno].expanded = obuf.buf;
8473 args[ap->argno].expand_length = obuf.length;
8474 args[ap->argno].free2 = obuf.buf;
8477 /* Add 4 for two newline-space markers to prevent
8478 token concatenation. */
8479 xbuf_len += args[ap->argno].expand_length + 4;
8481 if (args[ap->argno].use_count < 10)
8482 args[ap->argno].use_count++;
8485 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8487 /* Generate in XBUF the complete expansion
8488 with arguments substituted in.
8489 TOTLEN is the total size generated so far.
8490 OFFSET is the index in the definition
8491 of where we are copying from. */
8492 offset = totlen = 0;
8493 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8494 last_ap = ap, ap = ap->next) {
8495 register struct argdata *arg = &args[ap->argno];
8496 int count_before = totlen;
8498 /* Add chars to XBUF. */
8499 for (i = 0; i < ap->nchars; i++, offset++)
8500 xbuf[totlen++] = exp[offset];
8502 /* If followed by an empty rest arg with concatenation,
8503 delete the last run of nonwhite chars. */
8504 if (rest_zero && totlen > count_before
8505 && ((ap->rest_args && ap->raw_before != 0)
8506 || (last_ap != NULL && last_ap->rest_args
8507 && last_ap->raw_after != 0))) {
8508 /* Delete final whitespace. */
8509 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8510 totlen--;
8513 /* Delete the nonwhites before them. */
8514 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8515 totlen--;
8519 if (ap->stringify != 0) {
8520 int arglen = arg->raw_length;
8521 int escaped = 0;
8522 int in_string = 0;
8523 int c;
8524 i = 0;
8525 while (i < arglen
8526 && (c = arg->raw[i], is_space[c]))
8527 i++;
8528 while (i < arglen
8529 && (c = arg->raw[arglen - 1], is_space[c]))
8530 arglen--;
8531 if (!traditional)
8532 xbuf[totlen++] = '\"'; /* insert beginning quote */
8533 for (; i < arglen; i++) {
8534 c = arg->raw[i];
8536 if (! in_string) {
8537 /* Special markers Newline Space
8538 generate nothing for a stringified argument. */
8539 if (c == '\n' && arg->raw[i+1] != '\n') {
8540 i++;
8541 continue;
8544 /* Internal sequences of whitespace are replaced by one space
8545 except within an string or char token. */
8546 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8547 while (1) {
8548 /* Note that Newline Space does occur within whitespace
8549 sequences; consider it part of the sequence. */
8550 if (c == '\n' && is_space[arg->raw[i+1]])
8551 i += 2;
8552 else if (c != '\n' && is_space[c])
8553 i++;
8554 else break;
8555 c = arg->raw[i];
8557 i--;
8558 c = ' ';
8562 if (escaped)
8563 escaped = 0;
8564 else {
8565 if (c == '\\')
8566 escaped = 1;
8567 else if (in_string) {
8568 if (c == in_string)
8569 in_string = 0;
8570 else
8572 #ifdef MULTIBYTE_CHARS
8573 int length;
8574 length = local_mblen (arg->raw + i, arglen - i);
8575 if (length > 1)
8577 bcopy (arg->raw + i, xbuf + totlen, length);
8578 i += length - 1;
8579 totlen += length;
8580 continue;
8582 #endif
8584 } else if (c == '\"' || c == '\'')
8585 in_string = c;
8588 /* Escape these chars */
8589 if (c == '\"' || (in_string && c == '\\'))
8590 xbuf[totlen++] = '\\';
8591 /* We used to output e.g. \008 for control characters here,
8592 but this doesn't conform to the C Standard.
8593 Just output the characters as-is. */
8594 xbuf[totlen++] = c;
8596 if (!traditional)
8597 xbuf[totlen++] = '\"'; /* insert ending quote */
8598 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8599 U_CHAR *p1 = arg->raw;
8600 U_CHAR *l1 = p1 + arg->raw_length;
8601 if (ap->raw_before != 0) {
8602 while (p1 != l1 && is_space[*p1]) p1++;
8603 while (p1 != l1 && is_idchar[*p1])
8604 xbuf[totlen++] = *p1++;
8605 /* Delete any no-reexpansion marker that follows
8606 an identifier at the beginning of the argument
8607 if the argument is concatenated with what precedes it. */
8608 if (p1[0] == '\n' && p1[1] == '-')
8609 p1 += 2;
8610 } else if (!traditional) {
8611 /* Ordinary expanded use of the argument.
8612 Put in newline-space markers to prevent token pasting. */
8613 xbuf[totlen++] = '\n';
8614 xbuf[totlen++] = ' ';
8616 if (ap->raw_after != 0) {
8617 /* Arg is concatenated after: delete trailing whitespace,
8618 whitespace markers, and no-reexpansion markers. */
8619 while (p1 != l1) {
8620 if (is_space[l1[-1]]) l1--;
8621 else if (l1[-1] == '-') {
8622 U_CHAR *p2 = l1 - 1;
8623 /* If a `-' is preceded by an odd number of newlines then it
8624 and the last newline are a no-reexpansion marker. */
8625 while (p2 != p1 && p2[-1] == '\n') p2--;
8626 if ((l1 - 1 - p2) & 1) {
8627 l1 -= 2;
8629 else break;
8631 else break;
8635 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8636 totlen += l1 - p1;
8637 if (!traditional && ap->raw_after == 0) {
8638 /* Ordinary expanded use of the argument.
8639 Put in newline-space markers to prevent token pasting. */
8640 xbuf[totlen++] = '\n';
8641 xbuf[totlen++] = ' ';
8643 } else {
8644 /* Ordinary expanded use of the argument.
8645 Put in newline-space markers to prevent token pasting. */
8646 if (!traditional) {
8647 xbuf[totlen++] = '\n';
8648 xbuf[totlen++] = ' ';
8650 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8651 arg->expand_length);
8652 totlen += arg->expand_length;
8653 if (!traditional) {
8654 xbuf[totlen++] = '\n';
8655 xbuf[totlen++] = ' ';
8657 /* If a macro argument with newlines is used multiple times,
8658 then only expand the newlines once. This avoids creating output
8659 lines which don't correspond to any input line, which confuses
8660 gdb and gcov. */
8661 if (arg->use_count > 1 && arg->newlines > 0) {
8662 /* Don't bother doing change_newlines for subsequent
8663 uses of arg. */
8664 arg->use_count = 1;
8665 arg->expand_length
8666 = change_newlines (arg->expanded, arg->expand_length);
8670 if (totlen > xbuf_len)
8671 abort ();
8674 /* If there is anything left of the definition after handling
8675 the arg list, copy that in too. */
8677 for (i = offset; i < defn->length; i++) {
8678 /* if we've reached the end of the macro */
8679 if (exp[i] == ')')
8680 rest_zero = 0;
8681 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8682 && last_ap->raw_after != 0))
8683 xbuf[totlen++] = exp[i];
8686 xbuf[totlen] = 0;
8687 xbuf_len = totlen;
8689 for (i = 0; i < nargs; i++) {
8690 if (args[i].free1 != 0)
8691 free (args[i].free1);
8692 if (args[i].free2 != 0)
8693 free (args[i].free2);
8696 } else {
8697 xbuf = defn->expansion;
8698 xbuf_len = defn->length;
8701 /* Now put the expansion on the input stack
8702 so our caller will commence reading from it. */
8704 register FILE_BUF *ip2;
8706 ip2 = &instack[++indepth];
8708 ip2->fname = 0;
8709 ip2->nominal_fname = 0;
8710 ip2->nominal_fname_len = 0;
8711 ip2->inc = 0;
8712 /* This may not be exactly correct, but will give much better error
8713 messages for nested macro calls than using a line number of zero. */
8714 ip2->lineno = start_line;
8715 ip2->buf = xbuf;
8716 ip2->length = xbuf_len;
8717 ip2->bufp = xbuf;
8718 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8719 ip2->macro = hp;
8720 ip2->if_stack = if_stack;
8721 ip2->system_header_p = 0;
8723 /* Recursive macro use sometimes works traditionally.
8724 #define foo(x,y) bar (x (y,0), y)
8725 foo (foo, baz) */
8727 if (!traditional)
8728 hp->type = T_DISABLED;
8732 /* Parse a macro argument and store the info on it into *ARGPTR.
8733 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8734 Return nonzero to indicate a syntax error. */
8736 static int
8737 macarg (argptr, rest_args)
8738 register struct argdata *argptr;
8739 int rest_args;
8741 FILE_BUF *ip = &instack[indepth];
8742 int paren = 0;
8743 int newlines = 0;
8744 int comments = 0;
8745 int result = 0;
8747 /* Try to parse as much of the argument as exists at this
8748 input stack level. */
8749 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8750 &paren, &newlines, &comments, rest_args);
8752 /* If we find the end of the argument at this level,
8753 set up *ARGPTR to point at it in the input stack. */
8754 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8755 && bp != ip->buf + ip->length) {
8756 if (argptr != 0) {
8757 argptr->raw = ip->bufp;
8758 argptr->raw_length = bp - ip->bufp;
8759 argptr->newlines = newlines;
8761 ip->bufp = bp;
8762 } else {
8763 /* This input stack level ends before the macro argument does.
8764 We must pop levels and keep parsing.
8765 Therefore, we must allocate a temporary buffer and copy
8766 the macro argument into it. */
8767 int bufsize = bp - ip->bufp;
8768 int extra = newlines;
8769 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8770 int final_start = 0;
8772 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8773 ip->bufp = bp;
8774 ip->lineno += newlines;
8776 while (bp == ip->buf + ip->length) {
8777 if (instack[indepth].macro == 0) {
8778 result = 1;
8779 break;
8781 ip->macro->type = T_MACRO;
8782 if (ip->free_ptr)
8783 free (ip->free_ptr);
8784 ip = &instack[--indepth];
8785 newlines = 0;
8786 comments = 0;
8787 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8788 &newlines, &comments, rest_args);
8789 final_start = bufsize;
8790 bufsize += bp - ip->bufp;
8791 extra += newlines;
8792 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8793 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8794 bp - ip->bufp);
8795 ip->bufp = bp;
8796 ip->lineno += newlines;
8799 /* Now, if arg is actually wanted, record its raw form,
8800 discarding comments and duplicating newlines in whatever
8801 part of it did not come from a macro expansion.
8802 EXTRA space has been preallocated for duplicating the newlines.
8803 FINAL_START is the index of the start of that part. */
8804 if (argptr != 0) {
8805 argptr->raw = buffer;
8806 argptr->raw_length = bufsize;
8807 argptr->free1 = buffer;
8808 argptr->newlines = newlines;
8809 if ((newlines || comments) && ip->fname != 0)
8810 argptr->raw_length
8811 = final_start +
8812 discard_comments (argptr->raw + final_start,
8813 argptr->raw_length - final_start,
8814 newlines);
8815 argptr->raw[argptr->raw_length] = 0;
8816 if (argptr->raw_length > bufsize + extra)
8817 abort ();
8821 /* If we are not discarding this argument,
8822 macroexpand it and compute its length as stringified.
8823 All this info goes into *ARGPTR. */
8825 if (argptr != 0) {
8826 register U_CHAR *buf, *lim;
8827 register int totlen;
8829 buf = argptr->raw;
8830 lim = buf + argptr->raw_length;
8832 while (buf != lim && is_space[*buf])
8833 buf++;
8834 while (buf != lim && is_space[lim[-1]])
8835 lim--;
8836 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8837 while (buf != lim) {
8838 register U_CHAR c = *buf++;
8839 totlen++;
8840 /* Internal sequences of whitespace are replaced by one space
8841 in most cases, but not always. So count all the whitespace
8842 in case we need to keep it all. */
8843 #if 0
8844 if (is_space[c])
8845 SKIP_ALL_WHITE_SPACE (buf);
8846 else
8847 #endif
8848 if (c == '\"' || c == '\\') /* escape these chars */
8849 totlen++;
8851 argptr->stringified_length = totlen;
8853 return result;
8856 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8857 taken from the expansion of MACRO,
8858 counting parens in *DEPTHPTR,
8859 and return if reach LIMIT
8860 or before a `)' that would make *DEPTHPTR negative
8861 or before a comma when *DEPTHPTR is zero.
8862 Single and double quotes are matched and termination
8863 is inhibited within them. Comments also inhibit it.
8864 Value returned is pointer to stopping place.
8866 Increment *NEWLINES each time a newline is passed.
8867 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8868 Set *COMMENTS to 1 if a comment is seen. */
8870 static U_CHAR *
8871 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8872 U_CHAR *start;
8873 register U_CHAR *limit;
8874 struct hashnode *macro;
8875 int *depthptr, *newlines, *comments;
8876 int rest_args;
8878 register U_CHAR *bp = start;
8880 while (bp < limit) {
8881 switch (*bp) {
8882 case '(':
8883 (*depthptr)++;
8884 break;
8885 case ')':
8886 if (--(*depthptr) < 0)
8887 return bp;
8888 break;
8889 case '\\':
8890 /* Traditionally, backslash makes following char not special. */
8891 if (traditional && bp + 1 < limit && bp[1] != '\n')
8892 bp++;
8893 break;
8894 case '\n':
8895 ++*newlines;
8896 break;
8897 case '/':
8898 if (macro)
8899 break;
8900 if (bp[1] == '\\' && bp[2] == '\n')
8901 newline_fix (bp + 1);
8902 if (bp[1] == '*') {
8903 *comments = 1;
8904 for (bp += 2; bp < limit; bp++) {
8905 if (*bp == '\n')
8906 ++*newlines;
8907 else if (*bp == '*') {
8908 if (bp[-1] == '/' && warn_comments)
8909 warning ("`/*' within comment");
8910 if (bp[1] == '\\' && bp[2] == '\n')
8911 newline_fix (bp + 1);
8912 if (bp[1] == '/') {
8913 bp++;
8914 break;
8917 else
8919 #ifdef MULTIBYTE_CHARS
8920 int length;
8921 length = local_mblen (bp, limit - bp);
8922 if (length > 1)
8923 bp += (length - 1);
8924 #endif
8927 } else if (bp[1] == '/' && cplusplus_comments) {
8928 *comments = 1;
8929 for (bp += 2; bp < limit; bp++) {
8930 if (*bp == '\n') {
8931 ++*newlines;
8932 break;
8934 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
8936 ++*newlines;
8937 if (warn_comments)
8938 warning ("multiline `//' comment");
8939 ++bp;
8941 else
8943 #ifdef MULTIBYTE_CHARS
8944 int length;
8945 length = local_mblen (bp, limit - bp);
8946 if (length > 1)
8947 bp += (length - 1);
8948 #endif
8952 break;
8953 case '\'':
8954 case '\"':
8956 int quotec;
8957 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8958 if (*bp == '\\') {
8959 bp++;
8960 if (*bp == '\n')
8961 ++*newlines;
8962 if (!macro) {
8963 while (*bp == '\\' && bp[1] == '\n') {
8964 bp += 2;
8965 ++*newlines;
8968 } else if (*bp == '\n') {
8969 ++*newlines;
8970 if (quotec == '\'')
8971 break;
8973 else
8975 #ifdef MULTIBYTE_CHARS
8976 int length;
8977 length = local_mblen (bp, limit - bp);
8978 if (length > 1)
8979 bp += (length - 1);
8980 #endif
8984 break;
8985 case ',':
8986 /* if we've returned to lowest level and we aren't absorbing all args */
8987 if ((*depthptr) == 0 && rest_args == 0)
8988 return bp;
8989 break;
8991 bp++;
8994 return bp;
8997 /* Discard comments and duplicate newlines
8998 in the string of length LENGTH at START,
8999 except inside of string constants.
9000 The string is copied into itself with its beginning staying fixed.
9002 NEWLINES is the number of newlines that must be duplicated.
9003 We assume that that much extra space is available past the end
9004 of the string. */
9006 static int
9007 discard_comments (start, length, newlines)
9008 U_CHAR *start;
9009 int length;
9010 int newlines;
9012 register U_CHAR *ibp;
9013 register U_CHAR *obp;
9014 register U_CHAR *limit;
9015 register int c;
9017 /* If we have newlines to duplicate, copy everything
9018 that many characters up. Then, in the second part,
9019 we will have room to insert the newlines
9020 while copying down.
9021 NEWLINES may actually be too large, because it counts
9022 newlines in string constants, and we don't duplicate those.
9023 But that does no harm. */
9024 if (newlines > 0) {
9025 ibp = start + length;
9026 obp = ibp + newlines;
9027 limit = start;
9028 while (limit != ibp)
9029 *--obp = *--ibp;
9032 ibp = start + newlines;
9033 limit = start + length + newlines;
9034 obp = start;
9036 while (ibp < limit) {
9037 *obp++ = c = *ibp++;
9038 switch (c) {
9039 case '\n':
9040 /* Duplicate the newline. */
9041 *obp++ = '\n';
9042 break;
9044 case '\\':
9045 if (*ibp == '\n') {
9046 obp--;
9047 ibp++;
9049 break;
9051 case '/':
9052 if (*ibp == '\\' && ibp[1] == '\n')
9053 newline_fix (ibp);
9054 /* Delete any comment. */
9055 if (cplusplus_comments && ibp[0] == '/') {
9056 /* Comments are equivalent to spaces. */
9057 obp[-1] = ' ';
9058 ibp++;
9059 while (ibp < limit)
9061 if (*ibp == '\n')
9062 break;
9063 if (*ibp == '\\' && ibp + 1 < limit && ibp[1] == '\n')
9064 ibp++;
9065 else
9067 #ifdef MULTIBYTE_CHARS
9068 int length = local_mblen (ibp, limit - ibp);
9069 if (length > 1)
9070 ibp += (length - 1);
9071 #endif
9073 ibp++;
9075 break;
9077 if (ibp[0] != '*' || ibp + 1 >= limit)
9078 break;
9079 /* Comments are equivalent to spaces.
9080 For -traditional, a comment is equivalent to nothing. */
9081 if (traditional)
9082 obp--;
9083 else
9084 obp[-1] = ' ';
9085 while (++ibp < limit) {
9086 if (ibp[0] == '*') {
9087 if (ibp[1] == '\\' && ibp[2] == '\n')
9088 newline_fix (ibp + 1);
9089 if (ibp[1] == '/') {
9090 ibp += 2;
9091 break;
9094 else
9096 #ifdef MULTIBYTE_CHARS
9097 int length = local_mblen (ibp, limit - ibp);
9098 if (length > 1)
9099 ibp += (length - 1);
9100 #endif
9103 break;
9105 case '\'':
9106 case '\"':
9107 /* Notice and skip strings, so that we don't
9108 think that comments start inside them,
9109 and so we don't duplicate newlines in them. */
9111 int quotec = c;
9112 while (ibp < limit) {
9113 *obp++ = c = *ibp++;
9114 if (c == quotec)
9115 break;
9116 if (c == '\n')
9118 if (quotec == '\'')
9119 break;
9121 else if (c == '\\') {
9122 if (ibp < limit && *ibp == '\n') {
9123 ibp++;
9124 obp--;
9125 } else {
9126 while (*ibp == '\\' && ibp[1] == '\n')
9127 ibp += 2;
9128 if (ibp < limit)
9129 *obp++ = *ibp++;
9132 else
9134 #ifdef MULTIBYTE_CHARS
9135 int length;
9136 ibp--;
9137 length = local_mblen (ibp, limit - ibp);
9138 if (length > 1)
9140 obp--;
9141 bcopy (ibp, obp, length);
9142 ibp += length;
9143 obp += length;
9145 else
9146 ibp++;
9147 #endif
9151 break;
9155 return obp - start;
9158 /* Turn newlines to spaces in the string of length LENGTH at START,
9159 except inside of string constants.
9160 The string is copied into itself with its beginning staying fixed. */
9162 static int
9163 change_newlines (start, length)
9164 U_CHAR *start;
9165 int length;
9167 register U_CHAR *ibp;
9168 register U_CHAR *obp;
9169 register U_CHAR *limit;
9170 register int c;
9172 ibp = start;
9173 limit = start + length;
9174 obp = start;
9176 while (ibp < limit) {
9177 *obp++ = c = *ibp++;
9178 switch (c) {
9179 case '\n':
9180 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
9181 string. Skip past the newline and its duplicate.
9182 Put a space in the output. */
9183 if (*ibp == '\n')
9185 ibp++;
9186 obp--;
9187 *obp++ = ' ';
9189 break;
9191 case '\'':
9192 case '\"':
9193 /* Notice and skip strings, so that we don't delete newlines in them. */
9195 int quotec = c;
9196 while (ibp < limit) {
9197 *obp++ = c = *ibp++;
9198 if (c == quotec)
9199 break;
9200 else if (c == '\\' && ibp < limit && *ibp == '\n')
9201 *obp++ = *ibp++;
9202 else if (c == '\n')
9204 if (quotec == '\'')
9205 break;
9207 else
9209 #ifdef MULTIBYTE_CHARS
9210 int length;
9211 ibp--;
9212 length = local_mblen (ibp, limit - ibp);
9213 if (length > 1)
9215 obp--;
9216 bcopy (ibp, obp, length);
9217 ibp += length;
9218 obp += length;
9220 else
9221 ibp++;
9222 #endif
9226 break;
9230 return obp - start;
9233 /* my_strerror - return the descriptive text associated with an
9234 `errno' code. */
9236 static char *
9237 my_strerror (errnum)
9238 int errnum;
9240 char *result;
9242 #ifndef VMS
9243 #ifndef HAVE_STRERROR
9244 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
9245 #else
9246 result = strerror (errnum);
9247 #endif
9248 #else /* VMS */
9249 /* VAXCRTL's strerror() takes an optional second argument, which only
9250 matters when the first argument is EVMSERR. However, it's simplest
9251 just to pass it unconditionally. `vaxc$errno' is declared in
9252 <errno.h>, and maintained by the library in parallel with `errno'.
9253 We assume that caller's `errnum' either matches the last setting of
9254 `errno' by the library or else does not have the value `EVMSERR'. */
9256 result = strerror (errnum, vaxc$errno);
9257 #endif
9259 if (!result)
9260 result = "errno = ?";
9262 return result;
9265 /* notice - output message to stderr */
9267 static void
9268 notice VPROTO ((const char * msgid, ...))
9270 #ifndef ANSI_PROTOTYPES
9271 const char * msgid;
9272 #endif
9273 va_list args;
9275 VA_START (args, msgid);
9277 #ifndef ANSI_PROTOTYPES
9278 msgid = va_arg (args, const char *);
9279 #endif
9281 vnotice (msgid, args);
9282 va_end (args);
9285 static void
9286 vnotice (msgid, args)
9287 const char *msgid;
9288 va_list args;
9290 vfprintf (stderr, _(msgid), args);
9293 /* error - print error message and increment count of errors. */
9295 void
9296 error VPROTO ((const char * msgid, ...))
9298 #ifndef ANSI_PROTOTYPES
9299 const char * msgid;
9300 #endif
9301 va_list args;
9303 VA_START (args, msgid);
9305 #ifndef ANSI_PROTOTYPES
9306 msgid = va_arg (args, const char *);
9307 #endif
9309 verror (msgid, args);
9310 va_end (args);
9313 void
9314 verror (msgid, args)
9315 const char *msgid;
9316 va_list args;
9318 int i;
9319 FILE_BUF *ip = NULL;
9321 print_containing_files ();
9323 for (i = indepth; i >= 0; i--)
9324 if (instack[i].fname != NULL) {
9325 ip = &instack[i];
9326 break;
9329 if (ip != NULL) {
9330 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9331 fprintf (stderr, ":%d: ", ip->lineno);
9333 vnotice (msgid, args);
9334 fprintf (stderr, "\n");
9335 errors++;
9338 /* Error including a message from `errno'. */
9340 static void
9341 error_from_errno (name)
9342 char *name;
9344 int e = errno;
9345 int i;
9346 FILE_BUF *ip = NULL;
9348 print_containing_files ();
9350 for (i = indepth; i >= 0; i--)
9351 if (instack[i].fname != NULL) {
9352 ip = &instack[i];
9353 break;
9356 if (ip != NULL) {
9357 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9358 fprintf (stderr, ":%d: ", ip->lineno);
9361 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
9363 errors++;
9366 /* Print error message but don't count it. */
9368 void
9369 warning VPROTO ((const char * msgid, ...))
9371 #ifndef ANSI_PROTOTYPES
9372 const char * msgid;
9373 #endif
9374 va_list args;
9376 VA_START (args, msgid);
9378 #ifndef ANSI_PROTOTYPES
9379 msgid = va_arg (args, const char *);
9380 #endif
9382 vwarning (msgid, args);
9383 va_end (args);
9386 static void
9387 vwarning (msgid, args)
9388 const char *msgid;
9389 va_list args;
9391 int i;
9392 FILE_BUF *ip = NULL;
9394 if (inhibit_warnings)
9395 return;
9397 if (warnings_are_errors)
9398 errors++;
9400 print_containing_files ();
9402 for (i = indepth; i >= 0; i--)
9403 if (instack[i].fname != NULL) {
9404 ip = &instack[i];
9405 break;
9408 if (ip != NULL) {
9409 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9410 fprintf (stderr, ":%d: ", ip->lineno);
9412 notice ("warning: ");
9413 vnotice (msgid, args);
9414 fprintf (stderr, "\n");
9417 static void
9418 error_with_line VPROTO ((int line, const char * msgid, ...))
9420 #ifndef ANSI_PROTOTYPES
9421 int line;
9422 const char * msgid;
9423 #endif
9424 va_list args;
9426 VA_START (args, msgid);
9428 #ifndef ANSI_PROTOTYPES
9429 line = va_arg (args, int);
9430 msgid = va_arg (args, const char *);
9431 #endif
9433 verror_with_line (line, msgid, args);
9434 va_end (args);
9438 static void
9439 verror_with_line (line, msgid, args)
9440 int line;
9441 const char *msgid;
9442 va_list args;
9444 int i;
9445 FILE_BUF *ip = NULL;
9447 print_containing_files ();
9449 for (i = indepth; i >= 0; i--)
9450 if (instack[i].fname != NULL) {
9451 ip = &instack[i];
9452 break;
9455 if (ip != NULL) {
9456 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9457 fprintf (stderr, ":%d: ", line);
9459 vnotice (msgid, args);
9460 fprintf (stderr, "\n");
9461 errors++;
9464 static void
9465 warning_with_line VPROTO ((int line, const char * msgid, ...))
9467 #ifndef ANSI_PROTOTYPES
9468 int line;
9469 const char * msgid;
9470 #endif
9471 va_list args;
9473 VA_START (args, msgid);
9475 #ifndef ANSI_PROTOTYPES
9476 line = va_arg (args, int);
9477 msgid = va_arg (args, const char *);
9478 #endif
9480 vwarning_with_line (line, msgid, args);
9481 va_end (args);
9484 static void
9485 vwarning_with_line (line, msgid, args)
9486 int line;
9487 const char *msgid;
9488 va_list args;
9490 int i;
9491 FILE_BUF *ip = NULL;
9493 if (inhibit_warnings)
9494 return;
9496 if (warnings_are_errors)
9497 errors++;
9499 print_containing_files ();
9501 for (i = indepth; i >= 0; i--)
9502 if (instack[i].fname != NULL) {
9503 ip = &instack[i];
9504 break;
9507 if (ip != NULL) {
9508 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9509 fprintf (stderr, line ? ":%d: " : ": ", line);
9511 notice ("warning: ");
9512 vnotice (msgid, args);
9513 fprintf (stderr, "\n");
9516 /* Print an error message and maybe count it. */
9518 void
9519 pedwarn VPROTO ((const char * msgid, ...))
9521 #ifndef ANSI_PROTOTYPES
9522 const char * msgid;
9523 #endif
9524 va_list args;
9526 VA_START (args, msgid);
9528 #ifndef ANSI_PROTOTYPES
9529 msgid = va_arg (args, const char *);
9530 #endif
9532 if (pedantic_errors)
9533 verror (msgid, args);
9534 else
9535 vwarning (msgid, args);
9536 va_end (args);
9539 void
9540 pedwarn_with_line VPROTO ((int line, const char * msgid, ...))
9542 #ifndef ANSI_PROTOTYPES
9543 int line;
9544 const char * msgid;
9545 #endif
9546 va_list args;
9548 VA_START (args, msgid);
9550 #ifndef ANSI_PROTOTYPES
9551 line = va_arg (args, int);
9552 msgid = va_arg (args, const char *);
9553 #endif
9555 if (pedantic_errors)
9556 verror_with_line (line, msgid, args);
9557 else
9558 vwarning_with_line (line, msgid, args);
9559 va_end (args);
9562 /* Report a warning (or an error if pedantic_errors)
9563 giving specified file name and line number, not current. */
9565 static void
9566 pedwarn_with_file_and_line VPROTO ((const char *file, size_t file_len, int line,
9567 const char * msgid, ...))
9569 #ifndef ANSI_PROTOTYPES
9570 const char *file;
9571 size_t file_len;
9572 int line;
9573 const char * msgid;
9574 #endif
9575 va_list args;
9577 if (!pedantic_errors && inhibit_warnings)
9578 return;
9580 VA_START (args, msgid);
9582 #ifndef ANSI_PROTOTYPES
9583 file = va_arg (args, const char *);
9584 file_len = va_arg (args, size_t);
9585 line = va_arg (args, int);
9586 msgid = va_arg (args, const char *);
9587 #endif
9589 if (file) {
9590 eprint_string (file, file_len);
9591 fprintf (stderr, ":%d: ", line);
9593 if (pedantic_errors)
9594 errors++;
9595 if (!pedantic_errors)
9596 notice ("warning: ");
9597 vnotice (msgid, args);
9598 va_end (args);
9599 fprintf (stderr, "\n");
9602 static void
9603 pedwarn_strange_white_space (ch)
9604 int ch;
9606 switch (ch)
9608 case '\f': pedwarn ("formfeed in preprocessing directive"); break;
9609 case '\r': pedwarn ("carriage return in preprocessing directive"); break;
9610 case '\v': pedwarn ("vertical tab in preprocessing directive"); break;
9611 default: abort ();
9615 /* Print the file names and line numbers of the #include
9616 directives which led to the current file. */
9618 static void
9619 print_containing_files ()
9621 FILE_BUF *ip = NULL;
9622 int i;
9623 int first = 1;
9625 /* If stack of files hasn't changed since we last printed
9626 this info, don't repeat it. */
9627 if (last_error_tick == input_file_stack_tick)
9628 return;
9630 for (i = indepth; i >= 0; i--)
9631 if (instack[i].fname != NULL) {
9632 ip = &instack[i];
9633 break;
9636 /* Give up if we don't find a source file. */
9637 if (ip == NULL)
9638 return;
9640 /* Find the other, outer source files. */
9641 for (i--; i >= 0; i--)
9642 if (instack[i].fname != NULL) {
9643 ip = &instack[i];
9644 if (first) {
9645 first = 0;
9646 notice ( "In file included from ");
9647 } else {
9648 notice (",\n from ");
9651 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9652 fprintf (stderr, ":%d", ip->lineno);
9654 if (! first)
9655 fprintf (stderr, ":\n");
9657 /* Record we have printed the status as of this time. */
9658 last_error_tick = input_file_stack_tick;
9661 /* Return the line at which an error occurred.
9662 The error is not necessarily associated with the current spot
9663 in the input stack, so LINE says where. LINE will have been
9664 copied from ip->lineno for the current input level.
9665 If the current level is for a file, we return LINE.
9666 But if the current level is not for a file, LINE is meaningless.
9667 In that case, we return the lineno of the innermost file. */
9669 static int
9670 line_for_error (line)
9671 int line;
9673 int i;
9674 int line1 = line;
9676 for (i = indepth; i >= 0; ) {
9677 if (instack[i].fname != 0)
9678 return line1;
9679 i--;
9680 if (i < 0)
9681 return 0;
9682 line1 = instack[i].lineno;
9684 abort ();
9685 /*NOTREACHED*/
9686 return 0;
9690 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9692 * As things stand, nothing is ever placed in the output buffer to be
9693 * removed again except when it's KNOWN to be part of an identifier,
9694 * so flushing and moving down everything left, instead of expanding,
9695 * should work ok.
9698 /* You might think void was cleaner for the return type,
9699 but that would get type mismatch in check_expand in strict ANSI. */
9701 static int
9702 grow_outbuf (obuf, needed)
9703 register FILE_BUF *obuf;
9704 register int needed;
9706 register U_CHAR *p;
9707 int minsize;
9709 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9710 return 0;
9712 /* Make it at least twice as big as it is now. */
9713 obuf->length *= 2;
9714 /* Make it have at least 150% of the free space we will need. */
9715 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9716 if (minsize > obuf->length)
9717 obuf->length = minsize;
9719 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9720 memory_full ();
9722 obuf->bufp = p + (obuf->bufp - obuf->buf);
9723 obuf->buf = p;
9725 return 0;
9728 /* Symbol table for macro names and special symbols */
9731 * install a name in the main hash table, even if it is already there.
9732 * name stops with first non alphanumeric, except leading '#'.
9733 * caller must check against redefinition if that is desired.
9734 * delete_macro () removes things installed by install () in fifo order.
9735 * this is important because of the `defined' special symbol used
9736 * in #if, and also if pushdef/popdef directives are ever implemented.
9738 * If LEN is >= 0, it is the length of the name.
9739 * Otherwise, compute the length by scanning the entire name.
9741 * If HASH is >= 0, it is the precomputed hash code.
9742 * Otherwise, compute the hash code.
9745 static HASHNODE *
9746 install (name, len, type, value, hash)
9747 U_CHAR *name;
9748 int len;
9749 enum node_type type;
9750 char *value;
9751 int hash;
9753 register HASHNODE *hp;
9754 register int i, bucket;
9755 register U_CHAR *p, *q;
9757 if (len < 0) {
9758 p = name;
9759 while (is_idchar[*p])
9760 p++;
9761 len = p - name;
9764 if (hash < 0)
9765 hash = hashf (name, len, HASHSIZE);
9767 i = sizeof (HASHNODE) + len + 1;
9768 hp = (HASHNODE *) xmalloc (i);
9769 bucket = hash;
9770 hp->bucket_hdr = &hashtab[bucket];
9771 hp->next = hashtab[bucket];
9772 hashtab[bucket] = hp;
9773 hp->prev = NULL;
9774 if (hp->next != NULL)
9775 hp->next->prev = hp;
9776 hp->type = type;
9777 hp->length = len;
9778 hp->value.cpval = value;
9779 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9780 p = hp->name;
9781 q = name;
9782 for (i = 0; i < len; i++)
9783 *p++ = *q++;
9784 hp->name[len] = 0;
9785 return hp;
9789 * find the most recent hash node for name "name" (ending with first
9790 * non-identifier char) installed by install
9792 * If LEN is >= 0, it is the length of the name.
9793 * Otherwise, compute the length by scanning the entire name.
9795 * If HASH is >= 0, it is the precomputed hash code.
9796 * Otherwise, compute the hash code.
9799 HASHNODE *
9800 lookup (name, len, hash)
9801 U_CHAR *name;
9802 int len;
9803 int hash;
9805 register U_CHAR *bp;
9806 register HASHNODE *bucket;
9808 if (len < 0) {
9809 for (bp = name; is_idchar[*bp]; bp++) ;
9810 len = bp - name;
9813 if (hash < 0)
9814 hash = hashf (name, len, HASHSIZE);
9816 bucket = hashtab[hash];
9817 while (bucket) {
9818 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9819 return bucket;
9820 bucket = bucket->next;
9822 return NULL;
9826 * Delete a hash node. Some weirdness to free junk from macros.
9827 * More such weirdness will have to be added if you define more hash
9828 * types that need it.
9831 /* Note that the DEFINITION of a macro is removed from the hash table
9832 but its storage is not freed. This would be a storage leak
9833 except that it is not reasonable to keep undefining and redefining
9834 large numbers of macros many times.
9835 In any case, this is necessary, because a macro can be #undef'd
9836 in the middle of reading the arguments to a call to it.
9837 If #undef freed the DEFINITION, that would crash. */
9839 static void
9840 delete_macro (hp)
9841 HASHNODE *hp;
9844 if (hp->prev != NULL)
9845 hp->prev->next = hp->next;
9846 if (hp->next != NULL)
9847 hp->next->prev = hp->prev;
9849 /* Make sure that the bucket chain header that the deleted guy was
9850 on points to the right thing afterwards. */
9851 if (hp == *hp->bucket_hdr)
9852 *hp->bucket_hdr = hp->next;
9854 #if 0
9855 if (hp->type == T_MACRO) {
9856 DEFINITION *d = hp->value.defn;
9857 struct reflist *ap, *nextap;
9859 for (ap = d->pattern; ap != NULL; ap = nextap) {
9860 nextap = ap->next;
9861 free (ap);
9863 free (d);
9865 #endif
9866 free (hp);
9870 * return hash function on name. must be compatible with the one
9871 * computed a step at a time, elsewhere
9874 static int
9875 hashf (name, len, hashsize)
9876 register U_CHAR *name;
9877 register int len;
9878 int hashsize;
9880 register int r = 0;
9882 while (len--)
9883 r = HASHSTEP (r, *name++);
9885 return MAKE_POS (r) % hashsize;
9889 /* Dump the definition of a single macro HP to OF. */
9891 static void
9892 dump_single_macro (hp, of)
9893 register HASHNODE *hp;
9894 FILE *of;
9896 register DEFINITION *defn = hp->value.defn;
9897 struct reflist *ap;
9898 int offset;
9899 int concat;
9902 /* Print the definition of the macro HP. */
9904 fprintf (of, "#define %s", hp->name);
9906 if (defn->nargs >= 0) {
9907 int i;
9909 fprintf (of, "(");
9910 for (i = 0; i < defn->nargs; i++) {
9911 dump_arg_n (defn, i, of);
9912 if (i + 1 < defn->nargs)
9913 fprintf (of, ", ");
9915 fprintf (of, ")");
9918 fprintf (of, " ");
9920 offset = 0;
9921 concat = 0;
9922 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9923 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9924 offset += ap->nchars;
9925 if (!traditional) {
9926 if (ap->nchars != 0)
9927 concat = 0;
9928 if (ap->stringify) {
9929 switch (ap->stringify) {
9930 case SHARP_TOKEN: fprintf (of, "#"); break;
9931 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9932 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9933 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9934 default: abort ();
9937 if (ap->raw_before != 0) {
9938 if (concat) {
9939 switch (ap->raw_before) {
9940 case WHITE_SHARP_TOKEN:
9941 case WHITE_PERCENT_COLON_TOKEN:
9942 fprintf (of, " ");
9943 break;
9944 default:
9945 break;
9947 } else {
9948 switch (ap->raw_before) {
9949 case SHARP_TOKEN: fprintf (of, "##"); break;
9950 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9951 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9952 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9953 default: abort ();
9957 concat = 0;
9959 dump_arg_n (defn, ap->argno, of);
9960 if (!traditional && ap->raw_after != 0) {
9961 switch (ap->raw_after) {
9962 case SHARP_TOKEN: fprintf (of, "##"); break;
9963 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9964 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9965 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9966 default: abort ();
9968 concat = 1;
9971 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9972 fprintf (of, "\n");
9975 /* Dump all macro definitions as #defines to stdout. */
9977 static void
9978 dump_all_macros ()
9980 int bucket;
9982 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9983 register HASHNODE *hp;
9985 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9986 if (hp->type == T_MACRO)
9987 dump_single_macro (hp, stdout);
9992 /* Output to OF a substring of a macro definition.
9993 BASE is the beginning of the definition.
9994 Output characters START thru LENGTH.
9995 Unless traditional, discard newlines outside of strings, thus
9996 converting funny-space markers to ordinary spaces. */
9998 static void
9999 dump_defn_1 (base, start, length, of)
10000 U_CHAR *base;
10001 int start;
10002 int length;
10003 FILE *of;
10005 U_CHAR *p = base + start;
10006 U_CHAR *limit = base + start + length;
10008 if (traditional)
10009 fwrite (p, sizeof (*p), length, of);
10010 else {
10011 while (p < limit) {
10012 if (*p == '\"' || *p =='\'') {
10013 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
10014 NULL_PTR, NULL_PTR);
10015 fwrite (p, sizeof (*p), p1 - p, of);
10016 p = p1;
10017 } else {
10018 if (*p != '\n')
10019 putc (*p, of);
10020 p++;
10026 /* Print the name of argument number ARGNUM of macro definition DEFN
10027 to OF.
10028 Recall that DEFN->args.argnames contains all the arg names
10029 concatenated in reverse order with comma-space in between. */
10031 static void
10032 dump_arg_n (defn, argnum, of)
10033 DEFINITION *defn;
10034 int argnum;
10035 FILE *of;
10037 register U_CHAR *p = defn->args.argnames;
10038 while (argnum + 1 < defn->nargs) {
10039 p = (U_CHAR *) index ((char *) p, ' ') + 1;
10040 argnum++;
10043 while (*p && *p != ',') {
10044 putc (*p, of);
10045 p++;
10049 /* Initialize syntactic classifications of characters. */
10051 static void
10052 initialize_char_syntax ()
10054 register int i;
10057 * Set up is_idchar and is_idstart tables. These should be
10058 * faster than saying (is_alpha (c) || c == '_'), etc.
10059 * Set up these things before calling any routines tthat
10060 * refer to them.
10062 for (i = 'a'; i <= 'z'; i++) {
10063 is_idchar[i - 'a' + 'A'] = 1;
10064 is_idchar[i] = 1;
10065 is_idstart[i - 'a' + 'A'] = 1;
10066 is_idstart[i] = 1;
10068 for (i = '0'; i <= '9'; i++)
10069 is_idchar[i] = 1;
10070 is_idchar['_'] = 1;
10071 is_idstart['_'] = 1;
10072 is_idchar['$'] = 1;
10073 is_idstart['$'] = 1;
10075 /* horizontal space table */
10076 is_hor_space[' '] = 1;
10077 is_hor_space['\t'] = 1;
10078 is_hor_space['\v'] = 1;
10079 is_hor_space['\f'] = 1;
10080 is_hor_space['\r'] = 1;
10082 is_space[' '] = 1;
10083 is_space['\t'] = 1;
10084 is_space['\v'] = 1;
10085 is_space['\f'] = 1;
10086 is_space['\n'] = 1;
10087 is_space['\r'] = 1;
10090 /* Initialize the built-in macros. */
10092 static void
10093 initialize_builtins (inp, outp)
10094 FILE_BUF *inp;
10095 FILE_BUF *outp;
10097 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
10098 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
10099 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
10100 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
10101 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
10102 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
10103 #ifndef NO_BUILTIN_SIZE_TYPE
10104 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
10105 #endif
10106 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10107 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
10108 #endif
10109 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
10110 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
10111 NULL_PTR, -1);
10112 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
10113 NULL_PTR, -1);
10114 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
10115 NULL_PTR, -1);
10116 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
10117 if (!traditional) {
10118 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
10119 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
10121 /* This is supplied using a -D by the compiler driver
10122 so that it is present only when truly compiling with GNU C. */
10123 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
10124 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
10126 if (debug_output)
10128 char directive[2048];
10129 U_CHAR *udirective = (U_CHAR *) directive;
10130 register struct directive *dp = &directive_table[0];
10131 struct tm *timebuf = timestamp ();
10133 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
10134 instack[0].nominal_fname);
10135 output_line_directive (inp, outp, 0, same_file);
10136 pass_thru_directive (udirective, &udirective[strlen (directive)],
10137 outp, dp);
10139 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
10140 output_line_directive (inp, outp, 0, same_file);
10141 pass_thru_directive (udirective, &udirective[strlen (directive)],
10142 outp, dp);
10144 #ifndef NO_BUILTIN_SIZE_TYPE
10145 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
10146 output_line_directive (inp, outp, 0, same_file);
10147 pass_thru_directive (udirective, &udirective[strlen (directive)],
10148 outp, dp);
10149 #endif
10151 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10152 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
10153 output_line_directive (inp, outp, 0, same_file);
10154 pass_thru_directive (udirective, &udirective[strlen (directive)],
10155 outp, dp);
10156 #endif
10158 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
10159 output_line_directive (inp, outp, 0, same_file);
10160 pass_thru_directive (udirective, &udirective[strlen (directive)],
10161 outp, dp);
10163 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
10164 monthnames[timebuf->tm_mon],
10165 timebuf->tm_mday, timebuf->tm_year + 1900);
10166 output_line_directive (inp, outp, 0, same_file);
10167 pass_thru_directive (udirective, &udirective[strlen (directive)],
10168 outp, dp);
10170 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
10171 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
10172 output_line_directive (inp, outp, 0, same_file);
10173 pass_thru_directive (udirective, &udirective[strlen (directive)],
10174 outp, dp);
10176 if (!traditional)
10178 sprintf (directive, " __STDC__ 1");
10179 output_line_directive (inp, outp, 0, same_file);
10180 pass_thru_directive (udirective, &udirective[strlen (directive)],
10181 outp, dp);
10183 if (objc)
10185 sprintf (directive, " __OBJC__ 1");
10186 output_line_directive (inp, outp, 0, same_file);
10187 pass_thru_directive (udirective, &udirective[strlen (directive)],
10188 outp, dp);
10194 * process a given definition string, for initialization
10195 * If STR is just an identifier, define it with value 1.
10196 * If STR has anything after the identifier, then it should
10197 * be identifier=definition.
10200 static void
10201 make_definition (str)
10202 char *str;
10204 FILE_BUF *ip;
10205 struct directive *kt;
10206 U_CHAR *buf, *p;
10208 p = buf = (U_CHAR *) str;
10209 if (!is_idstart[*p]) {
10210 error ("malformed option `-D %s'", str);
10211 return;
10213 while (is_idchar[*++p])
10215 if (*p == '(') {
10216 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
10218 if (*p++ != ')')
10219 p = (U_CHAR *) str; /* Error */
10221 if (*p == 0) {
10222 buf = (U_CHAR *) alloca (p - buf + 4);
10223 strcpy ((char *)buf, str);
10224 strcat ((char *)buf, " 1");
10225 } else if (*p != '=') {
10226 error ("malformed option `-D %s'", str);
10227 return;
10228 } else {
10229 U_CHAR *q;
10230 /* Copy the entire option so we can modify it. */
10231 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
10232 strncpy ((char *) buf, str, p - (U_CHAR *) str);
10233 /* Change the = to a space. */
10234 buf[p - (U_CHAR *) str] = ' ';
10235 /* Scan for any backslash-newline and remove it. */
10236 p++;
10237 q = &buf[p - (U_CHAR *) str];
10238 while (*p) {
10239 if (*p == '\"' || *p == '\'') {
10240 int unterminated = 0;
10241 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
10242 NULL_PTR, NULL_PTR, &unterminated);
10243 if (unterminated)
10244 return;
10245 while (p != p1)
10246 *q++ = *p++;
10247 } else if (*p == '\\' && p[1] == '\n')
10248 p += 2;
10249 /* Change newline chars into newline-markers. */
10250 else if (*p == '\n')
10252 *q++ = '\n';
10253 *q++ = '\n';
10254 p++;
10256 else
10257 *q++ = *p++;
10259 *q = 0;
10262 ip = &instack[++indepth];
10263 ip->nominal_fname = ip->fname = "*Initialization*";
10264 ip->nominal_fname_len = strlen (ip->nominal_fname);
10266 ip->buf = ip->bufp = buf;
10267 ip->length = strlen ((char *) buf);
10268 ip->lineno = 1;
10269 ip->macro = 0;
10270 ip->free_ptr = 0;
10271 ip->if_stack = if_stack;
10272 ip->system_header_p = 0;
10274 for (kt = directive_table; kt->type != T_DEFINE; kt++)
10277 /* Pass NULL instead of OP, since this is a "predefined" macro. */
10278 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
10279 --indepth;
10282 /* JF, this does the work for the -U option */
10284 static void
10285 make_undef (str, op)
10286 char *str;
10287 FILE_BUF *op;
10289 FILE_BUF *ip;
10290 struct directive *kt;
10292 ip = &instack[++indepth];
10293 ip->nominal_fname = ip->fname = "*undef*";
10294 ip->nominal_fname_len = strlen (ip->nominal_fname);
10296 ip->buf = ip->bufp = (U_CHAR *) str;
10297 ip->length = strlen (str);
10298 ip->lineno = 1;
10299 ip->macro = 0;
10300 ip->free_ptr = 0;
10301 ip->if_stack = if_stack;
10302 ip->system_header_p = 0;
10304 for (kt = directive_table; kt->type != T_UNDEF; kt++)
10307 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
10308 --indepth;
10311 /* Process the string STR as if it appeared as the body of a #assert.
10312 OPTION is the option name for which STR was the argument. */
10314 static void
10315 make_assertion (option, str)
10316 const char *option;
10317 const char *str;
10319 FILE_BUF *ip;
10320 struct directive *kt;
10321 U_CHAR *buf, *p, *q;
10323 /* Copy the entire option so we can modify it. */
10324 buf = (U_CHAR *) alloca (strlen (str) + 1);
10325 strcpy ((char *) buf, str);
10326 /* Scan for any backslash-newline and remove it. */
10327 p = q = buf;
10328 while (*p) {
10329 if (*p == '\\' && p[1] == '\n')
10330 p += 2;
10331 else
10332 *q++ = *p++;
10334 *q = 0;
10336 p = buf;
10337 if (!is_idstart[*p]) {
10338 error ("malformed option `%s %s'", option, str);
10339 return;
10341 while (is_idchar[*++p])
10343 SKIP_WHITE_SPACE (p);
10344 if (! (*p == 0 || *p == '(')) {
10345 error ("malformed option `%s %s'", option, str);
10346 return;
10349 ip = &instack[++indepth];
10350 ip->nominal_fname = ip->fname = "*Initialization*";
10351 ip->nominal_fname_len = strlen (ip->nominal_fname);
10353 ip->buf = ip->bufp = buf;
10354 ip->length = strlen ((char *) buf);
10355 ip->lineno = 1;
10356 ip->macro = 0;
10357 ip->free_ptr = 0;
10358 ip->if_stack = if_stack;
10359 ip->system_header_p = 0;
10361 for (kt = directive_table; kt->type != T_ASSERT; kt++)
10364 /* Pass NULL as output ptr to do_define since we KNOW it never does
10365 any output.... */
10366 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
10367 --indepth;
10370 /* The previous include prefix, if any, is PREV_FILE_NAME.
10371 Translate any pathnames with COMPONENT.
10372 Allocate a new include prefix whose name is the
10373 simplified concatenation of PREFIX and NAME,
10374 with a trailing / added if needed.
10375 But return 0 if the include prefix should be ignored,
10376 e.g. because it is a duplicate of PREV_FILE_NAME. */
10378 static struct file_name_list *
10379 new_include_prefix (prev_file_name, component, prefix, name)
10380 struct file_name_list *prev_file_name;
10381 const char *component;
10382 const char *prefix;
10383 const char *name;
10385 if (name == 0)
10386 fatal ("Directory name missing after command line option");
10388 if (*name == 0)
10389 /* Ignore the empty string. */
10390 return 0;
10392 prefix = update_path (prefix, component);
10393 name = update_path (name, component);
10396 struct file_name_list *dir
10397 = ((struct file_name_list *)
10398 xmalloc (sizeof (struct file_name_list)
10399 + strlen (prefix) + strlen (name) + 2));
10400 size_t len;
10401 strcpy (dir->fname, prefix);
10402 strcat (dir->fname, name);
10403 len = simplify_filename (dir->fname);
10405 /* Convert directory name to a prefix. */
10406 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10407 if (len == 1 && dir->fname[len - 1] == '.')
10408 len = 0;
10409 else
10410 #ifdef VMS
10411 /* must be '/', hack_vms_include_specification triggers on it. */
10412 dir->fname[len++] = '/';
10413 #else
10414 dir->fname[len++] = DIR_SEPARATOR;
10415 #endif
10416 dir->fname[len] = 0;
10419 /* Ignore a directory whose name matches the previous one. */
10420 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10421 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10422 if (!first_bracket_include)
10423 first_bracket_include = prev_file_name;
10424 free (dir);
10425 return 0;
10428 #ifndef VMS
10429 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10431 /* Add a trailing "." if there is a filename. This increases the number
10432 of systems that can stat directories. We remove it below. */
10433 if (len != 0)
10435 dir->fname[len] = '.';
10436 dir->fname[len + 1] = 0;
10439 /* Ignore a nonexistent directory. */
10440 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10441 if (errno != ENOENT && errno != ENOTDIR)
10442 error_from_errno (dir->fname);
10443 free (dir);
10444 return 0;
10447 if (len != 0)
10448 dir->fname[len] = 0;
10450 /* Ignore a directory whose identity matches the previous one. */
10451 if (prev_file_name
10452 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10453 && prev_file_name->st.st_dev == dir->st.st_dev) {
10454 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10455 if (!first_bracket_include)
10456 first_bracket_include = prev_file_name;
10457 free (dir);
10458 return 0;
10460 #endif /* ! VMS */
10462 dir->next = 0;
10463 dir->c_system_include_path = 0;
10464 dir->got_name_map = 0;
10466 return dir;
10470 /* Append a chain of `struct file_name_list's
10471 to the end of the main include chain.
10472 FIRST is the beginning of the chain to append, and LAST is the end. */
10474 static void
10475 append_include_chain (first, last)
10476 struct file_name_list *first, *last;
10478 struct file_name_list *dir;
10480 if (!first || !last)
10481 return;
10483 if (include == 0)
10484 include = first;
10485 else
10486 last_include->next = first;
10488 if (first_bracket_include == 0)
10489 first_bracket_include = first;
10491 for (dir = first; ; dir = dir->next) {
10492 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10493 if (len > max_include_len)
10494 max_include_len = len;
10495 if (dir == last)
10496 break;
10499 last->next = NULL;
10500 last_include = last;
10503 /* Place into DST a representation of the file named SRC that is suitable
10504 for `make'. Do not null-terminate DST. Return its length. */
10505 static int
10506 quote_string_for_make (dst, src)
10507 char *dst;
10508 const char *src;
10510 const char *p = src;
10511 int i = 0;
10512 for (;;)
10514 char c = *p++;
10515 switch (c)
10517 case '\0':
10518 case ' ':
10519 case '\t':
10521 /* GNU make uses a weird quoting scheme for white space.
10522 A space or tab preceded by 2N+1 backslashes represents
10523 N backslashes followed by space; a space or tab
10524 preceded by 2N backslashes represents N backslashes at
10525 the end of a file name; and backslashes in other
10526 contexts should not be doubled. */
10527 const char *q;
10528 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10530 if (dst)
10531 dst[i] = '\\';
10532 i++;
10535 if (!c)
10536 return i;
10537 if (dst)
10538 dst[i] = '\\';
10539 i++;
10540 goto ordinary_char;
10542 case '$':
10543 if (dst)
10544 dst[i] = c;
10545 i++;
10546 /* Fall through. This can mishandle things like "$(" but
10547 there's no easy fix. */
10548 default:
10549 ordinary_char:
10550 /* This can mishandle characters in the string "\0\n%*?[\\~";
10551 exactly which chars are mishandled depends on the `make' version.
10552 We know of no portable solution for this;
10553 even GNU make 3.76.1 doesn't solve the problem entirely.
10554 (Also, '\0' is mishandled due to our calling conventions.) */
10555 if (dst)
10556 dst[i] = c;
10557 i++;
10558 break;
10564 /* Add output to `deps_buffer' for the -M switch.
10565 STRING points to the text to be output.
10566 SPACER is ':' for targets, ' ' for dependencies. */
10568 static void
10569 deps_output (string, spacer)
10570 const char *string;
10571 int spacer;
10573 int size = quote_string_for_make ((char *) 0, string);
10575 if (size == 0)
10576 return;
10578 #ifndef MAX_OUTPUT_COLUMNS
10579 #define MAX_OUTPUT_COLUMNS 72
10580 #endif
10581 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10582 && 1 < deps_column) {
10583 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10584 deps_size += 4;
10585 deps_column = 1;
10586 if (spacer == ' ')
10587 spacer = 0;
10590 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10591 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10592 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10594 if (spacer == ' ') {
10595 deps_buffer[deps_size++] = ' ';
10596 deps_column++;
10598 quote_string_for_make (&deps_buffer[deps_size], string);
10599 deps_size += size;
10600 deps_column += size;
10601 if (spacer == ':') {
10602 deps_buffer[deps_size++] = ':';
10603 deps_column++;
10605 deps_buffer[deps_size] = 0;
10608 void
10609 fatal VPROTO ((const char * msgid, ...))
10611 #ifndef ANSI_PROTOTYPES
10612 const char * msgid;
10613 #endif
10614 va_list args;
10616 fprintf (stderr, "%s: ", progname);
10617 VA_START (args, msgid);
10619 #ifndef ANSI_PROTOTYPES
10620 msgid = va_arg (args, const char *);
10621 #endif
10622 vnotice (msgid, args);
10623 va_end (args);
10624 fprintf (stderr, "\n");
10625 exit (FATAL_EXIT_CODE);
10628 /* More 'friendly' abort that prints the line and file.
10629 config.h can #define abort fancy_abort if you like that sort of thing. */
10631 void
10632 fancy_abort ()
10634 fatal ("Internal gcc abort.");
10637 static void
10638 perror_with_name (name)
10639 char *name;
10641 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10642 errors++;
10645 static void
10646 pfatal_with_name (name)
10647 char *name;
10649 perror_with_name (name);
10650 #ifdef VMS
10651 exit (vaxc$errno);
10652 #else
10653 exit (FATAL_EXIT_CODE);
10654 #endif
10657 /* Handler for SIGPIPE. */
10659 static void
10660 pipe_closed (signo)
10661 /* If this is missing, some compilers complain. */
10662 int signo ATTRIBUTE_UNUSED;
10664 fatal ("output pipe has been closed");
10667 static void
10668 memory_full ()
10670 fatal ("Memory exhausted.");
10674 xmalloc (size)
10675 size_t size;
10677 register PTR ptr = (PTR) malloc (size);
10678 if (!ptr)
10679 memory_full ();
10680 return ptr;
10684 xrealloc (old, size)
10685 PTR old;
10686 size_t size;
10688 register PTR ptr;
10689 if (old)
10690 ptr = (PTR) realloc (old, size);
10691 else
10692 ptr = (PTR) malloc (size);
10693 if (!ptr)
10694 memory_full ();
10695 return ptr;
10699 xcalloc (number, size)
10700 size_t number, size;
10702 register size_t total = number * size;
10703 register PTR ptr = (PTR) malloc (total);
10704 if (!ptr)
10705 memory_full ();
10706 bzero (ptr, total);
10707 return ptr;
10710 char *
10711 xstrdup (input)
10712 const char *input;
10714 register size_t len = strlen (input) + 1;
10715 register char *output = xmalloc (len);
10716 memcpy (output, input, len);
10717 return output;
10720 #ifdef VMS
10722 /* Under VMS we need to fix up the "include" specification filename.
10724 Rules for possible conversions
10726 fullname tried paths
10728 name name
10729 ./dir/name [.dir]name
10730 /dir/name dir:name
10731 /name [000000]name, name
10732 dir/name dir:[000000]name, dir:name, dir/name
10733 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10734 path:/name path:[000000]name, path:name
10735 path:/dir/name path:[000000.dir]name, path:[dir]name
10736 path:dir/name path:[dir]name
10737 [path]:[dir]name [path.dir]name
10738 path/[dir]name [path.dir]name
10740 The path:/name input is constructed when expanding <> includes.
10742 return 1 if name was changed, 0 else. */
10744 static int
10745 hack_vms_include_specification (fullname, vaxc_include)
10746 char *fullname;
10747 int vaxc_include;
10749 register char *basename, *unixname, *local_ptr, *first_slash;
10750 int f, check_filename_before_returning, must_revert;
10751 char Local[512];
10753 check_filename_before_returning = 0;
10754 must_revert = 0;
10755 /* See if we can find a 1st slash. If not, there's no path information. */
10756 first_slash = index (fullname, '/');
10757 if (first_slash == 0)
10758 return 0; /* Nothing to do!!! */
10760 /* construct device spec if none given. */
10762 if (index (fullname, ':') == 0)
10765 /* If fullname has a slash, take it as device spec. */
10767 if (first_slash == fullname)
10769 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10770 if (first_slash)
10771 *first_slash = ':'; /* make device spec */
10772 for (basename = fullname; *basename != 0; basename++)
10773 *basename = *(basename+1); /* remove leading slash */
10775 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10776 && (first_slash[-1] != ':')
10777 && (first_slash[-1] != ']')) /* or a vms path */
10779 *first_slash = ':';
10781 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10782 && (first_slash[-1] == '.'))
10783 fullname += 2;
10786 /* Get part after first ':' (basename[-1] == ':')
10787 or last '/' (basename[-1] == '/'). */
10789 basename = base_name (fullname);
10792 * Check if we have a vax-c style '#include filename'
10793 * and add the missing .h
10796 if (vaxc_include && !index (basename,'.'))
10797 strcat (basename, ".h");
10799 local_ptr = Local; /* initialize */
10801 /* We are trying to do a number of things here. First of all, we are
10802 trying to hammer the filenames into a standard format, such that later
10803 processing can handle them.
10805 If the file name contains something like [dir.], then it recognizes this
10806 as a root, and strips the ".]". Later processing will add whatever is
10807 needed to get things working properly.
10809 If no device is specified, then the first directory name is taken to be
10810 a device name (or a rooted logical). */
10812 /* Point to the UNIX filename part (which needs to be fixed!)
10813 but skip vms path information.
10814 [basename != fullname since first_slash != 0]. */
10816 if ((basename[-1] == ':') /* vms path spec. */
10817 || (basename[-1] == ']')
10818 || (basename[-1] == '>'))
10819 unixname = basename;
10820 else
10821 unixname = fullname;
10823 if (*unixname == '/')
10824 unixname++;
10826 /* If the directory spec is not rooted, we can just copy
10827 the UNIX filename part and we are done. */
10829 if (((basename - fullname) > 1)
10830 && ( (basename[-1] == ']')
10831 || (basename[-1] == '>')))
10833 if (basename[-2] != '.')
10836 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10837 -> PATH]:/name (basename = '/name', unixname = 'name')
10838 We strip the `]', and then splice the two parts of the name in the
10839 usual way. Given the default locations for include files in cccp.c,
10840 we will only use this code if the user specifies alternate locations
10841 with the /include (-I) switch on the command line. */
10843 basename -= 1; /* Strip "]" */
10844 unixname--; /* backspace */
10846 else
10849 /* The VMS part has a ".]" at the end, and this will not do. Later
10850 processing will add a second directory spec, and this would be a syntax
10851 error. Thus we strip the ".]", and thus merge the directory specs.
10852 We also backspace unixname, so that it points to a '/'. This inhibits the
10853 generation of the 000000 root directory spec (which does not belong here
10854 in this case). */
10856 basename -= 2; /* Strip ".]" */
10857 unixname--; /* backspace */
10861 else
10865 /* We drop in here if there is no VMS style directory specification yet.
10866 If there is no device specification either, we make the first dir a
10867 device and try that. If we do not do this, then we will be essentially
10868 searching the users default directory (as if they did a #include "asdf.h").
10870 Then all we need to do is to push a '[' into the output string. Later
10871 processing will fill this in, and close the bracket. */
10873 if ((unixname != fullname) /* vms path spec found. */
10874 && (basename[-1] != ':'))
10875 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10877 *local_ptr++ = '['; /* Open the directory specification */
10880 if (unixname == fullname) /* no vms dir spec. */
10882 must_revert = 1;
10883 if ((first_slash != 0) /* unix dir spec. */
10884 && (*unixname != '/') /* not beginning with '/' */
10885 && (*unixname != '.')) /* or './' or '../' */
10886 *local_ptr++ = '.'; /* dir is local ! */
10889 /* at this point we assume that we have the device spec, and (at least
10890 the opening "[" for a directory specification. We may have directories
10891 specified already.
10893 If there are no other slashes then the filename will be
10894 in the "root" directory. Otherwise, we need to add
10895 directory specifications. */
10897 if (index (unixname, '/') == 0)
10899 /* if no directories specified yet and none are following. */
10900 if (local_ptr[-1] == '[')
10902 /* Just add "000000]" as the directory string */
10903 strcpy (local_ptr, "000000]");
10904 local_ptr += strlen (local_ptr);
10905 check_filename_before_returning = 1; /* we might need to fool with this later */
10908 else
10911 /* As long as there are still subdirectories to add, do them. */
10912 while (index (unixname, '/') != 0)
10914 /* If this token is "." we can ignore it
10915 if it's not at the beginning of a path. */
10916 if ((unixname[0] == '.') && (unixname[1] == '/'))
10918 /* remove it at beginning of path. */
10919 if ( ((unixname == fullname) /* no device spec */
10920 && (fullname+2 != basename)) /* starts with ./ */
10921 /* or */
10922 || ((basename[-1] == ':') /* device spec */
10923 && (unixname-1 == basename))) /* and ./ afterwards */
10924 *local_ptr++ = '.'; /* make '[.' start of path. */
10925 unixname += 2;
10926 continue;
10929 /* Add a subdirectory spec. Do not duplicate "." */
10930 if ( local_ptr[-1] != '.'
10931 && local_ptr[-1] != '['
10932 && local_ptr[-1] != '<')
10933 *local_ptr++ = '.';
10935 /* If this is ".." then the spec becomes "-" */
10936 if ( (unixname[0] == '.')
10937 && (unixname[1] == '.')
10938 && (unixname[2] == '/'))
10940 /* Add "-" and skip the ".." */
10941 if ((local_ptr[-1] == '.')
10942 && (local_ptr[-2] == '['))
10943 local_ptr--; /* prevent [.- */
10944 *local_ptr++ = '-';
10945 unixname += 3;
10946 continue;
10949 /* Copy the subdirectory */
10950 while (*unixname != '/')
10951 *local_ptr++= *unixname++;
10953 unixname++; /* Skip the "/" */
10956 /* Close the directory specification */
10957 if (local_ptr[-1] == '.') /* no trailing periods */
10958 local_ptr--;
10960 if (local_ptr[-1] == '[') /* no dir needed */
10961 local_ptr--;
10962 else
10963 *local_ptr++ = ']';
10966 /* Now add the filename. */
10968 while (*unixname)
10969 *local_ptr++ = *unixname++;
10970 *local_ptr = 0;
10972 /* Now append it to the original VMS spec. */
10974 strcpy ((must_revert==1)?fullname:basename, Local);
10976 /* If we put a [000000] in the filename, try to open it first. If this fails,
10977 remove the [000000], and return that name. This provides flexibility
10978 to the user in that they can use both rooted and non-rooted logical names
10979 to point to the location of the file. */
10981 if (check_filename_before_returning)
10983 f = open (fullname, O_RDONLY, 0666);
10984 if (f >= 0)
10986 /* The file name is OK as it is, so return it as is. */
10987 close (f);
10988 return 1;
10991 /* The filename did not work. Try to remove the [000000] from the name,
10992 and return it. */
10994 basename = index (fullname, '[');
10995 local_ptr = index (fullname, ']') + 1;
10996 strcpy (basename, local_ptr); /* this gets rid of it */
11000 return 1;
11002 #endif /* VMS */
11004 #ifdef VMS
11006 /* The following wrapper functions supply additional arguments to the VMS
11007 I/O routines to optimize performance with file handling. The arguments
11008 are:
11009 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
11010 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
11011 "fop=tef"- Truncate unused portions of file when closing file.
11012 "shr=nil"- Disallow file sharing while file is open. */
11014 static FILE *
11015 VMS_freopen (fname, type, oldfile)
11016 char *fname;
11017 char *type;
11018 FILE *oldfile;
11020 #undef freopen /* Get back the real freopen routine. */
11021 if (strcmp (type, "w") == 0)
11022 return freopen (fname, type, oldfile,
11023 "mbc=16", "deq=64", "fop=tef", "shr=nil");
11024 return freopen (fname, type, oldfile, "mbc=16");
11027 static FILE *
11028 VMS_fopen (fname, type)
11029 char *fname;
11030 char *type;
11032 #undef fopen /* Get back the real fopen routine. */
11033 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
11034 fixed arguments, which matches ANSI's specification but not VAXCRTL's
11035 pre-ANSI implementation. This hack circumvents the mismatch problem. */
11036 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
11038 if (*type == 'w')
11039 return (*vmslib_fopen) (fname, type, "mbc=32",
11040 "deq=64", "fop=tef", "shr=nil");
11041 else
11042 return (*vmslib_fopen) (fname, type, "mbc=32");
11045 static int
11046 VMS_open (fname, flags, prot)
11047 char *fname;
11048 int flags;
11049 int prot;
11051 #undef open /* Get back the real open routine. */
11052 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
11055 /* more VMS hackery */
11056 #include <fab.h>
11057 #include <nam.h>
11059 extern unsigned long SYS$PARSE(), SYS$SEARCH();
11061 /* Work around another library bug. If a file is located via a searchlist,
11062 and if the device it's on is not the same device as the one specified
11063 in the first element of that searchlist, then both stat() and fstat()
11064 will fail to return info about it. `errno' will be set to EVMSERR, and
11065 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
11066 We can get around this by fully parsing the filename and then passing
11067 that absolute name to stat().
11069 Without this fix, we can end up failing to find header files, which is
11070 bad enough, but then compounding the problem by reporting the reason for
11071 failure as "normal successful completion." */
11073 #undef fstat /* Get back to the library version. */
11075 static int
11076 VMS_fstat (fd, statbuf)
11077 int fd;
11078 struct stat *statbuf;
11080 int result = fstat (fd, statbuf);
11082 if (result < 0)
11084 FILE *fp;
11085 char nambuf[NAM$C_MAXRSS+1];
11087 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
11088 result = VMS_stat (nambuf, statbuf);
11089 /* No fclose(fp) here; that would close(fd) as well. */
11092 return result;
11095 static int
11096 VMS_stat (name, statbuf)
11097 const char *name;
11098 struct stat *statbuf;
11100 int result = stat (name, statbuf);
11102 if (result < 0)
11104 struct FAB fab;
11105 struct NAM nam;
11106 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
11107 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
11109 fab = cc$rms_fab;
11110 fab.fab$l_fna = (char *) name;
11111 fab.fab$b_fns = (unsigned char) strlen (name);
11112 fab.fab$l_nam = (void *) &nam;
11113 nam = cc$rms_nam;
11114 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
11115 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
11116 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
11117 if (SYS$PARSE (&fab) & 1)
11119 if (SYS$SEARCH (&fab) & 1)
11121 res_nam[nam.nam$b_rsl] = '\0';
11122 result = stat (res_nam, statbuf);
11124 /* Clean up searchlist context cached by the system. */
11125 nam.nam$b_nop = NAM$M_SYNCHK;
11126 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
11127 (void) SYS$PARSE (&fab);
11131 return result;
11133 #endif /* VMS */