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