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