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