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