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