(main): Don't set "Include" environment variable for NT.
[official-gcc.git] / gcc / cccp.c
blobd63bba953cfead4856b8b9351506f442e42c967f
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92, 93, 94, 1995 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
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.
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.
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.
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! */
24 typedef unsigned char U_CHAR;
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 */
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 */
42 #ifndef STANDARD_INCLUDE_DIR
43 #define STANDARD_INCLUDE_DIR "/usr/include"
44 #endif
46 #ifndef LOCAL_INCLUDE_DIR
47 #define LOCAL_INCLUDE_DIR "/usr/local/include"
48 #endif
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 */
58 #include "pcp.h"
60 /* By default, colon separates directories in a path. */
61 #ifndef PATH_SEPARATOR
62 #define PATH_SEPARATOR ':'
63 #endif
65 /* In case config.h defines these. */
66 #undef bcopy
67 #undef bzero
68 #undef bcmp
70 #include <sys/types.h>
71 #include <sys/stat.h>
72 #include <ctype.h>
73 #include <stdio.h>
74 #include <signal.h>
76 #ifndef VMS
77 #ifndef USG
78 #include <sys/time.h> /* for __DATE__ and __TIME__ */
79 #include <sys/resource.h>
80 #else
81 #include <time.h>
82 #include <fcntl.h>
83 #endif /* USG */
84 #endif /* not VMS */
86 /* This defines "errno" properly for VMS, and gives us EACCES. */
87 #include <errno.h>
89 /* VMS-specific definitions */
90 #ifdef VMS
91 #include <time.h>
92 #include <descrip.h>
93 #define O_RDONLY 0 /* Open arg for Read/Only */
94 #define O_WRONLY 1 /* Open arg for Write/Only */
95 #define read(fd,buf,size) VMS_read (fd,buf,size)
96 #define write(fd,buf,size) VMS_write (fd,buf,size)
97 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
98 #define fopen(fname,mode) VMS_fopen (fname,mode)
99 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
100 #define strncat(dst,src,cnt) VMS_strncat (dst,src,cnt)
101 static char * VMS_strncat ();
102 static int VMS_read ();
103 static int VMS_write ();
104 static int VMS_open ();
105 static FILE * VMS_fopen ();
106 static FILE * VMS_freopen ();
107 static void hack_vms_include_specification ();
108 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
109 #define ino_t vms_ino_t
110 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
111 #ifdef __GNUC__
112 #define BSTRING /* VMS/GCC supplies the bstring routines */
113 #endif /* __GNUC__ */
114 #endif /* VMS */
116 extern char *index ();
117 extern char *rindex ();
119 #ifndef O_RDONLY
120 #define O_RDONLY 0
121 #endif
123 #undef MIN
124 #undef MAX
125 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
126 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
128 /* Find the largest host integer type and set its size and type. */
130 #ifndef HOST_BITS_PER_WIDE_INT
132 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
133 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
134 #define HOST_WIDE_INT long
135 #else
136 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
137 #define HOST_WIDE_INT int
138 #endif
140 #endif
142 #ifndef S_ISREG
143 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
144 #endif
146 #ifndef S_ISDIR
147 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
148 #endif
150 /* Define a generic NULL if one hasn't already been defined. */
152 #ifndef NULL
153 #define NULL 0
154 #endif
156 #ifndef GENERIC_PTR
157 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
158 #define GENERIC_PTR void *
159 #else
160 #define GENERIC_PTR char *
161 #endif
162 #endif
164 #ifndef NULL_PTR
165 #define NULL_PTR ((GENERIC_PTR)0)
166 #endif
168 #ifndef INCLUDE_LEN_FUDGE
169 #define INCLUDE_LEN_FUDGE 0
170 #endif
172 /* Forward declarations. */
174 char *xmalloc ();
175 void error ();
176 void warning ();
178 /* External declarations. */
180 extern char *getenv ();
181 extern FILE *fdopen ();
182 extern char *version_string;
183 extern struct tm *localtime ();
184 #ifndef VMS
185 #ifndef HAVE_STRERROR
186 extern int sys_nerr;
187 #if defined(bsd4_4) || defined(__NetBSD__)
188 extern const char *const sys_errlist[];
189 #else
190 extern char *sys_errlist[];
191 #endif
192 #else /* HAVE_STERRROR */
193 char *strerror ();
194 #endif
195 #else /* VMS */
196 char *strerror (int,...);
197 #endif
198 extern int parse_escape ();
199 extern HOST_WIDE_INT parse_c_expression ();
201 #ifndef errno
202 extern int errno;
203 #endif
205 /* Forward declarations. */
207 struct directive;
208 struct file_buf;
209 struct arglist;
210 struct argdata;
212 #if defined(USG) || defined(VMS)
213 #ifndef BSTRING
214 void bcopy ();
215 void bzero ();
216 int bcmp ();
217 #endif
218 #endif
220 /* These functions are declared to return int instead of void since they
221 are going to be placed in a table and some old compilers have trouble with
222 pointers to functions returning void. */
224 static int do_define ();
225 static int do_line ();
226 static int do_include ();
227 static int do_undef ();
228 static int do_error ();
229 static int do_pragma ();
230 static int do_ident ();
231 static int do_if ();
232 static int do_xifdef ();
233 static int do_else ();
234 static int do_elif ();
235 static int do_endif ();
236 static int do_sccs ();
237 static int do_once ();
238 static int do_assert ();
239 static int do_unassert ();
240 static int do_warning ();
242 static void add_import ();
243 static void append_include_chain ();
244 static void deps_output ();
245 static void make_undef ();
246 static void make_definition ();
247 static void make_assertion ();
248 static void path_include ();
249 static void initialize_builtins ();
250 static void initialize_char_syntax ();
251 static void dump_arg_n ();
252 static void dump_defn_1 ();
253 static void delete_macro ();
254 static void trigraph_pcp ();
255 static void rescan ();
256 static void finclude ();
257 static void validate_else ();
258 static int comp_def_part ();
259 static void error_from_errno ();
260 static void error_with_line ();
261 void pedwarn ();
262 void pedwarn_with_line ();
263 static void pedwarn_with_file_and_line ();
264 static void fatal ();
265 void fancy_abort ();
266 static void pfatal_with_name ();
267 static void perror_with_name ();
268 static void pipe_closed ();
269 static void print_containing_files ();
270 static int lookup_import ();
271 static int redundant_include_p ();
272 static is_system_include ();
273 static struct file_name_map *read_name_map ();
274 static char *read_filename_string ();
275 static int open_include_file ();
276 static int check_preconditions ();
277 static void pcfinclude ();
278 static void pcstring_used ();
279 static void write_output ();
280 static int check_macro_name ();
281 static int compare_defs ();
282 static int compare_token_lists ();
283 static HOST_WIDE_INT eval_if_expression ();
284 static int discard_comments ();
285 static int change_newlines ();
286 static int line_for_error ();
287 static int hashf ();
288 static int file_size_and_mode ();
290 static struct arglist *read_token_list ();
291 static void free_token_list ();
293 static struct hashnode *install ();
294 struct hashnode *lookup ();
296 static struct assertion_hashnode *assertion_install ();
297 static struct assertion_hashnode *assertion_lookup ();
299 static char *xrealloc ();
300 static char *xcalloc ();
301 static char *savestring ();
303 static void delete_assertion ();
304 static void macroexpand ();
305 static void dump_all_macros ();
306 static void conditional_skip ();
307 static void skip_if_group ();
308 static void output_line_command ();
310 /* Last arg to output_line_command. */
311 enum file_change_code {same_file, enter_file, leave_file};
313 static int grow_outbuf ();
314 static int handle_directive ();
315 static void memory_full ();
317 static U_CHAR *macarg1 ();
318 static char *macarg ();
320 static U_CHAR *skip_to_end_of_comment ();
321 static U_CHAR *skip_quoted_string ();
322 static U_CHAR *skip_paren_group ();
323 static char *quote_string ();
325 static char *check_precompiled ();
326 /* static struct macrodef create_definition (); [moved below] */
327 static void dump_single_macro ();
328 static void output_dots ();
330 #ifndef FAILURE_EXIT_CODE
331 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
332 #endif
334 #ifndef SUCCESS_EXIT_CODE
335 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
336 #endif
338 /* Name under which this program was invoked. */
340 static char *progname;
342 /* Nonzero means use extra default include directories for C++. */
344 static int cplusplus;
346 /* Nonzero means handle cplusplus style comments */
348 static int cplusplus_comments;
350 /* Nonzero means handle #import, for objective C. */
352 static int objc;
354 /* Nonzero means this is an assembly file, and allow
355 unknown directives, which could be comments. */
357 static int lang_asm;
359 /* Current maximum length of directory names in the search path
360 for include files. (Altered as we get more of them.) */
362 static int max_include_len;
364 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
366 static int for_lint = 0;
368 /* Nonzero means copy comments into the output file. */
370 static int put_out_comments = 0;
372 /* Nonzero means don't process the ANSI trigraph sequences. */
374 static int no_trigraphs = 0;
376 /* Nonzero means print the names of included files rather than
377 the preprocessed output. 1 means just the #include "...",
378 2 means #include <...> as well. */
380 static int print_deps = 0;
382 /* Nonzero if missing .h files in -M output are assumed to be generated
383 files and not errors. */
385 static int print_deps_missing_files = 0;
387 /* Nonzero means print names of header files (-H). */
389 static int print_include_names = 0;
391 /* Nonzero means don't output line number information. */
393 static int no_line_commands;
395 /* Nonzero means output the text in failing conditionals,
396 inside #failed ... #endfailed. */
398 static int output_conditionals;
400 /* dump_only means inhibit output of the preprocessed text
401 and instead output the definitions of all user-defined
402 macros in a form suitable for use as input to cccp.
403 dump_names means pass #define and the macro name through to output.
404 dump_definitions means pass the whole definition (plus #define) through
407 static enum {dump_none, dump_only, dump_names, dump_definitions}
408 dump_macros = dump_none;
410 /* Nonzero means pass all #define and #undef directives which we actually
411 process through to the output stream. This feature is used primarily
412 to allow cc1 to record the #defines and #undefs for the sake of
413 debuggers which understand about preprocessor macros, but it may
414 also be useful with -E to figure out how symbols are defined, and
415 where they are defined. */
416 static int debug_output = 0;
418 /* Nonzero indicates special processing used by the pcp program. The
419 special effects of this mode are:
421 Inhibit all macro expansion, except those inside #if directives.
423 Process #define directives normally, and output their contents
424 to the output file.
426 Output preconditions to pcp_outfile indicating all the relevant
427 preconditions for use of this file in a later cpp run.
429 static FILE *pcp_outfile;
431 /* Nonzero means we are inside an IF during a -pcp run. In this mode
432 macro expansion is done, and preconditions are output for all macro
433 uses requiring them. */
434 static int pcp_inside_if;
436 /* Nonzero means never to include precompiled files.
437 This is 1 since there's no way now to make precompiled files,
438 so it's not worth testing for them. */
439 static int no_precomp = 1;
441 /* Nonzero means give all the error messages the ANSI standard requires. */
443 int pedantic;
445 /* Nonzero means try to make failure to fit ANSI C an error. */
447 static int pedantic_errors;
449 /* Nonzero means don't print warning messages. -w. */
451 static int inhibit_warnings = 0;
453 /* Nonzero means warn if slash-star appears in a comment. */
455 static int warn_comments;
457 /* Nonzero means warn if a macro argument is (or would be)
458 stringified with -traditional. */
460 static int warn_stringify;
462 /* Nonzero means warn if there are any trigraphs. */
464 static int warn_trigraphs;
466 /* Nonzero means warn if #import is used. */
468 static int warn_import = 1;
470 /* Nonzero means turn warnings into errors. */
472 static int warnings_are_errors;
474 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
476 int traditional;
478 /* Nonzero causes output not to be done,
479 but directives such as #define that have side effects
480 are still obeyed. */
482 static int no_output;
484 /* Nonzero means this file was included with a -imacros or -include
485 command line and should not be recorded as an include file. */
487 static int no_record_file;
489 /* Nonzero means that we have finished processing the command line options.
490 This flag is used to decide whether or not to issue certain errors
491 and/or warnings. */
493 static int done_initializing = 0;
495 /* Line where a newline was first seen in a string constant. */
497 static int multiline_string_line = 0;
499 /* I/O buffer structure.
500 The `fname' field is nonzero for source files and #include files
501 and for the dummy text used for -D and -U.
502 It is zero for rescanning results of macro expansion
503 and for expanding macro arguments. */
504 #define INPUT_STACK_MAX 400
505 static struct file_buf {
506 char *fname;
507 /* Filename specified with #line command. */
508 char *nominal_fname;
509 /* Record where in the search path this file was found.
510 For #include_next. */
511 struct file_name_list *dir;
512 int lineno;
513 int length;
514 U_CHAR *buf;
515 U_CHAR *bufp;
516 /* Macro that this level is the expansion of.
517 Included so that we can reenable the macro
518 at the end of this level. */
519 struct hashnode *macro;
520 /* Value of if_stack at start of this file.
521 Used to prohibit unmatched #endif (etc) in an include file. */
522 struct if_stack *if_stack;
523 /* Object to be freed at end of input at this level. */
524 U_CHAR *free_ptr;
525 /* True if this is a header file included using <FILENAME>. */
526 char system_header_p;
527 } instack[INPUT_STACK_MAX];
529 static int last_error_tick; /* Incremented each time we print it. */
530 static int input_file_stack_tick; /* Incremented when the status changes. */
532 /* Current nesting level of input sources.
533 `instack[indepth]' is the level currently being read. */
534 static int indepth = -1;
535 #define CHECK_DEPTH(code) \
536 if (indepth >= (INPUT_STACK_MAX - 1)) \
538 error_with_line (line_for_error (instack[indepth].lineno), \
539 "macro or `#include' recursion too deep"); \
540 code; \
543 /* Current depth in #include directives that use <...>. */
544 static int system_include_depth = 0;
546 typedef struct file_buf FILE_BUF;
548 /* The output buffer. Its LENGTH field is the amount of room allocated
549 for the buffer, not the number of chars actually present. To get
550 that, subtract outbuf.buf from outbuf.bufp. */
552 #define OUTBUF_SIZE 10 /* initial size of output buffer */
553 static FILE_BUF outbuf;
555 /* Grow output buffer OBUF points at
556 so it can hold at least NEEDED more chars. */
558 #define check_expand(OBUF, NEEDED) \
559 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
560 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
562 struct file_name_list
564 struct file_name_list *next;
565 char *fname;
566 /* If the following is nonzero, it is a macro name.
567 Don't include the file again if that macro is defined. */
568 U_CHAR *control_macro;
569 /* If the following is nonzero, it is a C-language system include
570 directory. */
571 int c_system_include_path;
572 /* Mapping of file names for this directory. */
573 struct file_name_map *name_map;
574 /* Non-zero if name_map is valid. */
575 int got_name_map;
578 /* #include "file" looks in source file dir, then stack. */
579 /* #include <file> just looks in the stack. */
580 /* -I directories are added to the end, then the defaults are added. */
581 /* The */
582 static struct default_include {
583 char *fname; /* The name of the directory. */
584 int cplusplus; /* Only look here if we're compiling C++. */
585 int cxx_aware; /* Includes in this directory don't need to
586 be wrapped in extern "C" when compiling
587 C++. */
588 } include_defaults_array[]
589 #ifdef INCLUDE_DEFAULTS
590 = INCLUDE_DEFAULTS;
591 #else
593 /* Pick up GNU C++ specific include files. */
594 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
595 #ifdef CROSS_COMPILE
596 /* This is the dir for fixincludes. Put it just before
597 the files that we fix. */
598 { GCC_INCLUDE_DIR, 0, 0 },
599 /* For cross-compilation, this dir name is generated
600 automatically in Makefile.in. */
601 { CROSS_INCLUDE_DIR, 0, 0 },
602 /* This is another place that the target system's headers might be. */
603 { TOOL_INCLUDE_DIR, 0, 0 },
604 #else /* not CROSS_COMPILE */
605 /* This should be /usr/local/include and should come before
606 the fixincludes-fixed header files. */
607 { LOCAL_INCLUDE_DIR, 0, 1 },
608 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
609 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
610 { TOOL_INCLUDE_DIR, 0, 0 },
611 /* This is the dir for fixincludes. Put it just before
612 the files that we fix. */
613 { GCC_INCLUDE_DIR, 0, 0 },
614 /* Some systems have an extra dir of include files. */
615 #ifdef SYSTEM_INCLUDE_DIR
616 { SYSTEM_INCLUDE_DIR, 0, 0 },
617 #endif
618 { STANDARD_INCLUDE_DIR, 0, 0 },
619 #endif /* not CROSS_COMPILE */
620 { 0, 0, 0 }
622 #endif /* no INCLUDE_DEFAULTS */
624 /* The code looks at the defaults through this pointer, rather than through
625 the constant structure above. This pointer gets changed if an environment
626 variable specifies other defaults. */
627 static struct default_include *include_defaults = include_defaults_array;
629 static struct file_name_list *include = 0; /* First dir to search */
630 /* First dir to search for <file> */
631 /* This is the first element to use for #include <...>.
632 If it is 0, use the entire chain for such includes. */
633 static struct file_name_list *first_bracket_include = 0;
634 /* This is the first element in the chain that corresponds to
635 a directory of system header files. */
636 static struct file_name_list *first_system_include = 0;
637 static struct file_name_list *last_include = 0; /* Last in chain */
639 /* Chain of include directories to put at the end of the other chain. */
640 static struct file_name_list *after_include = 0;
641 static struct file_name_list *last_after_include = 0; /* Last in chain */
643 /* Chain to put at the start of the system include files. */
644 static struct file_name_list *before_system = 0;
645 static struct file_name_list *last_before_system = 0; /* Last in chain */
647 /* List of included files that contained #pragma once. */
648 static struct file_name_list *dont_repeat_files = 0;
650 /* List of other included files.
651 If ->control_macro if nonzero, the file had a #ifndef
652 around the entire contents, and ->control_macro gives the macro name. */
653 static struct file_name_list *all_include_files = 0;
655 /* Directory prefix that should replace `/usr' in the standard
656 include file directories. */
657 static char *include_prefix;
659 /* Global list of strings read in from precompiled files. This list
660 is kept in the order the strings are read in, with new strings being
661 added at the end through stringlist_tailp. We use this list to output
662 the strings at the end of the run.
664 static STRINGDEF *stringlist;
665 static STRINGDEF **stringlist_tailp = &stringlist;
668 /* Structure returned by create_definition */
669 typedef struct macrodef MACRODEF;
670 struct macrodef
672 struct definition *defn;
673 U_CHAR *symnam;
674 int symlen;
677 static struct macrodef create_definition ();
680 /* Structure allocated for every #define. For a simple replacement
681 such as
682 #define foo bar ,
683 nargs = -1, the `pattern' list is null, and the expansion is just
684 the replacement text. Nargs = 0 means a functionlike macro with no args,
685 e.g.,
686 #define getchar() getc (stdin) .
687 When there are args, the expansion is the replacement text with the
688 args squashed out, and the reflist is a list describing how to
689 build the output from the input: e.g., "3 chars, then the 1st arg,
690 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
691 The chars here come from the expansion. Whatever is left of the
692 expansion after the last arg-occurrence is copied after that arg.
693 Note that the reflist can be arbitrarily long---
694 its length depends on the number of times the arguments appear in
695 the replacement text, not how many args there are. Example:
696 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
697 pattern list
698 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
699 where (x, y) means (nchars, argno). */
701 typedef struct definition DEFINITION;
702 struct definition {
703 int nargs;
704 int length; /* length of expansion string */
705 int predefined; /* True if the macro was builtin or */
706 /* came from the command line */
707 U_CHAR *expansion;
708 int line; /* Line number of definition */
709 char *file; /* File of definition */
710 char rest_args; /* Nonzero if last arg. absorbs the rest */
711 struct reflist {
712 struct reflist *next;
714 /* The following three members have the value '#' if spelled with "#",
715 and '%' if spelled with "%:". */
716 char stringify; /* nonzero if this arg was preceded by a
717 # operator. */
718 char raw_before; /* Nonzero if a ## operator before arg. */
719 char raw_after; /* Nonzero if a ## operator after arg. */
721 char rest_args; /* Nonzero if this arg. absorbs the rest */
722 int nchars; /* Number of literal chars to copy before
723 this arg occurrence. */
724 int argno; /* Number of arg to substitute (origin-0) */
725 } *pattern;
726 union {
727 /* Names of macro args, concatenated in reverse order
728 with comma-space between them.
729 The only use of this is that we warn on redefinition
730 if this differs between the old and new definitions. */
731 U_CHAR *argnames;
732 } args;
735 /* different kinds of things that can appear in the value field
736 of a hash node. Actually, this may be useless now. */
737 union hashval {
738 char *cpval;
739 DEFINITION *defn;
740 KEYDEF *keydef;
744 * special extension string that can be added to the last macro argument to
745 * allow it to absorb the "rest" of the arguments when expanded. Ex:
746 * #define wow(a, b...) process (b, a, b)
747 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
748 * { wow (one, two); } -> { process (two, one, two); }
749 * if this "rest_arg" is used with the concat token '##' and if it is not
750 * supplied then the token attached to with ## will not be outputted. Ex:
751 * #define wow (a, b...) process (b ## , a, ## b)
752 * { wow (1, 2); } -> { process (2, 1, 2); }
753 * { wow (one); } -> { process (one); {
755 static char rest_extension[] = "...";
756 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
758 /* The structure of a node in the hash table. The hash table
759 has entries for all tokens defined by #define commands (type T_MACRO),
760 plus some special tokens like __LINE__ (these each have their own
761 type, and the appropriate code is run when that type of node is seen.
762 It does not contain control words like "#define", which are recognized
763 by a separate piece of code. */
765 /* different flavors of hash nodes --- also used in keyword table */
766 enum node_type {
767 T_DEFINE = 1, /* the `#define' keyword */
768 T_INCLUDE, /* the `#include' keyword */
769 T_INCLUDE_NEXT, /* the `#include_next' keyword */
770 T_IMPORT, /* the `#import' keyword */
771 T_IFDEF, /* the `#ifdef' keyword */
772 T_IFNDEF, /* the `#ifndef' keyword */
773 T_IF, /* the `#if' keyword */
774 T_ELSE, /* `#else' */
775 T_PRAGMA, /* `#pragma' */
776 T_ELIF, /* `#elif' */
777 T_UNDEF, /* `#undef' */
778 T_LINE, /* `#line' */
779 T_ERROR, /* `#error' */
780 T_WARNING, /* `#warning' */
781 T_ENDIF, /* `#endif' */
782 T_SCCS, /* `#sccs', used on system V. */
783 T_IDENT, /* `#ident', used on system V. */
784 T_ASSERT, /* `#assert', taken from system V. */
785 T_UNASSERT, /* `#unassert', taken from system V. */
786 T_SPECLINE, /* special symbol `__LINE__' */
787 T_DATE, /* `__DATE__' */
788 T_FILE, /* `__FILE__' */
789 T_BASE_FILE, /* `__BASE_FILE__' */
790 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
791 T_VERSION, /* `__VERSION__' */
792 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
793 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
794 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
795 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
796 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
797 T_TIME, /* `__TIME__' */
798 T_CONST, /* Constant value, used by `__STDC__' */
799 T_MACRO, /* macro defined by `#define' */
800 T_DISABLED, /* macro temporarily turned off for rescan */
801 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
802 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
803 T_UNUSED /* Used for something not defined. */
806 struct hashnode {
807 struct hashnode *next; /* double links for easy deletion */
808 struct hashnode *prev;
809 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
810 chain is kept, in case the node is the head
811 of the chain and gets deleted. */
812 enum node_type type; /* type of special token */
813 int length; /* length of token, for quick comparison */
814 U_CHAR *name; /* the actual name */
815 union hashval value; /* pointer to expansion, or whatever */
818 typedef struct hashnode HASHNODE;
820 /* Some definitions for the hash table. The hash function MUST be
821 computed as shown in hashf () below. That is because the rescan
822 loop computes the hash value `on the fly' for most tokens,
823 in order to avoid the overhead of a lot of procedure calls to
824 the hashf () function. Hashf () only exists for the sake of
825 politeness, for use when speed isn't so important. */
827 #define HASHSIZE 1403
828 static HASHNODE *hashtab[HASHSIZE];
829 #define HASHSTEP(old, c) ((old << 2) + c)
830 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
832 /* Symbols to predefine. */
834 #ifdef CPP_PREDEFINES
835 static char *predefs = CPP_PREDEFINES;
836 #else
837 static char *predefs = "";
838 #endif
840 /* We let tm.h override the types used here, to handle trivial differences
841 such as the choice of unsigned int or long unsigned int for size_t.
842 When machines start needing nontrivial differences in the size type,
843 it would be best to do something here to figure out automatically
844 from other information what type to use. */
846 /* The string value for __SIZE_TYPE__. */
848 #ifndef SIZE_TYPE
849 #define SIZE_TYPE "long unsigned int"
850 #endif
852 /* The string value for __PTRDIFF_TYPE__. */
854 #ifndef PTRDIFF_TYPE
855 #define PTRDIFF_TYPE "long int"
856 #endif
858 /* The string value for __WCHAR_TYPE__. */
860 #ifndef WCHAR_TYPE
861 #define WCHAR_TYPE "int"
862 #endif
863 char * wchar_type = WCHAR_TYPE;
864 #undef WCHAR_TYPE
866 /* The string value for __USER_LABEL_PREFIX__ */
868 #ifndef USER_LABEL_PREFIX
869 #define USER_LABEL_PREFIX ""
870 #endif
872 /* The string value for __REGISTER_PREFIX__ */
874 #ifndef REGISTER_PREFIX
875 #define REGISTER_PREFIX ""
876 #endif
878 /* In the definition of a #assert name, this structure forms
879 a list of the individual values asserted.
880 Each value is itself a list of "tokens".
881 These are strings that are compared by name. */
883 struct tokenlist_list {
884 struct tokenlist_list *next;
885 struct arglist *tokens;
888 struct assertion_hashnode {
889 struct assertion_hashnode *next; /* double links for easy deletion */
890 struct assertion_hashnode *prev;
891 /* also, a back pointer to this node's hash
892 chain is kept, in case the node is the head
893 of the chain and gets deleted. */
894 struct assertion_hashnode **bucket_hdr;
895 int length; /* length of token, for quick comparison */
896 U_CHAR *name; /* the actual name */
897 /* List of token-sequences. */
898 struct tokenlist_list *value;
901 typedef struct assertion_hashnode ASSERTION_HASHNODE;
903 /* Some definitions for the hash table. The hash function MUST be
904 computed as shown in hashf below. That is because the rescan
905 loop computes the hash value `on the fly' for most tokens,
906 in order to avoid the overhead of a lot of procedure calls to
907 the hashf function. hashf only exists for the sake of
908 politeness, for use when speed isn't so important. */
910 #define ASSERTION_HASHSIZE 37
911 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
913 /* Nonzero means inhibit macroexpansion of what seem to be
914 assertion tests, in rescan. For #if. */
915 static int assertions_flag;
917 /* `struct directive' defines one #-directive, including how to handle it. */
919 struct directive {
920 int length; /* Length of name */
921 int (*func)(); /* Function to handle directive */
922 char *name; /* Name of directive */
923 enum node_type type; /* Code which describes which directive. */
924 char angle_brackets; /* Nonzero => <...> is special. */
925 char traditional_comments; /* Nonzero: keep comments if -traditional. */
926 char pass_thru; /* Copy preprocessed directive to output file. */
929 /* Here is the actual list of #-directives, most-often-used first. */
931 static struct directive directive_table[] = {
932 { 6, do_define, "define", T_DEFINE, 0, 1},
933 { 2, do_if, "if", T_IF},
934 { 5, do_xifdef, "ifdef", T_IFDEF},
935 { 6, do_xifdef, "ifndef", T_IFNDEF},
936 { 5, do_endif, "endif", T_ENDIF},
937 { 4, do_else, "else", T_ELSE},
938 { 4, do_elif, "elif", T_ELIF},
939 { 4, do_line, "line", T_LINE},
940 { 7, do_include, "include", T_INCLUDE, 1},
941 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
942 { 6, do_include, "import", T_IMPORT, 1},
943 { 5, do_undef, "undef", T_UNDEF},
944 { 5, do_error, "error", T_ERROR},
945 { 7, do_warning, "warning", T_WARNING},
946 #ifdef SCCS_DIRECTIVE
947 { 4, do_sccs, "sccs", T_SCCS},
948 #endif
949 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
950 { 5, do_ident, "ident", T_IDENT},
951 { 6, do_assert, "assert", T_ASSERT},
952 { 8, do_unassert, "unassert", T_UNASSERT},
953 { -1, 0, "", T_UNUSED},
956 /* When a directive handler is called,
957 this points to the # (or the : of the %:) that started the directive. */
958 U_CHAR *directive_start;
960 /* table to tell if char can be part of a C identifier. */
961 U_CHAR is_idchar[256];
962 /* table to tell if char can be first char of a c identifier. */
963 U_CHAR is_idstart[256];
964 /* table to tell if c is horizontal space. */
965 U_CHAR is_hor_space[256];
966 /* table to tell if c is horizontal or vertical space. */
967 static U_CHAR is_space[256];
968 /* names of some characters */
969 static char *char_name[256];
971 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
972 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
974 static int errors = 0; /* Error counter for exit code */
976 /* Name of output file, for error messages. */
977 static char *out_fname;
979 /* Zero means dollar signs are punctuation.
980 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
981 This must be 0 for correct processing of this ANSI C program:
982 #define foo(a) #a
983 #define lose(b) foo (b)
984 #define test$
985 lose (test) */
986 static int dollars_in_ident;
987 #ifndef DOLLARS_IN_IDENTIFIERS
988 #define DOLLARS_IN_IDENTIFIERS 1
989 #endif
991 static FILE_BUF expand_to_temp_buffer ();
993 static DEFINITION *collect_expansion ();
995 /* Stack of conditionals currently in progress
996 (including both successful and failing conditionals). */
998 struct if_stack {
999 struct if_stack *next; /* for chaining to the next stack frame */
1000 char *fname; /* copied from input when frame is made */
1001 int lineno; /* similarly */
1002 int if_succeeded; /* true if a leg of this if-group
1003 has been passed through rescan */
1004 U_CHAR *control_macro; /* For #ifndef at start of file,
1005 this is the macro name tested. */
1006 enum node_type type; /* type of last directive seen in this group */
1008 typedef struct if_stack IF_STACK_FRAME;
1009 static IF_STACK_FRAME *if_stack = NULL;
1011 /* Buffer of -M output. */
1012 static char *deps_buffer;
1014 /* Number of bytes allocated in above. */
1015 static int deps_allocated_size;
1017 /* Number of bytes used. */
1018 static int deps_size;
1020 /* Number of bytes since the last newline. */
1021 static int deps_column;
1023 /* Nonzero means -I- has been seen,
1024 so don't look for #include "foo" the source-file directory. */
1025 static int ignore_srcdir;
1027 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1028 retrying if necessary. Return a negative value if an error occurs,
1029 otherwise return the actual number of bytes read,
1030 which must be LEN unless end-of-file was reached. */
1032 static int
1033 safe_read (desc, ptr, len)
1034 int desc;
1035 char *ptr;
1036 int len;
1038 int left = len;
1039 while (left > 0) {
1040 int nchars = read (desc, ptr, left);
1041 if (nchars < 0)
1043 #ifdef EINTR
1044 if (errno == EINTR)
1045 continue;
1046 #endif
1047 return nchars;
1049 if (nchars == 0)
1050 break;
1051 ptr += nchars;
1052 left -= nchars;
1054 return len - left;
1057 /* Write LEN bytes at PTR to descriptor DESC,
1058 retrying if necessary, and treating any real error as fatal. */
1060 static void
1061 safe_write (desc, ptr, len)
1062 int desc;
1063 char *ptr;
1064 int len;
1066 while (len > 0) {
1067 int written = write (desc, ptr, len);
1068 if (written < 0)
1070 #ifdef EINTR
1071 if (errno == EINTR)
1072 continue;
1073 #endif
1074 pfatal_with_name (out_fname);
1076 ptr += written;
1077 len -= written;
1082 main (argc, argv)
1083 int argc;
1084 char **argv;
1086 int st_mode;
1087 long st_size;
1088 char *in_fname;
1089 char *p;
1090 int f, i;
1091 FILE_BUF *fp;
1092 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1093 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1094 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1095 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1096 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1098 /* Record the option used with each element of pend_assertions.
1099 This is preparation for supporting more than one option for making
1100 an assertion. */
1101 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1102 int inhibit_predefs = 0;
1103 int no_standard_includes = 0;
1104 int no_standard_cplusplus_includes = 0;
1105 int missing_newline = 0;
1107 /* Non-0 means don't output the preprocessed program. */
1108 int inhibit_output = 0;
1109 /* Non-0 means -v, so print the full set of include dirs. */
1110 int verbose = 0;
1112 /* File name which deps are being written to.
1113 This is 0 if deps are being written to stdout. */
1114 char *deps_file = 0;
1115 /* Fopen file mode to open deps_file with. */
1116 char *deps_mode = "a";
1117 /* Stream on which to print the dependency information. */
1118 FILE *deps_stream = 0;
1119 /* Target-name to write with the dependency information. */
1120 char *deps_target = 0;
1122 #ifdef RLIMIT_STACK
1123 /* Get rid of any avoidable limit on stack size. */
1125 struct rlimit rlim;
1127 /* Set the stack limit huge so that alloca (particularly stringtab
1128 * in dbxread.c) does not fail. */
1129 getrlimit (RLIMIT_STACK, &rlim);
1130 rlim.rlim_cur = rlim.rlim_max;
1131 setrlimit (RLIMIT_STACK, &rlim);
1133 #endif /* RLIMIT_STACK defined */
1135 #ifdef SIGPIPE
1136 signal (SIGPIPE, pipe_closed);
1137 #endif
1139 p = argv[0] + strlen (argv[0]);
1140 while (p != argv[0] && p[-1] != '/'
1141 #ifdef DIR_SEPARATOR
1142 && p[-1] != DIR_SEPARATOR
1143 #endif
1145 --p;
1146 progname = p;
1148 #ifdef VMS
1150 /* Remove directories from PROGNAME. */
1151 char *s = progname;
1153 if ((p = rindex (s, ':')) != 0) s = p + 1; /* skip device */
1154 if ((p = rindex (s, ']')) != 0) s = p + 1; /* skip directory */
1155 if ((p = rindex (s, '>')) != 0) s = p + 1; /* alternate (int'n'l) dir */
1156 s = progname = savestring (s);
1157 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1158 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1159 && (p[1] == 'e' || p[1] == 'E')
1160 && (p[2] == 'x' || p[2] == 'X')
1161 && (p[3] == 'e' || p[3] == 'E')
1162 && !p[4])
1163 *p = '\0';
1165 #endif
1167 in_fname = NULL;
1168 out_fname = NULL;
1170 /* Initialize is_idchar to allow $. */
1171 dollars_in_ident = 1;
1172 initialize_char_syntax ();
1173 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1175 no_line_commands = 0;
1176 no_trigraphs = 1;
1177 dump_macros = dump_none;
1178 no_output = 0;
1179 cplusplus = 0;
1180 cplusplus_comments = 0;
1182 bzero ((char *) pend_files, argc * sizeof (char *));
1183 bzero ((char *) pend_defs, argc * sizeof (char *));
1184 bzero ((char *) pend_undefs, argc * sizeof (char *));
1185 bzero ((char *) pend_assertions, argc * sizeof (char *));
1186 bzero ((char *) pend_includes, argc * sizeof (char *));
1188 /* Process switches and find input file name. */
1190 for (i = 1; i < argc; i++) {
1191 if (argv[i][0] != '-') {
1192 if (out_fname != NULL)
1193 fatal ("Usage: %s [switches] input output", argv[0]);
1194 else if (in_fname != NULL)
1195 out_fname = argv[i];
1196 else
1197 in_fname = argv[i];
1198 } else {
1199 switch (argv[i][1]) {
1201 case 'i':
1202 if (!strcmp (argv[i], "-include")) {
1203 if (i + 1 == argc)
1204 fatal ("Filename missing after `-include' option");
1205 else
1206 pend_includes[i] = argv[i+1], i++;
1208 if (!strcmp (argv[i], "-imacros")) {
1209 if (i + 1 == argc)
1210 fatal ("Filename missing after `-imacros' option");
1211 else
1212 pend_files[i] = argv[i+1], i++;
1214 if (!strcmp (argv[i], "-iprefix")) {
1215 if (i + 1 == argc)
1216 fatal ("Filename missing after `-iprefix' option");
1217 else
1218 include_prefix = argv[++i];
1220 if (!strcmp (argv[i], "-ifoutput")) {
1221 output_conditionals = 1;
1223 if (!strcmp (argv[i], "-isystem")) {
1224 struct file_name_list *dirtmp;
1226 if (i + 1 == argc)
1227 fatal ("Filename missing after `-isystem' option");
1229 dirtmp = (struct file_name_list *)
1230 xmalloc (sizeof (struct file_name_list));
1231 dirtmp->next = 0;
1232 dirtmp->control_macro = 0;
1233 dirtmp->c_system_include_path = 1;
1234 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1]) + 1);
1235 strcpy (dirtmp->fname, argv[++i]);
1236 dirtmp->got_name_map = 0;
1238 if (before_system == 0)
1239 before_system = dirtmp;
1240 else
1241 last_before_system->next = dirtmp;
1242 last_before_system = dirtmp; /* Tail follows the last one */
1244 /* Add directory to end of path for includes,
1245 with the default prefix at the front of its name. */
1246 if (!strcmp (argv[i], "-iwithprefix")) {
1247 struct file_name_list *dirtmp;
1248 char *prefix;
1250 if (include_prefix != 0)
1251 prefix = include_prefix;
1252 else {
1253 prefix = savestring (GCC_INCLUDE_DIR);
1254 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1255 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1256 prefix[strlen (prefix) - 7] = 0;
1259 dirtmp = (struct file_name_list *)
1260 xmalloc (sizeof (struct file_name_list));
1261 dirtmp->next = 0; /* New one goes on the end */
1262 dirtmp->control_macro = 0;
1263 dirtmp->c_system_include_path = 0;
1264 if (i + 1 == argc)
1265 fatal ("Directory name missing after `-iwithprefix' option");
1267 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1268 + strlen (prefix) + 1);
1269 strcpy (dirtmp->fname, prefix);
1270 strcat (dirtmp->fname, argv[++i]);
1271 dirtmp->got_name_map = 0;
1273 if (after_include == 0)
1274 after_include = dirtmp;
1275 else
1276 last_after_include->next = dirtmp;
1277 last_after_include = dirtmp; /* Tail follows the last one */
1279 /* Add directory to main path for includes,
1280 with the default prefix at the front of its name. */
1281 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1282 struct file_name_list *dirtmp;
1283 char *prefix;
1285 if (include_prefix != 0)
1286 prefix = include_prefix;
1287 else {
1288 prefix = savestring (GCC_INCLUDE_DIR);
1289 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1290 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1291 prefix[strlen (prefix) - 7] = 0;
1294 dirtmp = (struct file_name_list *)
1295 xmalloc (sizeof (struct file_name_list));
1296 dirtmp->next = 0; /* New one goes on the end */
1297 dirtmp->control_macro = 0;
1298 dirtmp->c_system_include_path = 0;
1299 if (i + 1 == argc)
1300 fatal ("Directory name missing after `-iwithprefixbefore' option");
1302 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1303 + strlen (prefix) + 1);
1304 strcpy (dirtmp->fname, prefix);
1305 strcat (dirtmp->fname, argv[++i]);
1306 dirtmp->got_name_map = 0;
1308 append_include_chain (dirtmp, dirtmp);
1310 /* Add directory to end of path for includes. */
1311 if (!strcmp (argv[i], "-idirafter")) {
1312 struct file_name_list *dirtmp;
1314 dirtmp = (struct file_name_list *)
1315 xmalloc (sizeof (struct file_name_list));
1316 dirtmp->next = 0; /* New one goes on the end */
1317 dirtmp->control_macro = 0;
1318 dirtmp->c_system_include_path = 0;
1319 if (i + 1 == argc)
1320 fatal ("Directory name missing after `-idirafter' option");
1321 else
1322 dirtmp->fname = argv[++i];
1323 dirtmp->got_name_map = 0;
1325 if (after_include == 0)
1326 after_include = dirtmp;
1327 else
1328 last_after_include->next = dirtmp;
1329 last_after_include = dirtmp; /* Tail follows the last one */
1331 break;
1333 case 'o':
1334 if (out_fname != NULL)
1335 fatal ("Output filename specified twice");
1336 if (i + 1 == argc)
1337 fatal ("Filename missing after -o option");
1338 out_fname = argv[++i];
1339 if (!strcmp (out_fname, "-"))
1340 out_fname = "";
1341 break;
1343 case 'p':
1344 if (!strcmp (argv[i], "-pedantic"))
1345 pedantic = 1;
1346 else if (!strcmp (argv[i], "-pedantic-errors")) {
1347 pedantic = 1;
1348 pedantic_errors = 1;
1349 } else if (!strcmp (argv[i], "-pcp")) {
1350 char *pcp_fname;
1351 if (i + 1 == argc)
1352 fatal ("Filename missing after -pcp option");
1353 pcp_fname = argv[++i];
1354 pcp_outfile =
1355 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1356 ? fopen (pcp_fname, "w")
1357 : fdopen (dup (fileno (stdout)), "w"));
1358 if (pcp_outfile == 0)
1359 pfatal_with_name (pcp_fname);
1360 no_precomp = 1;
1362 break;
1364 case 't':
1365 if (!strcmp (argv[i], "-traditional")) {
1366 traditional = 1;
1367 if (dollars_in_ident > 0)
1368 dollars_in_ident = 1;
1369 } else if (!strcmp (argv[i], "-trigraphs")) {
1370 no_trigraphs = 0;
1372 break;
1374 case 'l':
1375 if (! strcmp (argv[i], "-lang-c"))
1376 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1377 if (! strcmp (argv[i], "-lang-c++"))
1378 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1379 if (! strcmp (argv[i], "-lang-c-c++-comments"))
1380 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1381 if (! strcmp (argv[i], "-lang-objc"))
1382 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1383 if (! strcmp (argv[i], "-lang-objc++"))
1384 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1385 if (! strcmp (argv[i], "-lang-asm"))
1386 lang_asm = 1;
1387 if (! strcmp (argv[i], "-lint"))
1388 for_lint = 1;
1389 break;
1391 case '+':
1392 cplusplus = 1, cplusplus_comments = 1;
1393 break;
1395 case 'w':
1396 inhibit_warnings = 1;
1397 break;
1399 case 'W':
1400 if (!strcmp (argv[i], "-Wtrigraphs"))
1401 warn_trigraphs = 1;
1402 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1403 warn_trigraphs = 0;
1404 else if (!strcmp (argv[i], "-Wcomment"))
1405 warn_comments = 1;
1406 else if (!strcmp (argv[i], "-Wno-comment"))
1407 warn_comments = 0;
1408 else if (!strcmp (argv[i], "-Wcomments"))
1409 warn_comments = 1;
1410 else if (!strcmp (argv[i], "-Wno-comments"))
1411 warn_comments = 0;
1412 else if (!strcmp (argv[i], "-Wtraditional"))
1413 warn_stringify = 1;
1414 else if (!strcmp (argv[i], "-Wno-traditional"))
1415 warn_stringify = 0;
1416 else if (!strcmp (argv[i], "-Wimport"))
1417 warn_import = 1;
1418 else if (!strcmp (argv[i], "-Wno-import"))
1419 warn_import = 0;
1420 else if (!strcmp (argv[i], "-Werror"))
1421 warnings_are_errors = 1;
1422 else if (!strcmp (argv[i], "-Wno-error"))
1423 warnings_are_errors = 0;
1424 else if (!strcmp (argv[i], "-Wall"))
1426 warn_trigraphs = 1;
1427 warn_comments = 1;
1429 break;
1431 case 'M':
1432 /* The style of the choices here is a bit mixed.
1433 The chosen scheme is a hybrid of keeping all options in one string
1434 and specifying each option in a separate argument:
1435 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1436 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1437 -M[M][G][D file]. This is awkward to handle in specs, and is not
1438 as extensible. */
1439 /* ??? -MG must be specified in addition to one of -M or -MM.
1440 This can be relaxed in the future without breaking anything.
1441 The converse isn't true. */
1443 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1444 if (!strcmp (argv[i], "-MG"))
1446 print_deps_missing_files = 1;
1447 break;
1449 if (!strcmp (argv[i], "-M"))
1450 print_deps = 2;
1451 else if (!strcmp (argv[i], "-MM"))
1452 print_deps = 1;
1453 else if (!strcmp (argv[i], "-MD"))
1454 print_deps = 2;
1455 else if (!strcmp (argv[i], "-MMD"))
1456 print_deps = 1;
1457 /* For -MD and -MMD options, write deps on file named by next arg. */
1458 if (!strcmp (argv[i], "-MD")
1459 || !strcmp (argv[i], "-MMD")) {
1460 if (i + 1 == argc)
1461 fatal ("Filename missing after %s option", argv[i]);
1462 i++;
1463 deps_file = argv[i];
1464 deps_mode = "w";
1465 } else {
1466 /* For -M and -MM, write deps on standard output
1467 and suppress the usual output. */
1468 deps_stream = stdout;
1469 inhibit_output = 1;
1471 break;
1473 case 'd':
1475 char *p = argv[i] + 2;
1476 char c;
1477 while (c = *p++) {
1478 /* Arg to -d specifies what parts of macros to dump */
1479 switch (c) {
1480 case 'M':
1481 dump_macros = dump_only;
1482 no_output = 1;
1483 break;
1484 case 'N':
1485 dump_macros = dump_names;
1486 break;
1487 case 'D':
1488 dump_macros = dump_definitions;
1489 break;
1493 break;
1495 case 'g':
1496 if (argv[i][2] == '3')
1497 debug_output = 1;
1498 break;
1500 case 'v':
1501 fprintf (stderr, "GNU CPP version %s", version_string);
1502 #ifdef TARGET_VERSION
1503 TARGET_VERSION;
1504 #endif
1505 fprintf (stderr, "\n");
1506 verbose = 1;
1507 break;
1509 case 'H':
1510 print_include_names = 1;
1511 break;
1513 case 'D':
1514 if (argv[i][2] != 0)
1515 pend_defs[i] = argv[i] + 2;
1516 else if (i + 1 == argc)
1517 fatal ("Macro name missing after -D option");
1518 else
1519 i++, pend_defs[i] = argv[i];
1520 break;
1522 case 'A':
1524 char *p;
1526 if (argv[i][2] != 0)
1527 p = argv[i] + 2;
1528 else if (i + 1 == argc)
1529 fatal ("Assertion missing after -A option");
1530 else
1531 p = argv[++i];
1533 if (!strcmp (p, "-")) {
1534 /* -A- eliminates all predefined macros and assertions.
1535 Let's include also any that were specified earlier
1536 on the command line. That way we can get rid of any
1537 that were passed automatically in from GCC. */
1538 int j;
1539 inhibit_predefs = 1;
1540 for (j = 0; j < i; j++)
1541 pend_defs[j] = pend_assertions[j] = 0;
1542 } else {
1543 pend_assertions[i] = p;
1544 pend_assertion_options[i] = "-A";
1547 break;
1549 case 'U': /* JF #undef something */
1550 if (argv[i][2] != 0)
1551 pend_undefs[i] = argv[i] + 2;
1552 else if (i + 1 == argc)
1553 fatal ("Macro name missing after -U option");
1554 else
1555 pend_undefs[i] = argv[i+1], i++;
1556 break;
1558 case 'C':
1559 put_out_comments = 1;
1560 break;
1562 case 'E': /* -E comes from cc -E; ignore it. */
1563 break;
1565 case 'P':
1566 no_line_commands = 1;
1567 break;
1569 case '$': /* Don't include $ in identifiers. */
1570 dollars_in_ident = 0;
1571 break;
1573 case 'I': /* Add directory to path for includes. */
1575 struct file_name_list *dirtmp;
1577 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1578 ignore_srcdir = 1;
1579 /* Don't use any preceding -I directories for #include <...>. */
1580 first_bracket_include = 0;
1582 else {
1583 dirtmp = (struct file_name_list *)
1584 xmalloc (sizeof (struct file_name_list));
1585 dirtmp->next = 0; /* New one goes on the end */
1586 dirtmp->control_macro = 0;
1587 dirtmp->c_system_include_path = 0;
1588 if (argv[i][2] != 0)
1589 dirtmp->fname = argv[i] + 2;
1590 else if (i + 1 == argc)
1591 fatal ("Directory name missing after -I option");
1592 else
1593 dirtmp->fname = argv[++i];
1594 dirtmp->got_name_map = 0;
1595 append_include_chain (dirtmp, dirtmp);
1598 break;
1600 case 'n':
1601 if (!strcmp (argv[i], "-nostdinc"))
1602 /* -nostdinc causes no default include directories.
1603 You must specify all include-file directories with -I. */
1604 no_standard_includes = 1;
1605 else if (!strcmp (argv[i], "-nostdinc++"))
1606 /* -nostdinc++ causes no default C++-specific include directories. */
1607 no_standard_cplusplus_includes = 1;
1608 else if (!strcmp (argv[i], "-noprecomp"))
1609 no_precomp = 1;
1610 break;
1612 case 'u':
1613 /* Sun compiler passes undocumented switch "-undef".
1614 Let's assume it means to inhibit the predefined symbols. */
1615 inhibit_predefs = 1;
1616 break;
1618 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1619 if (in_fname == NULL) {
1620 in_fname = "";
1621 break;
1622 } else if (out_fname == NULL) {
1623 out_fname = "";
1624 break;
1625 } /* else fall through into error */
1627 default:
1628 fatal ("Invalid option `%s'", argv[i]);
1633 /* Add dirs from CPATH after dirs from -I. */
1634 /* There seems to be confusion about what CPATH should do,
1635 so for the moment it is not documented. */
1636 /* Some people say that CPATH should replace the standard include dirs,
1637 but that seems pointless: it comes before them, so it overrides them
1638 anyway. */
1639 p = (char *) getenv ("CPATH");
1640 if (p != 0 && ! no_standard_includes)
1641 path_include (p);
1643 /* Now that dollars_in_ident is known, initialize is_idchar. */
1644 initialize_char_syntax ();
1646 /* Initialize output buffer */
1648 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1649 outbuf.bufp = outbuf.buf;
1650 outbuf.length = OUTBUF_SIZE;
1652 /* Do partial setup of input buffer for the sake of generating
1653 early #line directives (when -g is in effect). */
1655 fp = &instack[++indepth];
1656 if (in_fname == NULL)
1657 in_fname = "";
1658 fp->nominal_fname = fp->fname = in_fname;
1659 fp->lineno = 0;
1661 /* In C++, wchar_t is a distinct basic type, and we can expect
1662 __wchar_t to be defined by cc1plus. */
1663 if (cplusplus)
1664 wchar_type = "__wchar_t";
1666 /* Install __LINE__, etc. Must follow initialize_char_syntax
1667 and option processing. */
1668 initialize_builtins (fp, &outbuf);
1670 /* Do standard #defines and assertions
1671 that identify system and machine type. */
1673 if (!inhibit_predefs) {
1674 char *p = (char *) alloca (strlen (predefs) + 1);
1675 strcpy (p, predefs);
1676 while (*p) {
1677 char *q;
1678 while (*p == ' ' || *p == '\t')
1679 p++;
1680 /* Handle -D options. */
1681 if (p[0] == '-' && p[1] == 'D') {
1682 q = &p[2];
1683 while (*p && *p != ' ' && *p != '\t')
1684 p++;
1685 if (*p != 0)
1686 *p++= 0;
1687 if (debug_output)
1688 output_line_command (fp, &outbuf, 0, same_file);
1689 make_definition (q, &outbuf);
1690 while (*p == ' ' || *p == '\t')
1691 p++;
1692 } else if (p[0] == '-' && p[1] == 'A') {
1693 /* Handle -A options (assertions). */
1694 char *assertion;
1695 char *past_name;
1696 char *value;
1697 char *past_value;
1698 char *termination;
1699 int save_char;
1701 assertion = &p[2];
1702 past_name = assertion;
1703 /* Locate end of name. */
1704 while (*past_name && *past_name != ' '
1705 && *past_name != '\t' && *past_name != '(')
1706 past_name++;
1707 /* Locate `(' at start of value. */
1708 value = past_name;
1709 while (*value && (*value == ' ' || *value == '\t'))
1710 value++;
1711 if (*value++ != '(')
1712 abort ();
1713 while (*value && (*value == ' ' || *value == '\t'))
1714 value++;
1715 past_value = value;
1716 /* Locate end of value. */
1717 while (*past_value && *past_value != ' '
1718 && *past_value != '\t' && *past_value != ')')
1719 past_value++;
1720 termination = past_value;
1721 while (*termination && (*termination == ' ' || *termination == '\t'))
1722 termination++;
1723 if (*termination++ != ')')
1724 abort ();
1725 if (*termination && *termination != ' ' && *termination != '\t')
1726 abort ();
1727 /* Temporarily null-terminate the value. */
1728 save_char = *termination;
1729 *termination = '\0';
1730 /* Install the assertion. */
1731 make_assertion ("-A", assertion);
1732 *termination = (char) save_char;
1733 p = termination;
1734 while (*p == ' ' || *p == '\t')
1735 p++;
1736 } else {
1737 abort ();
1742 /* Now handle the command line options. */
1744 /* Do -U's, -D's and -A's in the order they were seen. */
1745 for (i = 1; i < argc; i++) {
1746 if (pend_undefs[i]) {
1747 if (debug_output)
1748 output_line_command (fp, &outbuf, 0, same_file);
1749 make_undef (pend_undefs[i], &outbuf);
1751 if (pend_defs[i]) {
1752 if (debug_output)
1753 output_line_command (fp, &outbuf, 0, same_file);
1754 make_definition (pend_defs[i], &outbuf);
1756 if (pend_assertions[i])
1757 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1760 done_initializing = 1;
1762 { /* read the appropriate environment variable and if it exists
1763 replace include_defaults with the listed path. */
1764 char *epath = 0;
1765 switch ((objc << 1) + cplusplus)
1767 case 0:
1768 epath = getenv ("C_INCLUDE_PATH");
1769 break;
1770 case 1:
1771 epath = getenv ("CPLUS_INCLUDE_PATH");
1772 break;
1773 case 2:
1774 epath = getenv ("OBJC_INCLUDE_PATH");
1775 break;
1776 case 3:
1777 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1778 break;
1780 /* If the environment var for this language is set,
1781 add to the default list of include directories. */
1782 if (epath) {
1783 char *nstore = (char *) alloca (strlen (epath) + 2);
1784 int num_dirs;
1785 char *startp, *endp;
1787 for (num_dirs = 1, startp = epath; *startp; startp++)
1788 if (*startp == PATH_SEPARATOR)
1789 num_dirs++;
1790 include_defaults
1791 = (struct default_include *) xmalloc ((num_dirs
1792 * sizeof (struct default_include))
1793 + sizeof (include_defaults_array));
1794 startp = endp = epath;
1795 num_dirs = 0;
1796 while (1) {
1797 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1798 if ((*endp == PATH_SEPARATOR
1799 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
1800 #ifdef __MSDOS__
1801 && (endp-startp != 1 || !isalpha (*startp))
1802 #endif
1803 #endif
1805 || *endp == 0) {
1806 strncpy (nstore, startp, endp-startp);
1807 if (endp == startp)
1808 strcpy (nstore, ".");
1809 else
1810 nstore[endp-startp] = '\0';
1812 include_defaults[num_dirs].fname = savestring (nstore);
1813 include_defaults[num_dirs].cplusplus = cplusplus;
1814 include_defaults[num_dirs].cxx_aware = 1;
1815 num_dirs++;
1816 if (*endp == '\0')
1817 break;
1818 endp = startp = endp + 1;
1819 } else
1820 endp++;
1822 /* Put the usual defaults back in at the end. */
1823 bcopy ((char *) include_defaults_array,
1824 (char *) &include_defaults[num_dirs],
1825 sizeof (include_defaults_array));
1829 append_include_chain (before_system, last_before_system);
1830 first_system_include = before_system;
1832 /* Unless -fnostdinc,
1833 tack on the standard include file dirs to the specified list */
1834 if (!no_standard_includes) {
1835 struct default_include *p = include_defaults;
1836 char *specd_prefix = include_prefix;
1837 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1838 int default_len = 0;
1839 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1840 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1841 default_len = strlen (default_prefix) - 7;
1842 default_prefix[default_len] = 0;
1844 /* Search "translated" versions of GNU directories.
1845 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1846 if (specd_prefix != 0 && default_len != 0)
1847 for (p = include_defaults; p->fname; p++) {
1848 /* Some standard dirs are only for C++. */
1849 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1850 /* Does this dir start with the prefix? */
1851 if (!strncmp (p->fname, default_prefix, default_len)) {
1852 /* Yes; change prefix and add to search list. */
1853 struct file_name_list *new
1854 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1855 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
1856 char *str = (char *) xmalloc (this_len + 1);
1857 strcpy (str, specd_prefix);
1858 strcat (str, p->fname + default_len);
1859 new->fname = str;
1860 new->control_macro = 0;
1861 new->c_system_include_path = !p->cxx_aware;
1862 new->got_name_map = 0;
1863 append_include_chain (new, new);
1864 if (first_system_include == 0)
1865 first_system_include = new;
1869 /* Search ordinary names for GNU include directories. */
1870 for (p = include_defaults; p->fname; p++) {
1871 /* Some standard dirs are only for C++. */
1872 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1873 struct file_name_list *new
1874 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1875 new->control_macro = 0;
1876 new->c_system_include_path = !p->cxx_aware;
1877 new->fname = p->fname;
1878 new->got_name_map = 0;
1879 append_include_chain (new, new);
1880 if (first_system_include == 0)
1881 first_system_include = new;
1886 /* Tack the after_include chain at the end of the include chain. */
1887 append_include_chain (after_include, last_after_include);
1888 if (first_system_include == 0)
1889 first_system_include = after_include;
1891 /* With -v, print the list of dirs to search. */
1892 if (verbose) {
1893 struct file_name_list *p;
1894 fprintf (stderr, "#include \"...\" search starts here:\n");
1895 for (p = include; p; p = p->next) {
1896 if (p == first_bracket_include)
1897 fprintf (stderr, "#include <...> search starts here:\n");
1898 fprintf (stderr, " %s\n", p->fname);
1900 fprintf (stderr, "End of search list.\n");
1903 /* Scan the -imacros files before the main input.
1904 Much like #including them, but with no_output set
1905 so that only their macro definitions matter. */
1907 no_output++; no_record_file++;
1908 for (i = 1; i < argc; i++)
1909 if (pend_files[i]) {
1910 int fd = open (pend_files[i], O_RDONLY, 0666);
1911 if (fd < 0) {
1912 perror_with_name (pend_files[i]);
1913 return FAILURE_EXIT_CODE;
1915 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
1917 no_output--; no_record_file--;
1919 /* Copy the entire contents of the main input file into
1920 the stacked input buffer previously allocated for it. */
1922 /* JF check for stdin */
1923 if (in_fname == NULL || *in_fname == 0) {
1924 in_fname = "";
1925 f = 0;
1926 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
1927 goto perror;
1929 /* -MG doesn't select the form of output and must be specified with one of
1930 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1931 inhibit compilation. */
1932 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1933 fatal ("-MG must be specified with one of -M or -MM");
1935 /* Either of two environment variables can specify output of deps.
1936 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1937 where OUTPUT_FILE is the file to write deps info to
1938 and DEPS_TARGET is the target to mention in the deps. */
1940 if (print_deps == 0
1941 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1942 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1943 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1944 char *s;
1945 char *output_file;
1947 if (spec == 0) {
1948 spec = getenv ("SUNPRO_DEPENDENCIES");
1949 print_deps = 2;
1951 else
1952 print_deps = 1;
1954 s = spec;
1955 /* Find the space before the DEPS_TARGET, if there is one. */
1956 /* This should use index. (mrs) */
1957 while (*s != 0 && *s != ' ') s++;
1958 if (*s != 0) {
1959 deps_target = s + 1;
1960 output_file = (char *) xmalloc (s - spec + 1);
1961 bcopy (spec, output_file, s - spec);
1962 output_file[s - spec] = 0;
1964 else {
1965 deps_target = 0;
1966 output_file = spec;
1969 deps_file = output_file;
1970 deps_mode = "a";
1973 /* For -M, print the expected object file name
1974 as the target of this Make-rule. */
1975 if (print_deps) {
1976 deps_allocated_size = 200;
1977 deps_buffer = (char *) xmalloc (deps_allocated_size);
1978 deps_buffer[0] = 0;
1979 deps_size = 0;
1980 deps_column = 0;
1982 if (deps_target) {
1983 deps_output (deps_target, ':');
1984 } else if (*in_fname == 0) {
1985 deps_output ("-", ':');
1986 } else {
1987 char *p, *q;
1988 int len;
1990 /* Discard all directory prefixes from filename. */
1991 if ((q = rindex (in_fname, '/')) != NULL
1992 #ifdef DIR_SEPARATOR
1993 && (q = rindex (in_fname, DIR_SEPARATOR)) != NULL
1994 #endif
1996 ++q;
1997 else
1998 q = in_fname;
2000 /* Copy remainder to mungable area. */
2001 p = (char *) alloca (strlen(q) + 8);
2002 strcpy (p, q);
2004 /* Output P, but remove known suffixes. */
2005 len = strlen (p);
2006 q = p + len;
2007 if (len >= 2
2008 && p[len - 2] == '.'
2009 && index("cCsSm", p[len - 1]))
2010 q = p + (len - 2);
2011 else if (len >= 3
2012 && p[len - 3] == '.'
2013 && p[len - 2] == 'c'
2014 && p[len - 1] == 'c')
2015 q = p + (len - 3);
2016 else if (len >= 4
2017 && p[len - 4] == '.'
2018 && p[len - 3] == 'c'
2019 && p[len - 2] == 'x'
2020 && p[len - 1] == 'x')
2021 q = p + (len - 4);
2022 else if (len >= 4
2023 && p[len - 4] == '.'
2024 && p[len - 3] == 'c'
2025 && p[len - 2] == 'p'
2026 && p[len - 1] == 'p')
2027 q = p + (len - 4);
2029 /* Supply our own suffix. */
2030 #ifndef VMS
2031 strcpy (q, ".o");
2032 #else
2033 strcpy (q, ".obj");
2034 #endif
2036 deps_output (p, ':');
2037 deps_output (in_fname, ' ');
2041 file_size_and_mode (f, &st_mode, &st_size);
2042 fp->nominal_fname = fp->fname = in_fname;
2043 fp->lineno = 1;
2044 fp->system_header_p = 0;
2045 /* JF all this is mine about reading pipes and ttys */
2046 if (! S_ISREG (st_mode)) {
2047 /* Read input from a file that is not a normal disk file.
2048 We cannot preallocate a buffer with the correct size,
2049 so we must read in the file a piece at the time and make it bigger. */
2050 int size;
2051 int bsize;
2052 int cnt;
2054 bsize = 2000;
2055 size = 0;
2056 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2057 for (;;) {
2058 cnt = safe_read (f, fp->buf + size, bsize - size);
2059 if (cnt < 0) goto perror; /* error! */
2060 size += cnt;
2061 if (size != bsize) break; /* End of file */
2062 bsize *= 2;
2063 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2065 fp->length = size;
2066 } else {
2067 /* Read a file whose size we can determine in advance.
2068 For the sake of VMS, st_size is just an upper bound. */
2069 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2070 fp->length = safe_read (f, fp->buf, st_size);
2071 if (fp->length < 0) goto perror;
2073 fp->bufp = fp->buf;
2074 fp->if_stack = if_stack;
2076 /* Make sure data ends with a newline. And put a null after it. */
2078 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2079 /* Backslash-newline at end is not good enough. */
2080 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2081 fp->buf[fp->length++] = '\n';
2082 missing_newline = 1;
2084 fp->buf[fp->length] = '\0';
2086 /* Unless inhibited, convert trigraphs in the input. */
2088 if (!no_trigraphs)
2089 trigraph_pcp (fp);
2091 /* Now that we know the input file is valid, open the output. */
2093 if (!out_fname || !strcmp (out_fname, ""))
2094 out_fname = "stdout";
2095 else if (! freopen (out_fname, "w", stdout))
2096 pfatal_with_name (out_fname);
2098 output_line_command (fp, &outbuf, 0, same_file);
2100 /* Scan the -include files before the main input. */
2102 no_record_file++;
2103 for (i = 1; i < argc; i++)
2104 if (pend_includes[i]) {
2105 int fd = open (pend_includes[i], O_RDONLY, 0666);
2106 if (fd < 0) {
2107 perror_with_name (pend_includes[i]);
2108 return FAILURE_EXIT_CODE;
2110 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
2112 no_record_file--;
2114 /* Scan the input, processing macros and directives. */
2116 rescan (&outbuf, 0);
2118 if (missing_newline)
2119 fp->lineno--;
2121 if (pedantic && missing_newline)
2122 pedwarn ("file does not end in newline");
2124 /* Now we have processed the entire input
2125 Write whichever kind of output has been requested. */
2127 if (dump_macros == dump_only)
2128 dump_all_macros ();
2129 else if (! inhibit_output) {
2130 write_output ();
2133 if (print_deps) {
2134 /* Don't actually write the deps file if compilation has failed. */
2135 if (errors == 0) {
2136 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2137 pfatal_with_name (deps_file);
2138 fputs (deps_buffer, deps_stream);
2139 putc ('\n', deps_stream);
2140 if (deps_file) {
2141 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2142 fatal ("I/O error on output");
2147 if (pcp_outfile && pcp_outfile != stdout
2148 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2149 fatal ("I/O error on `-pcp' output");
2151 if (ferror (stdout) || fclose (stdout) != 0)
2152 fatal ("I/O error on output");
2154 if (errors)
2155 exit (FAILURE_EXIT_CODE);
2156 exit (SUCCESS_EXIT_CODE);
2158 perror:
2159 pfatal_with_name (in_fname);
2160 return 0;
2163 /* Given a colon-separated list of file names PATH,
2164 add all the names to the search path for include files. */
2166 static void
2167 path_include (path)
2168 char *path;
2170 char *p;
2172 p = path;
2174 if (*p)
2175 while (1) {
2176 char *q = p;
2177 char *name;
2178 struct file_name_list *dirtmp;
2180 /* Find the end of this name. */
2181 while (*q != 0 && *q != PATH_SEPARATOR) q++;
2182 if (p == q) {
2183 /* An empty name in the path stands for the current directory. */
2184 name = (char *) xmalloc (2);
2185 name[0] = '.';
2186 name[1] = 0;
2187 } else {
2188 /* Otherwise use the directory that is named. */
2189 name = (char *) xmalloc (q - p + 1);
2190 bcopy (p, name, q - p);
2191 name[q - p] = 0;
2194 dirtmp = (struct file_name_list *)
2195 xmalloc (sizeof (struct file_name_list));
2196 dirtmp->next = 0; /* New one goes on the end */
2197 dirtmp->control_macro = 0;
2198 dirtmp->c_system_include_path = 0;
2199 dirtmp->fname = name;
2200 dirtmp->got_name_map = 0;
2201 append_include_chain (dirtmp, dirtmp);
2203 /* Advance past this name. */
2204 p = q;
2205 if (*p == 0)
2206 break;
2207 /* Skip the colon. */
2208 p++;
2212 /* Return the address of the first character in S that equals C.
2213 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2214 Return 0 if there is no such character. Assume that C itself is not '\0'.
2215 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2216 but unfortunately memchr isn't autoconfigured yet. */
2218 static U_CHAR *
2219 index0 (s, c, n)
2220 U_CHAR *s;
2221 int c;
2222 int n;
2224 for (;;) {
2225 char *q = index (s, c);
2226 if (q)
2227 return (U_CHAR *) q;
2228 else {
2229 int l = strlen (s);
2230 if (l == n)
2231 return 0;
2232 l++;
2233 s += l;
2234 n -= l;
2239 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2240 before main CCCP processing. Name `pcp' is also in honor of the
2241 drugs the trigraph designers must have been on.
2243 Using an extra pass through the buffer takes a little extra time,
2244 but is infinitely less hairy than trying to handle trigraphs inside
2245 strings, etc. everywhere, and also makes sure that trigraphs are
2246 only translated in the top level of processing. */
2248 static void
2249 trigraph_pcp (buf)
2250 FILE_BUF *buf;
2252 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2253 int len;
2255 fptr = bptr = sptr = buf->buf;
2256 lptr = fptr + buf->length;
2257 while ((sptr = (U_CHAR *) index0 (sptr, '?', lptr - sptr)) != NULL) {
2258 if (*++sptr != '?')
2259 continue;
2260 switch (*++sptr) {
2261 case '=':
2262 c = '#';
2263 break;
2264 case '(':
2265 c = '[';
2266 break;
2267 case '/':
2268 c = '\\';
2269 break;
2270 case ')':
2271 c = ']';
2272 break;
2273 case '\'':
2274 c = '^';
2275 break;
2276 case '<':
2277 c = '{';
2278 break;
2279 case '!':
2280 c = '|';
2281 break;
2282 case '>':
2283 c = '}';
2284 break;
2285 case '-':
2286 c = '~';
2287 break;
2288 case '?':
2289 sptr--;
2290 continue;
2291 default:
2292 continue;
2294 len = sptr - fptr - 2;
2296 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2297 C, this will be memmove (). */
2298 if (bptr != fptr && len > 0)
2299 bcopy ((char *) fptr, (char *) bptr, len);
2301 bptr += len;
2302 *bptr++ = c;
2303 fptr = ++sptr;
2305 len = buf->length - (fptr - buf->buf);
2306 if (bptr != fptr && len > 0)
2307 bcopy ((char *) fptr, (char *) bptr, len);
2308 buf->length -= fptr - bptr;
2309 buf->buf[buf->length] = '\0';
2310 if (warn_trigraphs && fptr != bptr)
2311 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
2314 /* Move all backslash-newline pairs out of embarrassing places.
2315 Exchange all such pairs following BP
2316 with any potentially-embarrassing characters that follow them.
2317 Potentially-embarrassing characters are / and *
2318 (because a backslash-newline inside a comment delimiter
2319 would cause it not to be recognized). */
2321 static void
2322 newline_fix (bp)
2323 U_CHAR *bp;
2325 register U_CHAR *p = bp;
2327 /* First count the backslash-newline pairs here. */
2329 while (p[0] == '\\' && p[1] == '\n')
2330 p += 2;
2332 /* What follows the backslash-newlines is not embarrassing. */
2334 if (*p != '/' && *p != '*')
2335 return;
2337 /* Copy all potentially embarrassing characters
2338 that follow the backslash-newline pairs
2339 down to where the pairs originally started. */
2341 while (*p == '*' || *p == '/')
2342 *bp++ = *p++;
2344 /* Now write the same number of pairs after the embarrassing chars. */
2345 while (bp < p) {
2346 *bp++ = '\\';
2347 *bp++ = '\n';
2351 /* Like newline_fix but for use within a directive-name.
2352 Move any backslash-newlines up past any following symbol constituents. */
2354 static void
2355 name_newline_fix (bp)
2356 U_CHAR *bp;
2358 register U_CHAR *p = bp;
2360 /* First count the backslash-newline pairs here. */
2361 while (p[0] == '\\' && p[1] == '\n')
2362 p += 2;
2364 /* What follows the backslash-newlines is not embarrassing. */
2366 if (!is_idchar[*p])
2367 return;
2369 /* Copy all potentially embarrassing characters
2370 that follow the backslash-newline pairs
2371 down to where the pairs originally started. */
2373 while (is_idchar[*p])
2374 *bp++ = *p++;
2376 /* Now write the same number of pairs after the embarrassing chars. */
2377 while (bp < p) {
2378 *bp++ = '\\';
2379 *bp++ = '\n';
2383 /* Look for lint commands in comments.
2385 When we come in here, ibp points into a comment. Limit is as one expects.
2386 scan within the comment -- it should start, after lwsp, with a lint command.
2387 If so that command is returned as a (constant) string.
2389 Upon return, any arg will be pointed to with argstart and will be
2390 arglen long. Note that we don't parse that arg since it will just
2391 be printed out again.
2394 static char *
2395 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2396 register U_CHAR *ibp;
2397 register U_CHAR *limit;
2398 U_CHAR **argstart; /* point to command arg */
2399 int *arglen, *cmdlen; /* how long they are */
2401 long linsize;
2402 register U_CHAR *numptr; /* temp for arg parsing */
2404 *arglen = 0;
2406 SKIP_WHITE_SPACE (ibp);
2408 if (ibp >= limit) return NULL;
2410 linsize = limit - ibp;
2412 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2413 if ((linsize >= 10) && !strncmp (ibp, "NOTREACHED", 10)) {
2414 *cmdlen = 10;
2415 return "NOTREACHED";
2417 if ((linsize >= 8) && !strncmp (ibp, "ARGSUSED", 8)) {
2418 *cmdlen = 8;
2419 return "ARGSUSED";
2421 if ((linsize >= 11) && !strncmp (ibp, "LINTLIBRARY", 11)) {
2422 *cmdlen = 11;
2423 return "LINTLIBRARY";
2425 if ((linsize >= 7) && !strncmp (ibp, "VARARGS", 7)) {
2426 *cmdlen = 7;
2427 ibp += 7; linsize -= 7;
2428 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2430 /* OK, read a number */
2431 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2432 numptr++);
2433 *arglen = numptr - *argstart;
2434 return "VARARGS";
2436 return NULL;
2440 * The main loop of the program.
2442 * Read characters from the input stack, transferring them to the
2443 * output buffer OP.
2445 * Macros are expanded and push levels on the input stack.
2446 * At the end of such a level it is popped off and we keep reading.
2447 * At the end of any other kind of level, we return.
2448 * #-directives are handled, except within macros.
2450 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2451 * and insert them when appropriate. This is set while scanning macro
2452 * arguments before substitution. It is zero when scanning for final output.
2453 * There are three types of Newline markers:
2454 * * Newline - follows a macro name that was not expanded
2455 * because it appeared inside an expansion of the same macro.
2456 * This marker prevents future expansion of that identifier.
2457 * When the input is rescanned into the final output, these are deleted.
2458 * These are also deleted by ## concatenation.
2459 * * Newline Space (or Newline and any other whitespace character)
2460 * stands for a place that tokens must be separated or whitespace
2461 * is otherwise desirable, but where the ANSI standard specifies there
2462 * is no whitespace. This marker turns into a Space (or whichever other
2463 * whitespace char appears in the marker) in the final output,
2464 * but it turns into nothing in an argument that is stringified with #.
2465 * Such stringified arguments are the only place where the ANSI standard
2466 * specifies with precision that whitespace may not appear.
2468 * During this function, IP->bufp is kept cached in IBP for speed of access.
2469 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2470 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2471 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2472 * explicitly, and before RECACHE, since RECACHE uses OBP.
2475 static void
2476 rescan (op, output_marks)
2477 FILE_BUF *op;
2478 int output_marks;
2480 /* Character being scanned in main loop. */
2481 register U_CHAR c;
2483 /* Length of pending accumulated identifier. */
2484 register int ident_length = 0;
2486 /* Hash code of pending accumulated identifier. */
2487 register int hash = 0;
2489 /* Current input level (&instack[indepth]). */
2490 FILE_BUF *ip;
2492 /* Pointer for scanning input. */
2493 register U_CHAR *ibp;
2495 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2496 register U_CHAR *limit;
2498 /* Pointer for storing output. */
2499 register U_CHAR *obp;
2501 /* REDO_CHAR is nonzero if we are processing an identifier
2502 after backing up over the terminating character.
2503 Sometimes we process an identifier without backing up over
2504 the terminating character, if the terminating character
2505 is not special. Backing up is done so that the terminating character
2506 will be dispatched on again once the identifier is dealt with. */
2507 int redo_char = 0;
2509 /* 1 if within an identifier inside of which a concatenation
2510 marker (Newline -) has been seen. */
2511 int concatenated = 0;
2513 /* While scanning a comment or a string constant,
2514 this records the line it started on, for error messages. */
2515 int start_line;
2517 /* Record position of last `real' newline. */
2518 U_CHAR *beg_of_line;
2520 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2522 #define POPMACRO \
2523 do { ip->macro->type = T_MACRO; \
2524 if (ip->free_ptr) free (ip->free_ptr); \
2525 --indepth; } while (0)
2527 /* Reload `rescan's local variables that describe the current
2528 level of the input stack. */
2530 #define RECACHE \
2531 do { ip = &instack[indepth]; \
2532 ibp = ip->bufp; \
2533 limit = ip->buf + ip->length; \
2534 op->bufp = obp; \
2535 check_expand (op, limit - ibp); \
2536 beg_of_line = 0; \
2537 obp = op->bufp; } while (0)
2539 if (no_output && instack[indepth].fname != 0)
2540 skip_if_group (&instack[indepth], 1, NULL);
2542 obp = op->bufp;
2543 RECACHE;
2545 beg_of_line = ibp;
2547 /* Our caller must always put a null after the end of
2548 the input at each input stack level. */
2549 if (*limit != 0)
2550 abort ();
2552 while (1) {
2553 c = *ibp++;
2554 *obp++ = c;
2556 switch (c) {
2557 case '\\':
2558 if (*ibp == '\n' && !ip->macro) {
2559 /* At the top level, always merge lines ending with backslash-newline,
2560 even in middle of identifier. But do not merge lines in a macro,
2561 since backslash might be followed by a newline-space marker. */
2562 ++ibp;
2563 ++ip->lineno;
2564 --obp; /* remove backslash from obuf */
2565 break;
2567 /* If ANSI, backslash is just another character outside a string. */
2568 if (!traditional)
2569 goto randomchar;
2570 /* Otherwise, backslash suppresses specialness of following char,
2571 so copy it here to prevent the switch from seeing it.
2572 But first get any pending identifier processed. */
2573 if (ident_length > 0)
2574 goto specialchar;
2575 if (ibp < limit)
2576 *obp++ = *ibp++;
2577 break;
2579 case '%':
2580 if (ident_length || ip->macro || traditional)
2581 goto randomchar;
2582 if (ip->fname == 0 && beg_of_line == ip->buf)
2583 goto randomchar;
2584 while (*ibp == '\\' && ibp[1] == '\n') {
2585 ibp += 2;
2586 ++ip->lineno;
2588 if (*ibp != ':')
2589 break;
2590 /* Treat this %: digraph as if it were #. */
2591 /* Fall through. */
2593 case '#':
2594 if (assertions_flag) {
2595 /* Copy #foo (bar lose) without macro expansion. */
2596 obp[-1] = '#'; /* In case it was '%'. */
2597 SKIP_WHITE_SPACE (ibp);
2598 while (is_idchar[*ibp])
2599 *obp++ = *ibp++;
2600 SKIP_WHITE_SPACE (ibp);
2601 if (*ibp == '(') {
2602 ip->bufp = ibp;
2603 skip_paren_group (ip);
2604 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2605 obp += ip->bufp - ibp;
2606 ibp = ip->bufp;
2610 /* If this is expanding a macro definition, don't recognize
2611 preprocessor directives. */
2612 if (ip->macro != 0)
2613 goto randomchar;
2614 /* If this is expand_into_temp_buffer, recognize them
2615 only after an actual newline at this level,
2616 not at the beginning of the input level. */
2617 if (ip->fname == 0 && beg_of_line == ip->buf)
2618 goto randomchar;
2619 if (ident_length)
2620 goto specialchar;
2623 /* # keyword: a # must be first nonblank char on the line */
2624 if (beg_of_line == 0)
2625 goto randomchar;
2627 U_CHAR *bp;
2629 /* Scan from start of line, skipping whitespace, comments
2630 and backslash-newlines, and see if we reach this #.
2631 If not, this # is not special. */
2632 bp = beg_of_line;
2633 /* If -traditional, require # to be at beginning of line. */
2634 if (!traditional) {
2635 while (1) {
2636 if (is_hor_space[*bp])
2637 bp++;
2638 else if (*bp == '\\' && bp[1] == '\n')
2639 bp += 2;
2640 else if (*bp == '/' && bp[1] == '*') {
2641 bp += 2;
2642 while (!(*bp == '*' && bp[1] == '/'))
2643 bp++;
2644 bp += 2;
2646 /* There is no point in trying to deal with C++ // comments here,
2647 because if there is one, then this # must be part of the
2648 comment and we would never reach here. */
2649 else break;
2651 if (c == '%') {
2652 if (bp[0] != '%')
2653 break;
2654 while (bp[1] == '\\' && bp[2] == '\n')
2655 bp += 2;
2656 if (bp + 1 != ibp)
2657 break;
2658 /* %: appears at start of line; skip past the ':' too. */
2659 bp++;
2660 ibp++;
2663 if (bp + 1 != ibp)
2664 goto randomchar;
2667 /* This # can start a directive. */
2669 --obp; /* Don't copy the '#' */
2671 ip->bufp = ibp;
2672 op->bufp = obp;
2673 if (! handle_directive (ip, op)) {
2674 #ifdef USE_C_ALLOCA
2675 alloca (0);
2676 #endif
2677 /* Not a known directive: treat it as ordinary text.
2678 IP, OP, IBP, etc. have not been changed. */
2679 if (no_output && instack[indepth].fname) {
2680 /* If not generating expanded output,
2681 what we do with ordinary text is skip it.
2682 Discard everything until next # directive. */
2683 skip_if_group (&instack[indepth], 1, 0);
2684 RECACHE;
2685 beg_of_line = ibp;
2686 break;
2688 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2689 /* Don't expand an identifier that could be a macro directive.
2690 (Section 3.8.3 of the ANSI C standard) */
2691 SKIP_WHITE_SPACE (ibp);
2692 if (is_idstart[*ibp])
2694 *obp++ = *ibp++;
2695 while (is_idchar[*ibp])
2696 *obp++ = *ibp++;
2698 goto randomchar;
2700 #ifdef USE_C_ALLOCA
2701 alloca (0);
2702 #endif
2703 /* A # directive has been successfully processed. */
2704 /* If not generating expanded output, ignore everything until
2705 next # directive. */
2706 if (no_output && instack[indepth].fname)
2707 skip_if_group (&instack[indepth], 1, 0);
2708 obp = op->bufp;
2709 RECACHE;
2710 beg_of_line = ibp;
2711 break;
2713 case '\"': /* skip quoted string */
2714 case '\'':
2715 /* A single quoted string is treated like a double -- some
2716 programs (e.g., troff) are perverse this way */
2718 if (ident_length)
2719 goto specialchar;
2721 start_line = ip->lineno;
2723 /* Skip ahead to a matching quote. */
2725 while (1) {
2726 if (ibp >= limit) {
2727 if (ip->macro != 0) {
2728 /* try harder: this string crosses a macro expansion boundary.
2729 This can happen naturally if -traditional.
2730 Otherwise, only -D can make a macro with an unmatched quote. */
2731 POPMACRO;
2732 RECACHE;
2733 continue;
2735 if (!traditional) {
2736 error_with_line (line_for_error (start_line),
2737 "unterminated string or character constant");
2738 error_with_line (multiline_string_line,
2739 "possible real start of unterminated constant");
2740 multiline_string_line = 0;
2742 break;
2744 *obp++ = *ibp;
2745 switch (*ibp++) {
2746 case '\n':
2747 ++ip->lineno;
2748 ++op->lineno;
2749 /* Traditionally, end of line ends a string constant with no error.
2750 So exit the loop and record the new line. */
2751 if (traditional) {
2752 beg_of_line = ibp;
2753 goto while2end;
2755 if (c == '\'') {
2756 error_with_line (line_for_error (start_line),
2757 "unterminated character constant");
2758 goto while2end;
2760 if (pedantic && multiline_string_line == 0) {
2761 pedwarn_with_line (line_for_error (start_line),
2762 "string constant runs past end of line");
2764 if (multiline_string_line == 0)
2765 multiline_string_line = ip->lineno - 1;
2766 break;
2768 case '\\':
2769 if (ibp >= limit)
2770 break;
2771 if (*ibp == '\n') {
2772 /* Backslash newline is replaced by nothing at all,
2773 but keep the line counts correct. */
2774 --obp;
2775 ++ibp;
2776 ++ip->lineno;
2777 } else {
2778 /* ANSI stupidly requires that in \\ the second \
2779 is *not* prevented from combining with a newline. */
2780 while (*ibp == '\\' && ibp[1] == '\n') {
2781 ibp += 2;
2782 ++ip->lineno;
2784 *obp++ = *ibp++;
2786 break;
2788 case '\"':
2789 case '\'':
2790 if (ibp[-1] == c)
2791 goto while2end;
2792 break;
2795 while2end:
2796 break;
2798 case '/':
2799 if (*ibp == '\\' && ibp[1] == '\n')
2800 newline_fix (ibp);
2802 if (*ibp != '*'
2803 && !(cplusplus_comments && *ibp == '/'))
2804 goto randomchar;
2805 if (ip->macro != 0)
2806 goto randomchar;
2807 if (ident_length)
2808 goto specialchar;
2810 if (*ibp == '/') {
2811 /* C++ style comment... */
2812 start_line = ip->lineno;
2814 --ibp; /* Back over the slash */
2815 --obp;
2817 /* Comments are equivalent to spaces. */
2818 if (! put_out_comments)
2819 *obp++ = ' ';
2820 else {
2821 /* must fake up a comment here */
2822 *obp++ = '/';
2823 *obp++ = '/';
2826 U_CHAR *before_bp = ibp+2;
2828 while (ibp < limit) {
2829 if (ibp[-1] != '\\' && *ibp == '\n') {
2830 if (put_out_comments) {
2831 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2832 obp += ibp - before_bp;
2834 break;
2835 } else {
2836 if (*ibp == '\n') {
2837 ++ip->lineno;
2838 /* Copy the newline into the output buffer, in order to
2839 avoid the pain of a #line every time a multiline comment
2840 is seen. */
2841 if (!put_out_comments)
2842 *obp++ = '\n';
2843 ++op->lineno;
2845 ibp++;
2848 break;
2852 /* Ordinary C comment. Skip it, optionally copying it to output. */
2854 start_line = ip->lineno;
2856 ++ibp; /* Skip the star. */
2858 /* If this cpp is for lint, we peek inside the comments: */
2859 if (for_lint) {
2860 U_CHAR *argbp;
2861 int cmdlen, arglen;
2862 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2864 if (lintcmd != NULL) {
2865 op->bufp = obp;
2866 check_expand (op, cmdlen + arglen + 14);
2867 obp = op->bufp;
2868 /* I believe it is always safe to emit this newline: */
2869 obp[-1] = '\n';
2870 bcopy ("#pragma lint ", (char *) obp, 13);
2871 obp += 13;
2872 bcopy (lintcmd, (char *) obp, cmdlen);
2873 obp += cmdlen;
2875 if (arglen != 0) {
2876 *(obp++) = ' ';
2877 bcopy (argbp, (char *) obp, arglen);
2878 obp += arglen;
2881 /* OK, now bring us back to the state we were in before we entered
2882 this branch. We need #line because the #pragma's newline always
2883 messes up the line count. */
2884 op->bufp = obp;
2885 output_line_command (ip, op, 0, same_file);
2886 check_expand (op, limit - ibp + 2);
2887 obp = op->bufp;
2888 *(obp++) = '/';
2892 /* Comments are equivalent to spaces.
2893 Note that we already output the slash; we might not want it.
2894 For -traditional, a comment is equivalent to nothing. */
2895 if (! put_out_comments) {
2896 if (traditional)
2897 obp--;
2898 else
2899 obp[-1] = ' ';
2901 else
2902 *obp++ = '*';
2905 U_CHAR *before_bp = ibp;
2907 while (ibp < limit) {
2908 switch (*ibp++) {
2909 case '/':
2910 if (warn_comments && *ibp == '*')
2911 warning ("`/*' within comment");
2912 break;
2913 case '*':
2914 if (*ibp == '\\' && ibp[1] == '\n')
2915 newline_fix (ibp);
2916 if (ibp >= limit || *ibp == '/')
2917 goto comment_end;
2918 break;
2919 case '\n':
2920 ++ip->lineno;
2921 /* Copy the newline into the output buffer, in order to
2922 avoid the pain of a #line every time a multiline comment
2923 is seen. */
2924 if (!put_out_comments)
2925 *obp++ = '\n';
2926 ++op->lineno;
2929 comment_end:
2931 if (ibp >= limit)
2932 error_with_line (line_for_error (start_line),
2933 "unterminated comment");
2934 else {
2935 ibp++;
2936 if (put_out_comments) {
2937 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2938 obp += ibp - before_bp;
2942 break;
2944 case '$':
2945 if (!dollars_in_ident)
2946 goto randomchar;
2947 goto letter;
2949 case '0': case '1': case '2': case '3': case '4':
2950 case '5': case '6': case '7': case '8': case '9':
2951 /* If digit is not part of identifier, it starts a number,
2952 which means that following letters are not an identifier.
2953 "0x5" does not refer to an identifier "x5".
2954 So copy all alphanumerics that follow without accumulating
2955 as an identifier. Periods also, for sake of "3.e7". */
2957 if (ident_length == 0) {
2958 for (;;) {
2959 while (ibp[0] == '\\' && ibp[1] == '\n') {
2960 ++ip->lineno;
2961 ibp += 2;
2963 c = *ibp++;
2964 if (!is_idchar[c] && c != '.') {
2965 --ibp;
2966 break;
2968 *obp++ = c;
2969 /* A sign can be part of a preprocessing number
2970 if it follows an e. */
2971 if (c == 'e' || c == 'E') {
2972 while (ibp[0] == '\\' && ibp[1] == '\n') {
2973 ++ip->lineno;
2974 ibp += 2;
2976 if (*ibp == '+' || *ibp == '-') {
2977 *obp++ = *ibp++;
2978 /* But traditional C does not let the token go past the sign. */
2979 if (traditional)
2980 break;
2984 break;
2986 /* fall through */
2988 case '_':
2989 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2990 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2991 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
2992 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2993 case 'y': case 'z':
2994 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2995 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
2996 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
2997 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2998 case 'Y': case 'Z':
2999 letter:
3000 ident_length++;
3001 /* Compute step of hash function, to avoid a proc call on every token */
3002 hash = HASHSTEP (hash, c);
3003 break;
3005 case '\n':
3006 if (ip->fname == 0 && *ibp == '-') {
3007 /* Newline - inhibits expansion of preceding token.
3008 If expanding a macro arg, we keep the newline -.
3009 In final output, it is deleted.
3010 We recognize Newline - in macro bodies and macro args. */
3011 if (! concatenated) {
3012 ident_length = 0;
3013 hash = 0;
3015 ibp++;
3016 if (!output_marks) {
3017 obp--;
3018 } else {
3019 /* If expanding a macro arg, keep the newline -. */
3020 *obp++ = '-';
3022 break;
3025 /* If reprocessing a macro expansion, newline is a special marker. */
3026 else if (ip->macro != 0) {
3027 /* Newline White is a "funny space" to separate tokens that are
3028 supposed to be separate but without space between.
3029 Here White means any whitespace character.
3030 Newline - marks a recursive macro use that is not
3031 supposed to be expandable. */
3033 if (is_space[*ibp]) {
3034 /* Newline Space does not prevent expansion of preceding token
3035 so expand the preceding token and then come back. */
3036 if (ident_length > 0)
3037 goto specialchar;
3039 /* If generating final output, newline space makes a space. */
3040 if (!output_marks) {
3041 obp[-1] = *ibp++;
3042 /* And Newline Newline makes a newline, so count it. */
3043 if (obp[-1] == '\n')
3044 op->lineno++;
3045 } else {
3046 /* If expanding a macro arg, keep the newline space.
3047 If the arg gets stringified, newline space makes nothing. */
3048 *obp++ = *ibp++;
3050 } else abort (); /* Newline followed by something random? */
3051 break;
3054 /* If there is a pending identifier, handle it and come back here. */
3055 if (ident_length > 0)
3056 goto specialchar;
3058 beg_of_line = ibp;
3060 /* Update the line counts and output a #line if necessary. */
3061 ++ip->lineno;
3062 ++op->lineno;
3063 if (ip->lineno != op->lineno) {
3064 op->bufp = obp;
3065 output_line_command (ip, op, 1, same_file);
3066 check_expand (op, limit - ibp);
3067 obp = op->bufp;
3069 break;
3071 /* Come here either after (1) a null character that is part of the input
3072 or (2) at the end of the input, because there is a null there. */
3073 case 0:
3074 if (ibp <= limit)
3075 /* Our input really contains a null character. */
3076 goto randomchar;
3078 /* At end of a macro-expansion level, pop it and read next level. */
3079 if (ip->macro != 0) {
3080 obp--;
3081 ibp--;
3082 /* If traditional, and we have an identifier that ends here,
3083 process it now, so we get the right error for recursion. */
3084 if (traditional && ident_length
3085 && ! is_idchar[*instack[indepth - 1].bufp]) {
3086 redo_char = 1;
3087 goto randomchar;
3089 POPMACRO;
3090 RECACHE;
3091 break;
3094 /* If we don't have a pending identifier,
3095 return at end of input. */
3096 if (ident_length == 0) {
3097 obp--;
3098 ibp--;
3099 op->bufp = obp;
3100 ip->bufp = ibp;
3101 goto ending;
3104 /* If we do have a pending identifier, just consider this null
3105 a special character and arrange to dispatch on it again.
3106 The second time, IDENT_LENGTH will be zero so we will return. */
3108 /* Fall through */
3110 specialchar:
3112 /* Handle the case of a character such as /, ', " or null
3113 seen following an identifier. Back over it so that
3114 after the identifier is processed the special char
3115 will be dispatched on again. */
3117 ibp--;
3118 obp--;
3119 redo_char = 1;
3121 default:
3123 randomchar:
3125 if (ident_length > 0) {
3126 register HASHNODE *hp;
3128 /* We have just seen an identifier end. If it's a macro, expand it.
3130 IDENT_LENGTH is the length of the identifier
3131 and HASH is its hash code.
3133 The identifier has already been copied to the output,
3134 so if it is a macro we must remove it.
3136 If REDO_CHAR is 0, the char that terminated the identifier
3137 has been skipped in the output and the input.
3138 OBP-IDENT_LENGTH-1 points to the identifier.
3139 If the identifier is a macro, we must back over the terminator.
3141 If REDO_CHAR is 1, the terminating char has already been
3142 backed over. OBP-IDENT_LENGTH points to the identifier. */
3144 if (!pcp_outfile || pcp_inside_if) {
3145 startagain:
3146 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3147 hp = hp->next) {
3149 if (hp->length == ident_length) {
3150 int obufp_before_macroname;
3151 int op_lineno_before_macroname;
3152 register int i = ident_length;
3153 register U_CHAR *p = hp->name;
3154 register U_CHAR *q = obp - i;
3155 int disabled;
3157 if (! redo_char)
3158 q--;
3160 do { /* All this to avoid a strncmp () */
3161 if (*p++ != *q++)
3162 goto hashcollision;
3163 } while (--i);
3165 /* We found a use of a macro name.
3166 see if the context shows it is a macro call. */
3168 /* Back up over terminating character if not already done. */
3169 if (! redo_char) {
3170 ibp--;
3171 obp--;
3174 /* Save this as a displacement from the beginning of the output
3175 buffer. We can not save this as a position in the output
3176 buffer, because it may get realloc'ed by RECACHE. */
3177 obufp_before_macroname = (obp - op->buf) - ident_length;
3178 op_lineno_before_macroname = op->lineno;
3180 if (hp->type == T_PCSTRING) {
3181 pcstring_used (hp); /* Mark the definition of this key
3182 as needed, ensuring that it
3183 will be output. */
3184 break; /* Exit loop, since the key cannot have a
3185 definition any longer. */
3188 /* Record whether the macro is disabled. */
3189 disabled = hp->type == T_DISABLED;
3191 /* This looks like a macro ref, but if the macro was disabled,
3192 just copy its name and put in a marker if requested. */
3194 if (disabled) {
3195 #if 0
3196 /* This error check caught useful cases such as
3197 #define foo(x,y) bar (x (y,0), y)
3198 foo (foo, baz) */
3199 if (traditional)
3200 error ("recursive use of macro `%s'", hp->name);
3201 #endif
3203 if (output_marks) {
3204 check_expand (op, limit - ibp + 2);
3205 *obp++ = '\n';
3206 *obp++ = '-';
3208 break;
3211 /* If macro wants an arglist, verify that a '(' follows.
3212 first skip all whitespace, copying it to the output
3213 after the macro name. Then, if there is no '(',
3214 decide this is not a macro call and leave things that way. */
3215 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3216 && hp->value.defn->nargs >= 0)
3218 U_CHAR *old_ibp = ibp;
3219 U_CHAR *old_obp = obp;
3220 int old_iln = ip->lineno;
3221 int old_oln = op->lineno;
3223 while (1) {
3224 /* Scan forward over whitespace, copying it to the output. */
3225 if (ibp == limit && ip->macro != 0) {
3226 POPMACRO;
3227 RECACHE;
3228 old_ibp = ibp;
3229 old_obp = obp;
3230 old_iln = ip->lineno;
3231 old_oln = op->lineno;
3233 /* A comment: copy it unchanged or discard it. */
3234 else if (*ibp == '/' && ibp[1] == '*') {
3235 if (put_out_comments) {
3236 *obp++ = '/';
3237 *obp++ = '*';
3238 } else if (! traditional) {
3239 *obp++ = ' ';
3241 ibp += 2;
3242 while (ibp + 1 != limit
3243 && !(ibp[0] == '*' && ibp[1] == '/')) {
3244 /* We need not worry about newline-marks,
3245 since they are never found in comments. */
3246 if (*ibp == '\n') {
3247 /* Newline in a file. Count it. */
3248 ++ip->lineno;
3249 ++op->lineno;
3251 if (put_out_comments)
3252 *obp++ = *ibp++;
3253 else
3254 ibp++;
3256 ibp += 2;
3257 if (put_out_comments) {
3258 *obp++ = '*';
3259 *obp++ = '/';
3262 else if (is_space[*ibp]) {
3263 *obp++ = *ibp++;
3264 if (ibp[-1] == '\n') {
3265 if (ip->macro == 0) {
3266 /* Newline in a file. Count it. */
3267 ++ip->lineno;
3268 ++op->lineno;
3269 } else if (!output_marks) {
3270 /* A newline mark, and we don't want marks
3271 in the output. If it is newline-hyphen,
3272 discard it entirely. Otherwise, it is
3273 newline-whitechar, so keep the whitechar. */
3274 obp--;
3275 if (*ibp == '-')
3276 ibp++;
3277 else {
3278 if (*ibp == '\n')
3279 ++op->lineno;
3280 *obp++ = *ibp++;
3282 } else {
3283 /* A newline mark; copy both chars to the output. */
3284 *obp++ = *ibp++;
3288 else break;
3290 if (*ibp != '(') {
3291 /* It isn't a macro call.
3292 Put back the space that we just skipped. */
3293 ibp = old_ibp;
3294 obp = old_obp;
3295 ip->lineno = old_iln;
3296 op->lineno = old_oln;
3297 /* Exit the for loop. */
3298 break;
3302 /* This is now known to be a macro call.
3303 Discard the macro name from the output,
3304 along with any following whitespace just copied,
3305 but preserve newlines if not outputting marks since this
3306 is more likely to do the right thing with line numbers. */
3307 obp = op->buf + obufp_before_macroname;
3308 if (output_marks)
3309 op->lineno = op_lineno_before_macroname;
3310 else {
3311 int newlines = op->lineno - op_lineno_before_macroname;
3312 while (0 < newlines--)
3313 *obp++ = '\n';
3316 /* Prevent accidental token-pasting with a character
3317 before the macro call. */
3318 if (!traditional && obp != op->buf) {
3319 switch (obp[-1]) {
3320 case '%': case '&': case '+': case '-':
3321 case ':': case '<': case '>': case '|':
3322 /* If we are expanding a macro arg, make a newline marker
3323 to separate the tokens. If we are making real output,
3324 a plain space will do. */
3325 if (output_marks)
3326 *obp++ = '\n';
3327 *obp++ = ' ';
3331 /* Expand the macro, reading arguments as needed,
3332 and push the expansion on the input stack. */
3333 ip->bufp = ibp;
3334 op->bufp = obp;
3335 macroexpand (hp, op);
3337 /* Reexamine input stack, since macroexpand has pushed
3338 a new level on it. */
3339 obp = op->bufp;
3340 RECACHE;
3341 break;
3343 hashcollision:
3345 } /* End hash-table-search loop */
3347 ident_length = hash = 0; /* Stop collecting identifier */
3348 redo_char = 0;
3349 concatenated = 0;
3350 } /* End if (ident_length > 0) */
3351 } /* End switch */
3352 } /* End per-char loop */
3354 /* Come here to return -- but first give an error message
3355 if there was an unterminated successful conditional. */
3356 ending:
3357 if (if_stack != ip->if_stack)
3359 char *str = "unknown";
3361 switch (if_stack->type)
3363 case T_IF:
3364 str = "if";
3365 break;
3366 case T_IFDEF:
3367 str = "ifdef";
3368 break;
3369 case T_IFNDEF:
3370 str = "ifndef";
3371 break;
3372 case T_ELSE:
3373 str = "else";
3374 break;
3375 case T_ELIF:
3376 str = "elif";
3377 break;
3380 error_with_line (line_for_error (if_stack->lineno),
3381 "unterminated `#%s' conditional", str);
3383 if_stack = ip->if_stack;
3387 * Rescan a string into a temporary buffer and return the result
3388 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3390 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3391 * and insert such markers when appropriate. See `rescan' for details.
3392 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3393 * before substitution; it is 0 for other uses.
3395 static FILE_BUF
3396 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3397 U_CHAR *buf, *limit;
3398 int output_marks, assertions;
3400 register FILE_BUF *ip;
3401 FILE_BUF obuf;
3402 int length = limit - buf;
3403 U_CHAR *buf1;
3404 int odepth = indepth;
3405 int save_assertions_flag = assertions_flag;
3407 assertions_flag = assertions;
3409 if (length < 0)
3410 abort ();
3412 /* Set up the input on the input stack. */
3414 buf1 = (U_CHAR *) alloca (length + 1);
3416 register U_CHAR *p1 = buf;
3417 register U_CHAR *p2 = buf1;
3419 while (p1 != limit)
3420 *p2++ = *p1++;
3422 buf1[length] = 0;
3424 /* Set up to receive the output. */
3426 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3427 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3428 obuf.fname = 0;
3429 obuf.macro = 0;
3430 obuf.free_ptr = 0;
3432 CHECK_DEPTH ({return obuf;});
3434 ++indepth;
3436 ip = &instack[indepth];
3437 ip->fname = 0;
3438 ip->nominal_fname = 0;
3439 ip->system_header_p = 0;
3440 ip->macro = 0;
3441 ip->free_ptr = 0;
3442 ip->length = length;
3443 ip->buf = ip->bufp = buf1;
3444 ip->if_stack = if_stack;
3446 ip->lineno = obuf.lineno = 1;
3448 /* Scan the input, create the output. */
3449 rescan (&obuf, output_marks);
3451 /* Pop input stack to original state. */
3452 --indepth;
3454 if (indepth != odepth)
3455 abort ();
3457 /* Record the output. */
3458 obuf.length = obuf.bufp - obuf.buf;
3460 assertions_flag = save_assertions_flag;
3461 return obuf;
3465 * Process a # directive. Expects IP->bufp to point after the '#', as in
3466 * `#define foo bar'. Passes to the command handler
3467 * (do_define, do_include, etc.): the addresses of the 1st and
3468 * last chars of the command (starting immediately after the #
3469 * keyword), plus op and the keyword table pointer. If the command
3470 * contains comments it is copied into a temporary buffer sans comments
3471 * and the temporary buffer is passed to the command handler instead.
3472 * Likewise for backslash-newlines.
3474 * Returns nonzero if this was a known # directive.
3475 * Otherwise, returns zero, without advancing the input pointer.
3478 static int
3479 handle_directive (ip, op)
3480 FILE_BUF *ip, *op;
3482 register U_CHAR *bp, *cp;
3483 register struct directive *kt;
3484 register int ident_length;
3485 U_CHAR *resume_p;
3487 /* Nonzero means we must copy the entire command
3488 to get rid of comments or backslash-newlines. */
3489 int copy_command = 0;
3491 U_CHAR *ident, *after_ident;
3493 bp = ip->bufp;
3495 /* Record where the directive started. do_xifdef needs this. */
3496 directive_start = bp - 1;
3498 /* Skip whitespace and \-newline. */
3499 while (1) {
3500 if (is_hor_space[*bp]) {
3501 if (*bp != ' ' && *bp != '\t' && pedantic)
3502 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3503 bp++;
3504 } else if (*bp == '/' && (bp[1] == '*'
3505 || (cplusplus_comments && bp[1] == '/'))) {
3506 ip->bufp = bp + 2;
3507 skip_to_end_of_comment (ip, &ip->lineno, 0);
3508 bp = ip->bufp;
3509 } else if (*bp == '\\' && bp[1] == '\n') {
3510 bp += 2; ip->lineno++;
3511 } else break;
3514 /* Now find end of directive name.
3515 If we encounter a backslash-newline, exchange it with any following
3516 symbol-constituents so that we end up with a contiguous name. */
3518 cp = bp;
3519 while (1) {
3520 if (is_idchar[*cp])
3521 cp++;
3522 else {
3523 if (*cp == '\\' && cp[1] == '\n')
3524 name_newline_fix (cp);
3525 if (is_idchar[*cp])
3526 cp++;
3527 else break;
3530 ident_length = cp - bp;
3531 ident = bp;
3532 after_ident = cp;
3534 /* A line of just `#' becomes blank. */
3536 if (ident_length == 0 && *after_ident == '\n') {
3537 ip->bufp = after_ident;
3538 return 1;
3541 if (ident_length == 0 || !is_idstart[*ident]) {
3542 U_CHAR *p = ident;
3543 while (is_idchar[*p]) {
3544 if (*p < '0' || *p > '9')
3545 break;
3546 p++;
3548 /* Handle # followed by a line number. */
3549 if (p != ident && !is_idchar[*p]) {
3550 static struct directive line_directive_table[] = {
3551 { 4, do_line, "line", T_LINE},
3553 if (pedantic)
3554 pedwarn ("`#' followed by integer");
3555 after_ident = ident;
3556 kt = line_directive_table;
3557 goto old_linenum;
3560 /* Avoid error for `###' and similar cases unless -pedantic. */
3561 if (p == ident) {
3562 while (*p == '#' || is_hor_space[*p]) p++;
3563 if (*p == '\n') {
3564 if (pedantic && !lang_asm)
3565 warning ("invalid preprocessor directive");
3566 return 0;
3570 if (!lang_asm)
3571 error ("invalid preprocessor directive name");
3573 return 0;
3577 * Decode the keyword and call the appropriate expansion
3578 * routine, after moving the input pointer up to the next line.
3580 for (kt = directive_table; kt->length > 0; kt++) {
3581 if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length)) {
3582 register U_CHAR *buf;
3583 register U_CHAR *limit;
3584 int unterminated;
3585 int junk;
3586 int *already_output;
3588 /* Nonzero means do not delete comments within the directive.
3589 #define needs this when -traditional. */
3590 int keep_comments;
3592 old_linenum:
3594 limit = ip->buf + ip->length;
3595 unterminated = 0;
3596 already_output = 0;
3597 keep_comments = traditional && kt->traditional_comments;
3598 /* #import is defined only in Objective C, or when on the NeXT. */
3599 if (kt->type == T_IMPORT && !(objc || lookup ("__NeXT__", -1, -1)))
3600 break;
3602 /* Find the end of this command (first newline not backslashed
3603 and not in a string or comment).
3604 Set COPY_COMMAND if the command must be copied
3605 (it contains a backslash-newline or a comment). */
3607 buf = bp = after_ident;
3608 while (bp < limit) {
3609 register U_CHAR c = *bp++;
3610 switch (c) {
3611 case '\\':
3612 if (bp < limit) {
3613 if (*bp == '\n') {
3614 ip->lineno++;
3615 copy_command = 1;
3616 bp++;
3617 } else if (traditional)
3618 bp++;
3620 break;
3622 case '\'':
3623 case '\"':
3624 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_command, &unterminated);
3625 /* Don't bother calling the directive if we already got an error
3626 message due to unterminated string. Skip everything and pretend
3627 we called the directive. */
3628 if (unterminated) {
3629 if (traditional) {
3630 /* Traditional preprocessing permits unterminated strings. */
3631 ip->bufp = bp;
3632 goto endloop1;
3634 ip->bufp = bp;
3635 return 1;
3637 break;
3639 /* <...> is special for #include. */
3640 case '<':
3641 if (!kt->angle_brackets)
3642 break;
3643 while (bp < limit && *bp != '>' && *bp != '\n') {
3644 if (*bp == '\\' && bp[1] == '\n') {
3645 ip->lineno++;
3646 copy_command = 1;
3647 bp++;
3649 bp++;
3651 break;
3653 case '/':
3654 if (*bp == '\\' && bp[1] == '\n')
3655 newline_fix (bp);
3656 if (*bp == '*'
3657 || (cplusplus_comments && *bp == '/')) {
3658 U_CHAR *obp = bp - 1;
3659 ip->bufp = bp + 1;
3660 skip_to_end_of_comment (ip, &ip->lineno, 0);
3661 bp = ip->bufp;
3662 /* No need to copy the command because of a comment at the end;
3663 just don't include the comment in the directive. */
3664 if (bp == limit || *bp == '\n') {
3665 bp = obp;
3666 goto endloop1;
3668 /* Don't remove the comments if -traditional. */
3669 if (! keep_comments)
3670 copy_command++;
3672 break;
3674 case '\f':
3675 case '\r':
3676 case '\v':
3677 if (pedantic)
3678 pedwarn ("%s in preprocessing directive", char_name[c]);
3679 break;
3681 case '\n':
3682 --bp; /* Point to the newline */
3683 ip->bufp = bp;
3684 goto endloop1;
3687 ip->bufp = bp;
3689 endloop1:
3690 resume_p = ip->bufp;
3691 /* BP is the end of the directive.
3692 RESUME_P is the next interesting data after the directive.
3693 A comment may come between. */
3695 /* If a directive should be copied through, and -E was given,
3696 pass it through before removing comments. */
3697 if (!no_output && kt->pass_thru && put_out_comments) {
3698 int len;
3700 /* Output directive name. */
3701 check_expand (op, kt->length + 2);
3702 /* Make sure # is at the start of a line */
3703 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3704 op->lineno++;
3705 *op->bufp++ = '\n';
3707 *op->bufp++ = '#';
3708 bcopy (kt->name, op->bufp, kt->length);
3709 op->bufp += kt->length;
3711 /* Output arguments. */
3712 len = (bp - buf);
3713 check_expand (op, len);
3714 bcopy (buf, (char *) op->bufp, len);
3715 op->bufp += len;
3716 /* Take account of any (escaped) newlines just output. */
3717 while (--len >= 0)
3718 if (buf[len] == '\n')
3719 op->lineno++;
3721 already_output = &junk;
3722 } /* Don't we need a newline or #line? */
3724 if (copy_command) {
3725 register U_CHAR *xp = buf;
3726 /* Need to copy entire command into temp buffer before dispatching */
3728 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
3729 some slop */
3730 buf = cp;
3732 /* Copy to the new buffer, deleting comments
3733 and backslash-newlines (and whitespace surrounding the latter). */
3735 while (xp < bp) {
3736 register U_CHAR c = *xp++;
3737 *cp++ = c;
3739 switch (c) {
3740 case '\n':
3741 abort (); /* A bare newline should never part of the line. */
3742 break;
3744 /* <...> is special for #include. */
3745 case '<':
3746 if (!kt->angle_brackets)
3747 break;
3748 while (xp < bp && c != '>') {
3749 c = *xp++;
3750 if (c == '\\' && xp < bp && *xp == '\n')
3751 xp++;
3752 else
3753 *cp++ = c;
3755 break;
3757 case '\\':
3758 if (*xp == '\n') {
3759 xp++;
3760 cp--;
3761 if (cp != buf && is_space[cp[-1]]) {
3762 while (cp != buf && is_space[cp[-1]]) cp--;
3763 cp++;
3764 SKIP_WHITE_SPACE (xp);
3765 } else if (is_space[*xp]) {
3766 *cp++ = *xp++;
3767 SKIP_WHITE_SPACE (xp);
3769 } else if (traditional && xp < bp) {
3770 *cp++ = *xp++;
3772 break;
3774 case '\'':
3775 case '\"':
3777 register U_CHAR *bp1
3778 = skip_quoted_string (xp - 1, bp, ip->lineno,
3779 NULL_PTR, NULL_PTR, NULL_PTR);
3780 while (xp != bp1)
3781 if (*xp == '\\') {
3782 if (*++xp != '\n')
3783 *cp++ = '\\';
3784 else
3785 xp++;
3786 } else
3787 *cp++ = *xp++;
3789 break;
3791 case '/':
3792 if (*xp == '*'
3793 || (cplusplus_comments && *xp == '/')) {
3794 ip->bufp = xp + 1;
3795 /* If we already copied the command through,
3796 already_output != 0 prevents outputting comment now. */
3797 skip_to_end_of_comment (ip, already_output, 0);
3798 if (keep_comments)
3799 while (xp != ip->bufp)
3800 *cp++ = *xp++;
3801 /* Delete or replace the slash. */
3802 else if (traditional)
3803 cp--;
3804 else
3805 cp[-1] = ' ';
3806 xp = ip->bufp;
3811 /* Null-terminate the copy. */
3813 *cp = 0;
3814 } else
3815 cp = bp;
3817 ip->bufp = resume_p;
3819 /* Some directives should be written out for cc1 to process,
3820 just as if they were not defined. And sometimes we're copying
3821 definitions through. */
3823 if (!no_output && already_output == 0
3824 && (kt->pass_thru
3825 || (kt->type == T_DEFINE
3826 && (dump_macros == dump_names
3827 || dump_macros == dump_definitions)))) {
3828 int len;
3830 /* Output directive name. */
3831 check_expand (op, kt->length + 1);
3832 *op->bufp++ = '#';
3833 bcopy (kt->name, (char *) op->bufp, kt->length);
3834 op->bufp += kt->length;
3836 if (kt->pass_thru || dump_macros == dump_definitions) {
3837 /* Output arguments. */
3838 len = (cp - buf);
3839 check_expand (op, len);
3840 bcopy (buf, (char *) op->bufp, len);
3841 op->bufp += len;
3842 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
3843 U_CHAR *xp = buf;
3844 U_CHAR *yp;
3845 SKIP_WHITE_SPACE (xp);
3846 yp = xp;
3847 while (is_idchar[*xp]) xp++;
3848 len = (xp - yp);
3849 check_expand (op, len + 1);
3850 *op->bufp++ = ' ';
3851 bcopy (yp, op->bufp, len);
3852 op->bufp += len;
3854 } /* Don't we need a newline or #line? */
3856 /* Call the appropriate command handler. buf now points to
3857 either the appropriate place in the input buffer, or to
3858 the temp buffer if it was necessary to make one. cp
3859 points to the first char after the contents of the (possibly
3860 copied) command, in either case. */
3861 (*kt->func) (buf, cp, op, kt);
3862 check_expand (op, ip->length - (ip->bufp - ip->buf));
3864 return 1;
3868 /* It is deliberate that we don't warn about undefined directives.
3869 That is the responsibility of cc1. */
3870 return 0;
3873 static struct tm *
3874 timestamp ()
3876 static struct tm *timebuf;
3877 if (!timebuf) {
3878 time_t t = time ((time_t *)0);
3879 timebuf = localtime (&t);
3881 return timebuf;
3884 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3885 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3889 * expand things like __FILE__. Place the expansion into the output
3890 * buffer *without* rescanning.
3893 static void
3894 special_symbol (hp, op)
3895 HASHNODE *hp;
3896 FILE_BUF *op;
3898 char *buf;
3899 int i, len;
3900 int true_indepth;
3901 FILE_BUF *ip = NULL;
3902 struct tm *timebuf;
3904 int paren = 0; /* For special `defined' keyword */
3906 if (pcp_outfile && pcp_inside_if
3907 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
3908 error ("Predefined macro `%s' used inside `#if' during precompilation",
3909 hp->name);
3911 for (i = indepth; i >= 0; i--)
3912 if (instack[i].fname != NULL) {
3913 ip = &instack[i];
3914 break;
3916 if (ip == NULL) {
3917 error ("cccp error: not in any file?!");
3918 return; /* the show must go on */
3921 switch (hp->type) {
3922 case T_FILE:
3923 case T_BASE_FILE:
3925 char *string;
3926 if (hp->type == T_FILE)
3927 string = ip->nominal_fname;
3928 else
3929 string = instack[0].nominal_fname;
3931 if (string)
3933 buf = (char *) alloca (3 + 4 * strlen (string));
3934 quote_string (buf, string);
3936 else
3937 buf = "\"\"";
3939 break;
3942 case T_INCLUDE_LEVEL:
3943 true_indepth = 0;
3944 for (i = indepth; i >= 0; i--)
3945 if (instack[i].fname != NULL)
3946 true_indepth++;
3948 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
3949 sprintf (buf, "%d", true_indepth - 1);
3950 break;
3952 case T_VERSION:
3953 buf = (char *) alloca (3 + strlen (version_string));
3954 sprintf (buf, "\"%s\"", version_string);
3955 break;
3957 #ifndef NO_BUILTIN_SIZE_TYPE
3958 case T_SIZE_TYPE:
3959 buf = SIZE_TYPE;
3960 break;
3961 #endif
3963 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3964 case T_PTRDIFF_TYPE:
3965 buf = PTRDIFF_TYPE;
3966 break;
3967 #endif
3969 case T_WCHAR_TYPE:
3970 buf = wchar_type;
3971 break;
3973 case T_USER_LABEL_PREFIX_TYPE:
3974 buf = USER_LABEL_PREFIX;
3975 break;
3977 case T_REGISTER_PREFIX_TYPE:
3978 buf = REGISTER_PREFIX;
3979 break;
3981 case T_CONST:
3982 buf = hp->value.cpval;
3983 if (pcp_inside_if && pcp_outfile)
3984 /* Output a precondition for this macro use */
3985 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
3986 break;
3988 case T_SPECLINE:
3989 buf = (char *) alloca (10);
3990 sprintf (buf, "%d", ip->lineno);
3991 break;
3993 case T_DATE:
3994 case T_TIME:
3995 buf = (char *) alloca (20);
3996 timebuf = timestamp ();
3997 if (hp->type == T_DATE)
3998 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3999 timebuf->tm_mday, timebuf->tm_year + 1900);
4000 else
4001 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4002 timebuf->tm_sec);
4003 break;
4005 case T_SPEC_DEFINED:
4006 buf = " 0 "; /* Assume symbol is not defined */
4007 ip = &instack[indepth];
4008 SKIP_WHITE_SPACE (ip->bufp);
4009 if (*ip->bufp == '(') {
4010 paren++;
4011 ip->bufp++; /* Skip over the paren */
4012 SKIP_WHITE_SPACE (ip->bufp);
4015 if (!is_idstart[*ip->bufp])
4016 goto oops;
4017 if (hp = lookup (ip->bufp, -1, -1)) {
4018 if (pcp_outfile && pcp_inside_if
4019 && (hp->type == T_CONST
4020 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4021 /* Output a precondition for this macro use. */
4022 fprintf (pcp_outfile, "#define %s\n", hp->name);
4023 buf = " 1 ";
4025 else
4026 if (pcp_outfile && pcp_inside_if) {
4027 /* Output a precondition for this macro use */
4028 U_CHAR *cp = ip->bufp;
4029 fprintf (pcp_outfile, "#undef ");
4030 while (is_idchar[*cp]) /* Ick! */
4031 fputc (*cp++, pcp_outfile);
4032 putc ('\n', pcp_outfile);
4034 while (is_idchar[*ip->bufp])
4035 ++ip->bufp;
4036 SKIP_WHITE_SPACE (ip->bufp);
4037 if (paren) {
4038 if (*ip->bufp != ')')
4039 goto oops;
4040 ++ip->bufp;
4042 break;
4044 oops:
4046 error ("`defined' without an identifier");
4047 break;
4049 default:
4050 error ("cccp error: invalid special hash type"); /* time for gdb */
4051 abort ();
4053 len = strlen (buf);
4054 check_expand (op, len);
4055 bcopy (buf, (char *) op->bufp, len);
4056 op->bufp += len;
4058 return;
4062 /* Routines to handle #directives */
4064 /* Handle #include and #import.
4065 This function expects to see "fname" or <fname> on the input. */
4067 static int
4068 do_include (buf, limit, op, keyword)
4069 U_CHAR *buf, *limit;
4070 FILE_BUF *op;
4071 struct directive *keyword;
4073 int importing = (keyword->type == T_IMPORT);
4074 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4075 static int import_warning = 0;
4076 char *fname; /* Dynamically allocated fname buffer */
4077 char *pcftry;
4078 char *pcfname;
4079 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
4081 struct file_name_list *search_start = include; /* Chain of dirs to search */
4082 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4083 struct file_name_list *searchptr = 0;
4084 int flen;
4086 int f; /* file number */
4088 int retried = 0; /* Have already tried macro
4089 expanding the include line*/
4090 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4091 int pcf = -1;
4092 char *pcfbuf;
4093 int pcfbuflimit;
4094 int pcfnum;
4095 f= -1; /* JF we iz paranoid! */
4097 if (importing && warn_import && !inhibit_warnings
4098 && !instack[indepth].system_header_p && !import_warning) {
4099 import_warning = 1;
4100 warning ("using `#import' is not recommended");
4101 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4102 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4103 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4104 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4105 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4106 fprintf (stderr, " ... <real contents of file> ...\n");
4107 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4108 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4109 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4110 fprintf (stderr, "when it is equipped with such a conditional.\n");
4113 get_filename:
4115 fbeg = buf;
4116 SKIP_WHITE_SPACE (fbeg);
4117 /* Discard trailing whitespace so we can easily see
4118 if we have parsed all the significant chars we were given. */
4119 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
4121 switch (*fbeg++) {
4122 case '\"':
4124 FILE_BUF *fp;
4125 /* Copy the operand text, concatenating the strings. */
4127 U_CHAR *fin = fbeg;
4128 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
4129 fend = fbeg;
4130 while (fin != limit) {
4131 while (fin != limit && *fin != '\"')
4132 *fend++ = *fin++;
4133 fin++;
4134 if (fin == limit)
4135 break;
4136 /* If not at the end, there had better be another string. */
4137 /* Skip just horiz space, and don't go past limit. */
4138 while (fin != limit && is_hor_space[*fin]) fin++;
4139 if (fin != limit && *fin == '\"')
4140 fin++;
4141 else
4142 goto fail;
4145 *fend = 0;
4147 /* We have "filename". Figure out directory this source
4148 file is coming from and put it on the front of the list. */
4150 /* If -I- was specified, don't search current dir, only spec'd ones. */
4151 if (ignore_srcdir) break;
4153 for (fp = &instack[indepth]; fp >= instack; fp--)
4155 int n;
4156 char *ep,*nam;
4158 if ((nam = fp->nominal_fname) != NULL) {
4159 /* Found a named file. Figure out dir of the file,
4160 and put it in front of the search list. */
4161 dsp[0].next = search_start;
4162 search_start = dsp;
4163 #ifndef VMS
4164 ep = rindex (nam, '/');
4165 #ifdef DIR_SEPARATOR
4166 if (ep == NULL) ep = rindex (nam, DIR_SEPARATOR);
4167 else {
4168 char *tmp = rindex (nam, DIR_SEPARATOR);
4169 if (tmp != NULL && tmp > ep) ep = tmp;
4171 #endif
4172 #else /* VMS */
4173 ep = rindex (nam, ']');
4174 if (ep == NULL) ep = rindex (nam, '>');
4175 if (ep == NULL) ep = rindex (nam, ':');
4176 if (ep != NULL) ep++;
4177 #endif /* VMS */
4178 if (ep != NULL) {
4179 n = ep - nam;
4180 dsp[0].fname = (char *) alloca (n + 1);
4181 strncpy (dsp[0].fname, nam, n);
4182 dsp[0].fname[n] = '\0';
4183 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4184 max_include_len = n + INCLUDE_LEN_FUDGE;
4185 } else {
4186 dsp[0].fname = 0; /* Current directory */
4188 dsp[0].got_name_map = 0;
4189 break;
4192 break;
4195 case '<':
4196 fend = fbeg;
4197 while (fend != limit && *fend != '>') fend++;
4198 if (*fend == '>' && fend + 1 == limit) {
4199 angle_brackets = 1;
4200 /* If -I-, start with the first -I dir after the -I-. */
4201 if (first_bracket_include)
4202 search_start = first_bracket_include;
4203 break;
4205 goto fail;
4207 default:
4208 #ifdef VMS
4210 * Support '#include xyz' like VAX-C to allow for easy use of all the
4211 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4212 * code from case '<' is repeated here) and generates a warning.
4213 * (Note: macro expansion of `xyz' takes precedence.)
4215 if (retried && isalpha(*(--fbeg))) {
4216 fend = fbeg;
4217 while (fend != limit && (!isspace(*fend))) fend++;
4218 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4219 if (fend == limit) {
4220 angle_brackets = 1;
4221 /* If -I-, start with the first -I dir after the -I-. */
4222 if (first_bracket_include)
4223 search_start = first_bracket_include;
4224 break;
4227 #endif
4229 fail:
4230 if (retried) {
4231 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4232 return 0;
4233 } else {
4234 /* Expand buffer and then remove any newline markers.
4235 We can't just tell expand_to_temp_buffer to omit the markers,
4236 since it would put extra spaces in include file names. */
4237 FILE_BUF trybuf;
4238 U_CHAR *src;
4239 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4240 src = trybuf.buf;
4241 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4242 limit = buf;
4243 while (src != trybuf.bufp) {
4244 switch ((*limit++ = *src++)) {
4245 case '\n':
4246 limit--;
4247 src++;
4248 break;
4250 case '\'':
4251 case '\"':
4253 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4254 NULL_PTR, NULL_PTR, NULL_PTR);
4255 while (src != src1)
4256 *limit++ = *src++;
4258 break;
4261 *limit = 0;
4262 free (trybuf.buf);
4263 retried++;
4264 goto get_filename;
4268 /* For #include_next, skip in the search path
4269 past the dir in which the containing file was found. */
4270 if (skip_dirs) {
4271 FILE_BUF *fp;
4272 for (fp = &instack[indepth]; fp >= instack; fp--)
4273 if (fp->fname != NULL) {
4274 /* fp->dir is null if the containing file was specified
4275 with an absolute file name. In that case, don't skip anything. */
4276 if (fp->dir)
4277 search_start = fp->dir->next;
4278 break;
4282 flen = fend - fbeg;
4284 if (flen == 0)
4286 error ("empty file name in `#%s'", keyword->name);
4287 return 0;
4290 /* Allocate this permanently, because it gets stored in the definitions
4291 of macros. */
4292 fname = (char *) xmalloc (max_include_len + flen + 4);
4293 /* + 2 above for slash and terminating null. */
4294 /* + 2 added for '.h' on VMS (to support '#include filename') */
4296 /* If specified file name is absolute, just open it. */
4298 if (*fbeg == '/'
4299 #ifdef DIR_SEPARATOR
4300 || *fbeg == DIR_SEPARATOR
4301 #endif
4303 strncpy (fname, fbeg, flen);
4304 fname[flen] = 0;
4305 if (redundant_include_p (fname))
4306 return 0;
4307 if (importing)
4308 f = lookup_import (fname, NULL_PTR);
4309 else
4310 f = open_include_file (fname, NULL_PTR);
4311 if (f == -2)
4312 return 0; /* Already included this file */
4313 } else {
4314 /* Search directory path, trying to open the file.
4315 Copy each filename tried into FNAME. */
4317 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4318 if (searchptr->fname) {
4319 /* The empty string in a search path is ignored.
4320 This makes it possible to turn off entirely
4321 a standard piece of the list. */
4322 if (searchptr->fname[0] == 0)
4323 continue;
4324 strcpy (fname, searchptr->fname);
4325 strcat (fname, "/");
4326 fname[strlen (fname) + flen] = 0;
4327 } else {
4328 fname[0] = 0;
4330 strncat (fname, fbeg, flen);
4331 #ifdef VMS
4332 /* Change this 1/2 Unix 1/2 VMS file specification into a
4333 full VMS file specification */
4334 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4335 /* Fix up the filename */
4336 hack_vms_include_specification (fname);
4337 } else {
4338 /* This is a normal VMS filespec, so use it unchanged. */
4339 strncpy (fname, fbeg, flen);
4340 fname[flen] = 0;
4341 /* if it's '#include filename', add the missing .h */
4342 if (index(fname,'.')==NULL) {
4343 strcat (fname, ".h");
4346 #endif /* VMS */
4347 if (importing)
4348 f = lookup_import (fname, searchptr);
4349 else
4350 f = open_include_file (fname, searchptr);
4351 if (f == -2)
4352 return 0; /* Already included this file */
4353 #ifdef EACCES
4354 else if (f == -1 && errno == EACCES)
4355 warning ("Header file %s exists, but is not readable", fname);
4356 #endif
4357 if (redundant_include_p (fname)) {
4358 close (f);
4359 return 0;
4361 if (f >= 0)
4362 break;
4366 if (f < 0) {
4367 /* A file that was not found. */
4369 strncpy (fname, fbeg, flen);
4370 fname[flen] = 0;
4371 /* If generating dependencies and -MG was specified, we assume missing
4372 files are leaf files, living in the same directory as the source file
4373 or other similar place; these missing files may be generated from
4374 other files and may not exist yet (eg: y.tab.h). */
4375 if (print_deps_missing_files
4376 && print_deps > (angle_brackets || (system_include_depth > 0)))
4378 /* If it was requested as a system header file,
4379 then assume it belongs in the first place to look for such. */
4380 if (angle_brackets)
4382 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
4384 if (searchptr->fname)
4386 char *p;
4388 if (searchptr->fname[0] == 0)
4389 continue;
4390 p = xmalloc (strlen (searchptr->fname)
4391 + strlen (fname) + 2);
4392 strcpy (p, searchptr->fname);
4393 strcat (p, "/");
4394 strcat (p, fname);
4395 deps_output (p, ' ');
4396 break;
4400 else
4402 /* Otherwise, omit the directory, as if the file existed
4403 in the directory with the source. */
4404 deps_output (fname, ' ');
4407 /* If -M was specified, and this header file won't be added to the
4408 dependency list, then don't count this as an error, because we can
4409 still produce correct output. Otherwise, we can't produce correct
4410 output, because there may be dependencies we need inside the missing
4411 file, and we don't know what directory this missing file exists in. */
4412 else if (print_deps
4413 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4414 warning ("No include path in which to find %s", fname);
4415 else if (search_start)
4416 error_from_errno (fname);
4417 else
4418 error ("No include path in which to find %s", fname);
4419 } else {
4420 struct stat stat_f;
4422 /* Check to see if this include file is a once-only include file.
4423 If so, give up. */
4425 struct file_name_list* ptr;
4427 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4428 if (!strcmp (ptr->fname, fname)) {
4429 close (f);
4430 return 0; /* This file was once'd. */
4434 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4435 if (!strcmp (ptr->fname, fname))
4436 break; /* This file was included before. */
4439 if (ptr == 0) {
4440 /* This is the first time for this file. */
4441 /* Add it to list of files included. */
4443 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4444 ptr->control_macro = 0;
4445 ptr->c_system_include_path = 0;
4446 ptr->next = all_include_files;
4447 all_include_files = ptr;
4448 ptr->fname = savestring (fname);
4449 ptr->got_name_map = 0;
4451 /* For -M, add this file to the dependencies. */
4452 if (print_deps > (angle_brackets || (system_include_depth > 0)))
4453 deps_output (fname, ' ');
4456 /* Handle -H option. */
4457 if (print_include_names) {
4458 output_dots (stderr, indepth);
4459 fprintf (stderr, "%s\n", fname);
4462 if (angle_brackets)
4463 system_include_depth++;
4465 /* Actually process the file. */
4466 add_import (f, fname); /* Record file on "seen" list for #import. */
4468 pcftry = (char *) alloca (strlen (fname) + 30);
4469 pcfbuf = 0;
4470 pcfnum = 0;
4472 fstat (f, &stat_f);
4474 if (!no_precomp)
4475 do {
4476 sprintf (pcftry, "%s%d", fname, pcfnum++);
4478 pcf = open (pcftry, O_RDONLY, 0666);
4479 if (pcf != -1)
4481 struct stat s;
4483 fstat (pcf, &s);
4484 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
4485 sizeof (s.st_ino))
4486 || stat_f.st_dev != s.st_dev)
4488 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4489 /* Don't need it any more. */
4490 close (pcf);
4492 else
4494 /* Don't need it at all. */
4495 close (pcf);
4496 break;
4499 } while (pcf != -1 && !pcfbuf);
4501 /* Actually process the file */
4502 if (pcfbuf) {
4503 pcfname = xmalloc (strlen (pcftry) + 1);
4504 strcpy (pcfname, pcftry);
4505 pcfinclude (pcfbuf, pcfbuflimit, fname, op);
4507 else
4508 finclude (f, fname, op, is_system_include (fname), searchptr);
4510 if (angle_brackets)
4511 system_include_depth--;
4513 return 0;
4516 /* Return nonzero if there is no need to include file NAME
4517 because it has already been included and it contains a conditional
4518 to make a repeated include do nothing. */
4520 static int
4521 redundant_include_p (name)
4522 char *name;
4524 struct file_name_list *l = all_include_files;
4525 for (; l; l = l->next)
4526 if (! strcmp (name, l->fname)
4527 && l->control_macro
4528 && lookup (l->control_macro, -1, -1))
4529 return 1;
4530 return 0;
4533 /* Return nonzero if the given FILENAME is an absolute pathname which
4534 designates a file within one of the known "system" include file
4535 directories. We assume here that if the given FILENAME looks like
4536 it is the name of a file which resides either directly in a "system"
4537 include file directory, or within any subdirectory thereof, then the
4538 given file must be a "system" include file. This function tells us
4539 if we should suppress pedantic errors/warnings for the given FILENAME.
4541 The value is 2 if the file is a C-language system header file
4542 for which C++ should (on most systems) assume `extern "C"'. */
4544 static int
4545 is_system_include (filename)
4546 register char *filename;
4548 struct file_name_list *searchptr;
4550 for (searchptr = first_system_include; searchptr;
4551 searchptr = searchptr->next)
4552 if (searchptr->fname) {
4553 register char *sys_dir = searchptr->fname;
4554 register unsigned length = strlen (sys_dir);
4556 if (! strncmp (sys_dir, filename, length)
4557 && (filename[length] == '/'
4558 #ifdef DIR_SEPARATOR
4559 || filename[length] == DIR_SEPARATOR
4560 #endif
4561 )) {
4562 if (searchptr->c_system_include_path)
4563 return 2;
4564 else
4565 return 1;
4568 return 0;
4571 /* The file_name_map structure holds a mapping of file names for a
4572 particular directory. This mapping is read from the file named
4573 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4574 map filenames on a file system with severe filename restrictions,
4575 such as DOS. The format of the file name map file is just a series
4576 of lines with two tokens on each line. The first token is the name
4577 to map, and the second token is the actual name to use. */
4579 struct file_name_map
4581 struct file_name_map *map_next;
4582 char *map_from;
4583 char *map_to;
4586 #define FILE_NAME_MAP_FILE "header.gcc"
4588 /* Read a space delimited string of unlimited length from a stdio
4589 file. */
4591 static char *
4592 read_filename_string (ch, f)
4593 int ch;
4594 FILE *f;
4596 char *alloc, *set;
4597 int len;
4599 len = 20;
4600 set = alloc = xmalloc (len + 1);
4601 if (! is_space[ch])
4603 *set++ = ch;
4604 while ((ch = getc (f)) != EOF && ! is_space[ch])
4606 if (set - alloc == len)
4608 len *= 2;
4609 alloc = xrealloc (alloc, len + 1);
4610 set = alloc + len / 2;
4612 *set++ = ch;
4615 *set = '\0';
4616 ungetc (ch, f);
4617 return alloc;
4620 /* Read the file name map file for DIRNAME. */
4622 static struct file_name_map *
4623 read_name_map (dirname)
4624 char *dirname;
4626 /* This structure holds a linked list of file name maps, one per
4627 directory. */
4628 struct file_name_map_list
4630 struct file_name_map_list *map_list_next;
4631 char *map_list_name;
4632 struct file_name_map *map_list_map;
4634 static struct file_name_map_list *map_list;
4635 register struct file_name_map_list *map_list_ptr;
4636 char *name;
4637 FILE *f;
4639 for (map_list_ptr = map_list; map_list_ptr;
4640 map_list_ptr = map_list_ptr->map_list_next)
4641 if (! strcmp (map_list_ptr->map_list_name, dirname))
4642 return map_list_ptr->map_list_map;
4644 map_list_ptr = ((struct file_name_map_list *)
4645 xmalloc (sizeof (struct file_name_map_list)));
4646 map_list_ptr->map_list_name = savestring (dirname);
4647 map_list_ptr->map_list_map = NULL;
4649 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
4650 strcpy (name, dirname);
4651 if (*dirname)
4652 strcat (name, "/");
4653 strcat (name, FILE_NAME_MAP_FILE);
4654 f = fopen (name, "r");
4655 if (!f)
4656 map_list_ptr->map_list_map = NULL;
4657 else
4659 int ch;
4660 int dirlen = strlen (dirname);
4662 while ((ch = getc (f)) != EOF)
4664 char *from, *to;
4665 struct file_name_map *ptr;
4667 if (is_space[ch])
4668 continue;
4669 from = read_filename_string (ch, f);
4670 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4672 to = read_filename_string (ch, f);
4674 ptr = ((struct file_name_map *)
4675 xmalloc (sizeof (struct file_name_map)));
4676 ptr->map_from = from;
4678 /* Make the real filename absolute. */
4679 if (*to == '/')
4680 ptr->map_to = to;
4681 else
4683 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
4684 strcpy (ptr->map_to, dirname);
4685 ptr->map_to[dirlen] = '/';
4686 strcpy (ptr->map_to + dirlen + 1, to);
4687 free (to);
4690 ptr->map_next = map_list_ptr->map_list_map;
4691 map_list_ptr->map_list_map = ptr;
4693 while ((ch = getc (f)) != '\n')
4694 if (ch == EOF)
4695 break;
4697 fclose (f);
4700 map_list_ptr->map_list_next = map_list;
4701 map_list = map_list_ptr;
4703 return map_list_ptr->map_list_map;
4706 /* Try to open include file FILENAME. SEARCHPTR is the directory
4707 being tried from the include file search path. This function maps
4708 filenames on file systems based on information read by
4709 read_name_map. */
4711 static int
4712 open_include_file (filename, searchptr)
4713 char *filename;
4714 struct file_name_list *searchptr;
4716 register struct file_name_map *map;
4717 register char *from;
4718 char *p, *dir;
4720 if (searchptr && ! searchptr->got_name_map)
4722 searchptr->name_map = read_name_map (searchptr->fname
4723 ? searchptr->fname : ".");
4724 searchptr->got_name_map = 1;
4727 /* First check the mapping for the directory we are using. */
4728 if (searchptr && searchptr->name_map)
4730 from = filename;
4731 if (searchptr->fname)
4732 from += strlen (searchptr->fname) + 1;
4733 for (map = searchptr->name_map; map; map = map->map_next)
4735 if (! strcmp (map->map_from, from))
4737 /* Found a match. */
4738 return open (map->map_to, O_RDONLY, 0666);
4743 /* Try to find a mapping file for the particular directory we are
4744 looking in. Thus #include <sys/types.h> will look up sys/types.h
4745 in /usr/include/header.gcc and look up types.h in
4746 /usr/include/sys/header.gcc. */
4747 p = rindex (filename, '/');
4748 #ifdef DIR_SEPARATOR
4749 if (! p) p = rindex (filename, DIR_SEPARATOR);
4750 else {
4751 char *tmp = rindex (filename, DIR_SEPARATOR);
4752 if (tmp != NULL && tmp > p) p = tmp;
4754 #endif
4755 if (! p)
4756 p = filename;
4757 if (searchptr
4758 && searchptr->fname
4759 && strlen (searchptr->fname) == p - filename
4760 && ! strncmp (searchptr->fname, filename, p - filename))
4762 /* FILENAME is in SEARCHPTR, which we've already checked. */
4763 return open (filename, O_RDONLY, 0666);
4766 if (p == filename)
4768 dir = ".";
4769 from = filename;
4771 else
4773 dir = (char *) alloca (p - filename + 1);
4774 bcopy (filename, dir, p - filename);
4775 dir[p - filename] = '\0';
4776 from = p + 1;
4778 for (map = read_name_map (dir); map; map = map->map_next)
4779 if (! strcmp (map->map_from, from))
4780 return open (map->map_to, O_RDONLY, 0666);
4782 return open (filename, O_RDONLY, 0666);
4785 /* Process the contents of include file FNAME, already open on descriptor F,
4786 with output to OP.
4787 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4788 "system" include directories (as decided by the `is_system_include'
4789 function above).
4790 DIRPTR is the link in the dir path through which this file was found,
4791 or 0 if the file name was absolute. */
4793 static void
4794 finclude (f, fname, op, system_header_p, dirptr)
4795 int f;
4796 char *fname;
4797 FILE_BUF *op;
4798 int system_header_p;
4799 struct file_name_list *dirptr;
4801 int st_mode;
4802 long st_size;
4803 long i;
4804 FILE_BUF *fp; /* For input stack frame */
4805 int missing_newline = 0;
4807 CHECK_DEPTH (return;);
4809 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
4811 perror_with_name (fname);
4812 close (f);
4813 return;
4816 fp = &instack[indepth + 1];
4817 bzero ((char *) fp, sizeof (FILE_BUF));
4818 fp->nominal_fname = fp->fname = fname;
4819 fp->length = 0;
4820 fp->lineno = 1;
4821 fp->if_stack = if_stack;
4822 fp->system_header_p = system_header_p;
4823 fp->dir = dirptr;
4825 if (S_ISREG (st_mode)) {
4826 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
4827 fp->bufp = fp->buf;
4829 /* Read the file contents, knowing that st_size is an upper bound
4830 on the number of bytes we can read. */
4831 fp->length = safe_read (f, fp->buf, st_size);
4832 if (fp->length < 0) goto nope;
4834 else if (S_ISDIR (st_mode)) {
4835 error ("directory `%s' specified in #include", fname);
4836 close (f);
4837 return;
4838 } else {
4839 /* Cannot count its file size before reading.
4840 First read the entire file into heap and
4841 copy them into buffer on stack. */
4843 int bsize = 2000;
4845 st_size = 0;
4846 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
4848 for (;;) {
4849 i = safe_read (f, fp->buf + st_size, bsize - st_size);
4850 if (i < 0)
4851 goto nope; /* error! */
4852 st_size += i;
4853 if (st_size != bsize)
4854 break; /* End of file */
4855 bsize *= 2;
4856 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
4858 fp->bufp = fp->buf;
4859 fp->length = st_size;
4862 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
4863 /* Backslash-newline at end is not good enough. */
4864 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
4865 fp->buf[fp->length++] = '\n';
4866 missing_newline = 1;
4868 fp->buf[fp->length] = '\0';
4870 /* Close descriptor now, so nesting does not use lots of descriptors. */
4871 close (f);
4873 /* Must do this before calling trigraph_pcp, so that the correct file name
4874 will be printed in warning messages. */
4876 indepth++;
4877 input_file_stack_tick++;
4879 if (!no_trigraphs)
4880 trigraph_pcp (fp);
4882 output_line_command (fp, op, 0, enter_file);
4883 rescan (op, 0);
4885 if (missing_newline)
4886 fp->lineno--;
4888 if (pedantic && missing_newline)
4889 pedwarn ("file does not end in newline");
4891 indepth--;
4892 input_file_stack_tick++;
4893 output_line_command (&instack[indepth], op, 0, leave_file);
4894 free (fp->buf);
4895 return;
4897 nope:
4899 perror_with_name (fname);
4900 close (f);
4901 free (fp->buf);
4904 /* Record that inclusion of the file named FILE
4905 should be controlled by the macro named MACRO_NAME.
4906 This means that trying to include the file again
4907 will do something if that macro is defined. */
4909 static void
4910 record_control_macro (file, macro_name)
4911 char *file;
4912 U_CHAR *macro_name;
4914 struct file_name_list *new;
4916 for (new = all_include_files; new; new = new->next) {
4917 if (!strcmp (new->fname, file)) {
4918 new->control_macro = macro_name;
4919 return;
4923 /* If the file is not in all_include_files, something's wrong. */
4924 abort ();
4927 /* Maintain and search list of included files, for #import. */
4929 #define IMPORT_HASH_SIZE 31
4931 struct import_file {
4932 char *name;
4933 ino_t inode;
4934 dev_t dev;
4935 struct import_file *next;
4938 /* Hash table of files already included with #include or #import. */
4940 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
4942 /* Hash a file name for import_hash_table. */
4944 static int
4945 import_hash (f)
4946 char *f;
4948 int val = 0;
4950 while (*f) val += *f++;
4951 return (val%IMPORT_HASH_SIZE);
4954 /* Search for file FILENAME in import_hash_table.
4955 Return -2 if found, either a matching name or a matching inode.
4956 Otherwise, open the file and return a file descriptor if successful
4957 or -1 if unsuccessful. */
4959 static int
4960 lookup_import (filename, searchptr)
4961 char *filename;
4962 struct file_name_list *searchptr;
4964 struct import_file *i;
4965 int h;
4966 int hashval;
4967 struct stat sb;
4968 int fd;
4970 hashval = import_hash (filename);
4972 /* Attempt to find file in list of already included files */
4973 i = import_hash_table[hashval];
4975 while (i) {
4976 if (!strcmp (filename, i->name))
4977 return -2; /* return found */
4978 i = i->next;
4980 /* Open it and try a match on inode/dev */
4981 fd = open_include_file (filename, searchptr);
4982 if (fd < 0)
4983 return fd;
4984 fstat (fd, &sb);
4985 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
4986 i = import_hash_table[h];
4987 while (i) {
4988 /* Compare the inode and the device.
4989 Supposedly on some systems the inode is not a scalar. */
4990 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
4991 && i->dev == sb.st_dev) {
4992 close (fd);
4993 return -2; /* return found */
4995 i = i->next;
4998 return fd; /* Not found, return open file */
5001 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
5003 static void
5004 add_import (fd, fname)
5005 int fd;
5006 char *fname;
5008 struct import_file *i;
5009 int hashval;
5010 struct stat sb;
5012 hashval = import_hash (fname);
5013 fstat (fd, &sb);
5014 i = (struct import_file *)xmalloc (sizeof (struct import_file));
5015 i->name = (char *)xmalloc (strlen (fname)+1);
5016 strcpy (i->name, fname);
5017 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5018 i->dev = sb.st_dev;
5019 i->next = import_hash_table[hashval];
5020 import_hash_table[hashval] = i;
5023 /* Load the specified precompiled header into core, and verify its
5024 preconditions. PCF indicates the file descriptor to read, which must
5025 be a regular file. FNAME indicates the file name of the original
5026 header. *LIMIT will be set to an address one past the end of the file.
5027 If the preconditions of the file are not satisfied, the buffer is
5028 freed and we return 0. If the preconditions are satisfied, return
5029 the address of the buffer following the preconditions. The buffer, in
5030 this case, should never be freed because various pieces of it will
5031 be referred to until all precompiled strings are output at the end of
5032 the run.
5034 static char *
5035 check_precompiled (pcf, fname, limit)
5036 int pcf;
5037 char *fname;
5038 char **limit;
5040 int st_mode;
5041 long st_size;
5042 int length = 0;
5043 char *buf;
5044 char *cp;
5046 if (pcp_outfile)
5047 return 0;
5049 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
5050 return 0;
5052 if (S_ISREG (st_mode))
5054 buf = xmalloc (st_size + 2);
5055 length = safe_read (pcf, buf, st_size);
5056 if (length < 0)
5057 goto nope;
5059 else
5060 abort ();
5062 if (length > 0 && buf[length-1] != '\n')
5063 buf[length++] = '\n';
5064 buf[length] = '\0';
5066 *limit = buf + length;
5068 /* File is in core. Check the preconditions. */
5069 if (!check_preconditions (buf))
5070 goto nope;
5071 for (cp = buf; *cp; cp++)
5073 #ifdef DEBUG_PCP
5074 fprintf (stderr, "Using preinclude %s\n", fname);
5075 #endif
5076 return cp + 1;
5078 nope:
5079 #ifdef DEBUG_PCP
5080 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5081 #endif
5082 free (buf);
5083 return 0;
5086 /* PREC (null terminated) points to the preconditions of a
5087 precompiled header. These are a series of #define and #undef
5088 lines which must match the current contents of the hash
5089 table. */
5090 static int
5091 check_preconditions (prec)
5092 char *prec;
5094 MACRODEF mdef;
5095 char *lineend;
5097 while (*prec) {
5098 lineend = (char *) index (prec, '\n');
5100 if (*prec++ != '#') {
5101 error ("Bad format encountered while reading precompiled file");
5102 return 0;
5104 if (!strncmp (prec, "define", 6)) {
5105 HASHNODE *hp;
5107 prec += 6;
5108 mdef = create_definition (prec, lineend, NULL_PTR);
5110 if (mdef.defn == 0)
5111 abort ();
5113 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5114 || (hp->type != T_MACRO && hp->type != T_CONST)
5115 || (hp->type == T_MACRO
5116 && !compare_defs (mdef.defn, hp->value.defn)
5117 && (mdef.defn->length != 2
5118 || mdef.defn->expansion[0] != '\n'
5119 || mdef.defn->expansion[1] != ' ')))
5120 return 0;
5121 } else if (!strncmp (prec, "undef", 5)) {
5122 char *name;
5123 int len;
5125 prec += 5;
5126 while (is_hor_space[(U_CHAR) *prec])
5127 prec++;
5128 name = prec;
5129 while (is_idchar[(U_CHAR) *prec])
5130 prec++;
5131 len = prec - name;
5133 if (lookup (name, len, -1))
5134 return 0;
5135 } else {
5136 error ("Bad format encountered while reading precompiled file");
5137 return 0;
5139 prec = lineend + 1;
5141 /* They all passed successfully */
5142 return 1;
5145 /* Process the main body of a precompiled file. BUF points to the
5146 string section of the file, following the preconditions. LIMIT is one
5147 character past the end. NAME is the name of the file being read
5148 in. OP is the main output buffer */
5149 static void
5150 pcfinclude (buf, limit, name, op)
5151 U_CHAR *buf, *limit, *name;
5152 FILE_BUF *op;
5154 FILE_BUF tmpbuf;
5155 int nstrings;
5156 U_CHAR *cp = buf;
5158 /* First in the file comes 4 bytes indicating the number of strings, */
5159 /* in network byte order. (MSB first). */
5160 nstrings = *cp++;
5161 nstrings = (nstrings << 8) | *cp++;
5162 nstrings = (nstrings << 8) | *cp++;
5163 nstrings = (nstrings << 8) | *cp++;
5165 /* Looping over each string... */
5166 while (nstrings--) {
5167 U_CHAR *string_start;
5168 U_CHAR *endofthiskey;
5169 STRINGDEF *str;
5170 int nkeys;
5172 /* Each string starts with a STRINGDEF structure (str), followed */
5173 /* by the text of the string (string_start) */
5175 /* First skip to a longword boundary */
5176 /* ??? Why a 4-byte boundary? On all machines? */
5177 /* NOTE: This works correctly even if HOST_WIDE_INT
5178 is narrower than a pointer.
5179 Do not try risky measures here to get another type to use!
5180 Do not include stddef.h--it will fail! */
5181 if ((HOST_WIDE_INT) cp & 3)
5182 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5184 /* Now get the string. */
5185 str = (STRINGDEF *) cp;
5186 string_start = cp += sizeof (STRINGDEF);
5188 for (; *cp; cp++) /* skip the string */
5191 /* We need to macro expand the string here to ensure that the
5192 proper definition environment is in place. If it were only
5193 expanded when we find out it is needed, macros necessary for
5194 its proper expansion might have had their definitions changed. */
5195 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5196 /* Lineno is already set in the precompiled file */
5197 str->contents = tmpbuf.buf;
5198 str->len = tmpbuf.length;
5199 str->writeflag = 0;
5200 str->filename = name;
5201 str->output_mark = outbuf.bufp - outbuf.buf;
5203 str->chain = 0;
5204 *stringlist_tailp = str;
5205 stringlist_tailp = &str->chain;
5207 /* Next comes a fourbyte number indicating the number of keys */
5208 /* for this string. */
5209 nkeys = *cp++;
5210 nkeys = (nkeys << 8) | *cp++;
5211 nkeys = (nkeys << 8) | *cp++;
5212 nkeys = (nkeys << 8) | *cp++;
5214 /* If this number is -1, then the string is mandatory. */
5215 if (nkeys == -1)
5216 str->writeflag = 1;
5217 else
5218 /* Otherwise, for each key, */
5219 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5220 KEYDEF *kp = (KEYDEF *) cp;
5221 HASHNODE *hp;
5223 /* It starts with a KEYDEF structure */
5224 cp += sizeof (KEYDEF);
5226 /* Find the end of the key. At the end of this for loop we
5227 advance CP to the start of the next key using this variable. */
5228 endofthiskey = cp + strlen (cp);
5229 kp->str = str;
5231 /* Expand the key, and enter it into the hash table. */
5232 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5233 tmpbuf.bufp = tmpbuf.buf;
5235 while (is_hor_space[*tmpbuf.bufp])
5236 tmpbuf.bufp++;
5237 if (!is_idstart[*tmpbuf.bufp]
5238 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5239 str->writeflag = 1;
5240 continue;
5243 hp = lookup (tmpbuf.bufp, -1, -1);
5244 if (hp == NULL) {
5245 kp->chain = 0;
5246 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5248 else if (hp->type == T_PCSTRING) {
5249 kp->chain = hp->value.keydef;
5250 hp->value.keydef = kp;
5252 else
5253 str->writeflag = 1;
5256 /* This output_line_command serves to switch us back to the current
5257 input file in case some of these strings get output (which will
5258 result in line commands for the header file being output). */
5259 output_line_command (&instack[indepth], op, 0, enter_file);
5262 /* Called from rescan when it hits a key for strings. Mark them all */
5263 /* used and clean up. */
5264 static void
5265 pcstring_used (hp)
5266 HASHNODE *hp;
5268 KEYDEF *kp;
5270 for (kp = hp->value.keydef; kp; kp = kp->chain)
5271 kp->str->writeflag = 1;
5272 delete_macro (hp);
5275 /* Write the output, interspersing precompiled strings in their */
5276 /* appropriate places. */
5277 static void
5278 write_output ()
5280 STRINGDEF *next_string;
5281 U_CHAR *cur_buf_loc;
5282 int line_command_len = 80;
5283 char *line_command = xmalloc (line_command_len);
5284 int len;
5286 /* In each run through the loop, either cur_buf_loc == */
5287 /* next_string_loc, in which case we print a series of strings, or */
5288 /* it is less than next_string_loc, in which case we write some of */
5289 /* the buffer. */
5290 cur_buf_loc = outbuf.buf;
5291 next_string = stringlist;
5293 while (cur_buf_loc < outbuf.bufp || next_string) {
5294 if (next_string
5295 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5296 if (next_string->writeflag) {
5297 len = 4 * strlen (next_string->filename) + 32;
5298 while (len > line_command_len)
5299 line_command = xrealloc (line_command,
5300 line_command_len *= 2);
5301 sprintf (line_command, "\n# %d ", next_string->lineno);
5302 strcpy (quote_string (line_command + strlen (line_command),
5303 next_string->filename),
5304 "\n");
5305 safe_write (fileno (stdout), line_command, strlen (line_command));
5306 safe_write (fileno (stdout), next_string->contents, next_string->len);
5308 next_string = next_string->chain;
5310 else {
5311 len = (next_string
5312 ? (next_string->output_mark
5313 - (cur_buf_loc - outbuf.buf))
5314 : outbuf.bufp - cur_buf_loc);
5316 safe_write (fileno (stdout), cur_buf_loc, len);
5317 cur_buf_loc += len;
5320 free (line_command);
5323 /* Pass a directive through to the output file.
5324 BUF points to the contents of the directive, as a contiguous string.
5325 LIMIT points to the first character past the end of the directive.
5326 KEYWORD is the keyword-table entry for the directive. */
5328 static void
5329 pass_thru_directive (buf, limit, op, keyword)
5330 U_CHAR *buf, *limit;
5331 FILE_BUF *op;
5332 struct directive *keyword;
5334 register unsigned keyword_length = keyword->length;
5336 check_expand (op, 1 + keyword_length + (limit - buf));
5337 *op->bufp++ = '#';
5338 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5339 op->bufp += keyword_length;
5340 if (limit != buf && buf[0] != ' ')
5341 *op->bufp++ = ' ';
5342 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5343 op->bufp += (limit - buf);
5344 #if 0
5345 *op->bufp++ = '\n';
5346 /* Count the line we have just made in the output,
5347 to get in sync properly. */
5348 op->lineno++;
5349 #endif
5352 /* The arglist structure is built by do_define to tell
5353 collect_definition where the argument names begin. That
5354 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5355 would contain pointers to the strings x, y, and z.
5356 Collect_definition would then build a DEFINITION node,
5357 with reflist nodes pointing to the places x, y, and z had
5358 appeared. So the arglist is just convenience data passed
5359 between these two routines. It is not kept around after
5360 the current #define has been processed and entered into the
5361 hash table. */
5363 struct arglist {
5364 struct arglist *next;
5365 U_CHAR *name;
5366 int length;
5367 int argno;
5368 char rest_args;
5371 /* Create a DEFINITION node from a #define directive. Arguments are
5372 as for do_define. */
5373 static MACRODEF
5374 create_definition (buf, limit, op)
5375 U_CHAR *buf, *limit;
5376 FILE_BUF *op;
5378 U_CHAR *bp; /* temp ptr into input buffer */
5379 U_CHAR *symname; /* remember where symbol name starts */
5380 int sym_length; /* and how long it is */
5381 int line = instack[indepth].lineno;
5382 char *file = instack[indepth].nominal_fname;
5383 int rest_args = 0;
5385 DEFINITION *defn;
5386 int arglengths = 0; /* Accumulate lengths of arg names
5387 plus number of args. */
5388 MACRODEF mdef;
5390 bp = buf;
5392 while (is_hor_space[*bp])
5393 bp++;
5395 symname = bp; /* remember where it starts */
5396 sym_length = check_macro_name (bp, "macro");
5397 bp += sym_length;
5399 /* Lossage will occur if identifiers or control keywords are broken
5400 across lines using backslash. This is not the right place to take
5401 care of that. */
5403 if (*bp == '(') {
5404 struct arglist *arg_ptrs = NULL;
5405 int argno = 0;
5407 bp++; /* skip '(' */
5408 SKIP_WHITE_SPACE (bp);
5410 /* Loop over macro argument names. */
5411 while (*bp != ')') {
5412 struct arglist *temp;
5414 temp = (struct arglist *) alloca (sizeof (struct arglist));
5415 temp->name = bp;
5416 temp->next = arg_ptrs;
5417 temp->argno = argno++;
5418 temp->rest_args = 0;
5419 arg_ptrs = temp;
5421 if (rest_args)
5422 pedwarn ("another parameter follows `%s'",
5423 rest_extension);
5425 if (!is_idstart[*bp])
5426 pedwarn ("invalid character in macro parameter name");
5428 /* Find the end of the arg name. */
5429 while (is_idchar[*bp]) {
5430 bp++;
5431 /* do we have a "special" rest-args extension here? */
5432 if (limit - bp > REST_EXTENSION_LENGTH &&
5433 strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5434 rest_args = 1;
5435 temp->rest_args = 1;
5436 break;
5439 temp->length = bp - temp->name;
5440 if (rest_args == 1)
5441 bp += REST_EXTENSION_LENGTH;
5442 arglengths += temp->length + 2;
5443 SKIP_WHITE_SPACE (bp);
5444 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5445 error ("badly punctuated parameter list in `#define'");
5446 goto nope;
5448 if (*bp == ',') {
5449 bp++;
5450 SKIP_WHITE_SPACE (bp);
5451 /* A comma at this point can only be followed by an identifier. */
5452 if (!is_idstart[*bp]) {
5453 error ("badly punctuated parameter list in `#define'");
5454 goto nope;
5457 if (bp >= limit) {
5458 error ("unterminated parameter list in `#define'");
5459 goto nope;
5462 struct arglist *otemp;
5464 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5465 if (temp->length == otemp->length &&
5466 strncmp (temp->name, otemp->name, temp->length) == 0) {
5467 U_CHAR *name;
5469 name = (U_CHAR *) alloca (temp->length + 1);
5470 (void) strncpy (name, temp->name, temp->length);
5471 name[temp->length] = '\0';
5472 error ("duplicate argument name `%s' in `#define'", name);
5473 goto nope;
5478 ++bp; /* skip paren */
5479 SKIP_WHITE_SPACE (bp);
5480 /* now everything from bp before limit is the definition. */
5481 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5482 defn->rest_args = rest_args;
5484 /* Now set defn->args.argnames to the result of concatenating
5485 the argument names in reverse order
5486 with comma-space between them. */
5487 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5489 struct arglist *temp;
5490 int i = 0;
5491 for (temp = arg_ptrs; temp; temp = temp->next) {
5492 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5493 i += temp->length;
5494 if (temp->next != 0) {
5495 defn->args.argnames[i++] = ',';
5496 defn->args.argnames[i++] = ' ';
5499 defn->args.argnames[i] = 0;
5501 } else {
5502 /* Simple expansion or empty definition. */
5504 if (bp < limit)
5506 if (is_hor_space[*bp]) {
5507 bp++;
5508 SKIP_WHITE_SPACE (bp);
5509 } else {
5510 switch (*bp) {
5511 case '!': case '"': case '#': case '%': case '&': case '\'':
5512 case ')': case '*': case '+': case ',': case '-': case '.':
5513 case '/': case ':': case ';': case '<': case '=': case '>':
5514 case '?': case '[': case '\\': case ']': case '^': case '{':
5515 case '|': case '}': case '~':
5516 warning ("missing white space after `#define %.*s'",
5517 sym_length, symname);
5518 break;
5520 default:
5521 pedwarn ("missing white space after `#define %.*s'",
5522 sym_length, symname);
5523 break;
5527 /* Now everything from bp before limit is the definition. */
5528 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5529 defn->args.argnames = (U_CHAR *) "";
5532 defn->line = line;
5533 defn->file = file;
5535 /* OP is null if this is a predefinition */
5536 defn->predefined = !op;
5537 mdef.defn = defn;
5538 mdef.symnam = symname;
5539 mdef.symlen = sym_length;
5541 return mdef;
5543 nope:
5544 mdef.defn = 0;
5545 return mdef;
5548 /* Process a #define command.
5549 BUF points to the contents of the #define command, as a contiguous string.
5550 LIMIT points to the first character past the end of the definition.
5551 KEYWORD is the keyword-table entry for #define. */
5553 static int
5554 do_define (buf, limit, op, keyword)
5555 U_CHAR *buf, *limit;
5556 FILE_BUF *op;
5557 struct directive *keyword;
5559 int hashcode;
5560 MACRODEF mdef;
5562 /* If this is a precompiler run (with -pcp) pass thru #define commands. */
5563 if (pcp_outfile && op)
5564 pass_thru_directive (buf, limit, op, keyword);
5566 mdef = create_definition (buf, limit, op);
5567 if (mdef.defn == 0)
5568 goto nope;
5570 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5573 HASHNODE *hp;
5574 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5575 int ok = 0;
5576 /* Redefining a precompiled key is ok. */
5577 if (hp->type == T_PCSTRING)
5578 ok = 1;
5579 /* Redefining a macro is ok if the definitions are the same. */
5580 else if (hp->type == T_MACRO)
5581 ok = ! compare_defs (mdef.defn, hp->value.defn);
5582 /* Redefining a constant is ok with -D. */
5583 else if (hp->type == T_CONST)
5584 ok = ! done_initializing;
5585 /* Print the warning if it's not ok. */
5586 if (!ok) {
5587 U_CHAR *msg; /* what pain... */
5589 /* If we are passing through #define and #undef directives, do
5590 that for this re-definition now. */
5591 if (debug_output && op)
5592 pass_thru_directive (buf, limit, op, keyword);
5594 msg = (U_CHAR *) alloca (mdef.symlen + 22);
5595 *msg = '`';
5596 bcopy ((char *) mdef.symnam, (char *) (msg + 1), mdef.symlen);
5597 strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
5598 pedwarn (msg);
5599 if (hp->type == T_MACRO)
5600 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5601 "this is the location of the previous definition");
5603 /* Replace the old definition. */
5604 hp->type = T_MACRO;
5605 hp->value.defn = mdef.defn;
5606 } else {
5607 /* If we are passing through #define and #undef directives, do
5608 that for this new definition now. */
5609 if (debug_output && op)
5610 pass_thru_directive (buf, limit, op, keyword);
5611 install (mdef.symnam, mdef.symlen, T_MACRO,
5612 (char *) mdef.defn, hashcode);
5616 return 0;
5618 nope:
5620 return 1;
5623 /* Check a purported macro name SYMNAME, and yield its length.
5624 USAGE is the kind of name this is intended for. */
5626 static int
5627 check_macro_name (symname, usage)
5628 U_CHAR *symname;
5629 char *usage;
5631 U_CHAR *p;
5632 int sym_length;
5634 for (p = symname; is_idchar[*p]; p++)
5636 sym_length = p - symname;
5637 if (sym_length == 0)
5638 error ("invalid %s name", usage);
5639 else if (!is_idstart[*symname]) {
5640 U_CHAR *msg; /* what pain... */
5641 msg = (U_CHAR *) alloca (sym_length + 1);
5642 bcopy ((char *) symname, (char *) msg, sym_length);
5643 msg[sym_length] = 0;
5644 error ("invalid %s name `%s'", usage, msg);
5645 } else {
5646 if (! strncmp (symname, "defined", 7) && sym_length == 7)
5647 error ("invalid %s name `defined'", usage);
5649 return sym_length;
5653 * return zero if two DEFINITIONs are isomorphic
5655 static int
5656 compare_defs (d1, d2)
5657 DEFINITION *d1, *d2;
5659 register struct reflist *a1, *a2;
5660 register U_CHAR *p1 = d1->expansion;
5661 register U_CHAR *p2 = d2->expansion;
5662 int first = 1;
5664 if (d1->nargs != d2->nargs)
5665 return 1;
5666 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5667 return 1;
5668 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5669 a1 = a1->next, a2 = a2->next) {
5670 if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
5671 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5672 || a1->argno != a2->argno
5673 || a1->stringify != a2->stringify
5674 || a1->raw_before != a2->raw_before
5675 || a1->raw_after != a2->raw_after)
5676 return 1;
5677 first = 0;
5678 p1 += a1->nchars;
5679 p2 += a2->nchars;
5681 if (a1 != a2)
5682 return 1;
5683 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5684 p2, d2->length - (p2 - d2->expansion), 1))
5685 return 1;
5686 return 0;
5689 /* Return 1 if two parts of two macro definitions are effectively different.
5690 One of the parts starts at BEG1 and has LEN1 chars;
5691 the other has LEN2 chars at BEG2.
5692 Any sequence of whitespace matches any other sequence of whitespace.
5693 FIRST means these parts are the first of a macro definition;
5694 so ignore leading whitespace entirely.
5695 LAST means these parts are the last of a macro definition;
5696 so ignore trailing whitespace entirely. */
5698 static int
5699 comp_def_part (first, beg1, len1, beg2, len2, last)
5700 int first;
5701 U_CHAR *beg1, *beg2;
5702 int len1, len2;
5703 int last;
5705 register U_CHAR *end1 = beg1 + len1;
5706 register U_CHAR *end2 = beg2 + len2;
5707 if (first) {
5708 while (beg1 != end1 && is_space[*beg1]) beg1++;
5709 while (beg2 != end2 && is_space[*beg2]) beg2++;
5711 if (last) {
5712 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5713 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5715 while (beg1 != end1 && beg2 != end2) {
5716 if (is_space[*beg1] && is_space[*beg2]) {
5717 while (beg1 != end1 && is_space[*beg1]) beg1++;
5718 while (beg2 != end2 && is_space[*beg2]) beg2++;
5719 } else if (*beg1 == *beg2) {
5720 beg1++; beg2++;
5721 } else break;
5723 return (beg1 != end1) || (beg2 != end2);
5726 /* Read a replacement list for a macro with parameters.
5727 Build the DEFINITION structure.
5728 Reads characters of text starting at BUF until END.
5729 ARGLIST specifies the formal parameters to look for
5730 in the text of the definition; NARGS is the number of args
5731 in that list, or -1 for a macro name that wants no argument list.
5732 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5733 and NAMELEN is its length in characters.
5735 Note that comments and backslash-newlines have already been deleted
5736 from the argument. */
5738 /* Leading and trailing Space, Tab, etc. are converted to markers
5739 Newline Space, Newline Tab, etc.
5740 Newline Space makes a space in the final output
5741 but is discarded if stringified. (Newline Tab is similar but
5742 makes a Tab instead.)
5744 If there is no trailing whitespace, a Newline Space is added at the end
5745 to prevent concatenation that would be contrary to the standard. */
5747 static DEFINITION *
5748 collect_expansion (buf, end, nargs, arglist)
5749 U_CHAR *buf, *end;
5750 int nargs;
5751 struct arglist *arglist;
5753 DEFINITION *defn;
5754 register U_CHAR *p, *limit, *lastp, *exp_p;
5755 struct reflist *endpat = NULL;
5756 /* Pointer to first nonspace after last ## seen. */
5757 U_CHAR *concat = 0;
5758 /* Pointer to first nonspace after last single-# seen. */
5759 U_CHAR *stringify = 0;
5760 /* How those tokens were spelled: 0, '#', or '%' (meaning %:). */
5761 char concat_spelling = 0;
5762 char stringify_spelling = 0;
5763 int maxsize;
5764 int expected_delimiter = '\0';
5766 /* Scan thru the replacement list, ignoring comments and quoted
5767 strings, picking up on the macro calls. It does a linear search
5768 thru the arg list on every potential symbol. Profiling might say
5769 that something smarter should happen. */
5771 if (end < buf)
5772 abort ();
5774 /* Find the beginning of the trailing whitespace. */
5775 /* Find end of leading whitespace. */
5776 limit = end;
5777 p = buf;
5778 while (p < limit && is_space[limit[-1]]) limit--;
5779 while (p < limit && is_space[*p]) p++;
5781 /* Allocate space for the text in the macro definition.
5782 Leading and trailing whitespace chars need 2 bytes each.
5783 Each other input char may or may not need 1 byte,
5784 so this is an upper bound.
5785 The extra 2 are for invented trailing newline-marker and final null. */
5786 maxsize = (sizeof (DEFINITION)
5787 + 2 * (end - limit) + 2 * (p - buf)
5788 + (limit - p) + 3);
5789 defn = (DEFINITION *) xcalloc (1, maxsize);
5791 defn->nargs = nargs;
5792 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5793 lastp = exp_p;
5795 p = buf;
5797 /* Convert leading whitespace to Newline-markers. */
5798 while (p < limit && is_space[*p]) {
5799 *exp_p++ = '\n';
5800 *exp_p++ = *p++;
5803 if (p[0] == '#'
5804 ? p[1] == '#'
5805 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5806 error ("`##' at start of macro definition");
5807 p += p[0] == '#' ? 2 : 4;
5810 /* Process the main body of the definition. */
5811 while (p < limit) {
5812 int skipped_arg = 0;
5813 register U_CHAR c = *p++;
5815 *exp_p++ = c;
5817 if (!traditional) {
5818 switch (c) {
5819 case '\'':
5820 case '\"':
5821 if (expected_delimiter != '\0') {
5822 if (c == expected_delimiter)
5823 expected_delimiter = '\0';
5824 } else
5825 expected_delimiter = c;
5826 break;
5828 case '\\':
5829 if (p < limit && expected_delimiter) {
5830 /* In a string, backslash goes through
5831 and makes next char ordinary. */
5832 *exp_p++ = *p++;
5834 break;
5836 case '%':
5837 if (!expected_delimiter && *p == ':') {
5838 /* %: is not a digraph if preceded by an odd number of '<'s. */
5839 U_CHAR *p0 = p - 1;
5840 while (buf < p0 && p0[-1] == '<')
5841 p0--;
5842 if ((p - p0) & 1) {
5843 /* Treat %:%: as ## and %: as #. */
5844 if (p[1] == '%' && p[2] == ':') {
5845 p += 2;
5846 goto hash_hash_token;
5848 if (nargs >= 0) {
5849 p++;
5850 goto hash_token;
5854 break;
5856 case '#':
5857 /* # is ordinary inside a string. */
5858 if (expected_delimiter)
5859 break;
5860 if (*p == '#') {
5861 hash_hash_token:
5862 /* ##: concatenate preceding and following tokens. */
5863 /* Take out the first #, discard preceding whitespace. */
5864 exp_p--;
5865 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5866 --exp_p;
5867 /* Skip the second #. */
5868 p++;
5869 /* Discard following whitespace. */
5870 SKIP_WHITE_SPACE (p);
5871 concat = p;
5872 concat_spelling = c;
5873 if (p == limit)
5874 error ("`##' at end of macro definition");
5875 } else if (nargs >= 0) {
5876 /* Single #: stringify following argument ref.
5877 Don't leave the # in the expansion. */
5878 hash_token:
5879 exp_p--;
5880 SKIP_WHITE_SPACE (p);
5881 if (! is_idstart[*p] || nargs == 0)
5882 error ("`#' operator is not followed by a macro argument name");
5883 else {
5884 stringify = p;
5885 stringify_spelling = c;
5888 break;
5890 } else {
5891 /* In -traditional mode, recognize arguments inside strings and
5892 and character constants, and ignore special properties of #.
5893 Arguments inside strings are considered "stringified", but no
5894 extra quote marks are supplied. */
5895 switch (c) {
5896 case '\'':
5897 case '\"':
5898 if (expected_delimiter != '\0') {
5899 if (c == expected_delimiter)
5900 expected_delimiter = '\0';
5901 } else
5902 expected_delimiter = c;
5903 break;
5905 case '\\':
5906 /* Backslash quotes delimiters and itself, but not macro args. */
5907 if (expected_delimiter != 0 && p < limit
5908 && (*p == expected_delimiter || *p == '\\')) {
5909 *exp_p++ = *p++;
5910 continue;
5912 break;
5914 case '/':
5915 if (expected_delimiter != '\0') /* No comments inside strings. */
5916 break;
5917 if (*p == '*') {
5918 /* If we find a comment that wasn't removed by handle_directive,
5919 this must be -traditional. So replace the comment with
5920 nothing at all. */
5921 exp_p--;
5922 p += 1;
5923 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
5924 p++;
5925 #if 0
5926 /* Mark this as a concatenation-point, as if it had been ##. */
5927 concat = p;
5928 #endif
5930 break;
5934 /* Handle the start of a symbol. */
5935 if (is_idchar[c] && nargs > 0) {
5936 U_CHAR *id_beg = p - 1;
5937 int id_len;
5939 --exp_p;
5940 while (p != limit && is_idchar[*p]) p++;
5941 id_len = p - id_beg;
5943 if (is_idstart[c]) {
5944 register struct arglist *arg;
5946 for (arg = arglist; arg != NULL; arg = arg->next) {
5947 struct reflist *tpat;
5949 if (arg->name[0] == c
5950 && arg->length == id_len
5951 && strncmp (arg->name, id_beg, id_len) == 0) {
5952 if (expected_delimiter && warn_stringify) {
5953 if (traditional) {
5954 warning ("macro argument `%.*s' is stringified.",
5955 id_len, arg->name);
5956 } else {
5957 warning ("macro arg `%.*s' would be stringified with -traditional.",
5958 id_len, arg->name);
5961 /* If ANSI, don't actually substitute inside a string. */
5962 if (!traditional && expected_delimiter)
5963 break;
5964 /* make a pat node for this arg and append it to the end of
5965 the pat list */
5966 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
5967 tpat->next = NULL;
5968 tpat->raw_before = concat == id_beg ? concat_spelling : 0;
5969 tpat->raw_after = 0;
5970 tpat->rest_args = arg->rest_args;
5971 tpat->stringify = (traditional ? expected_delimiter != '\0'
5972 : stringify == id_beg) ? stringify_spelling : 0;
5974 if (endpat == NULL)
5975 defn->pattern = tpat;
5976 else
5977 endpat->next = tpat;
5978 endpat = tpat;
5980 tpat->argno = arg->argno;
5981 tpat->nchars = exp_p - lastp;
5983 register U_CHAR *p1 = p;
5984 SKIP_WHITE_SPACE (p1);
5985 if (p1[0]=='#'
5986 ? p1[1]=='#'
5987 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
5988 tpat->raw_after = p1[0];
5990 lastp = exp_p; /* place to start copying from next time */
5991 skipped_arg = 1;
5992 break;
5997 /* If this was not a macro arg, copy it into the expansion. */
5998 if (! skipped_arg) {
5999 register U_CHAR *lim1 = p;
6000 p = id_beg;
6001 while (p != lim1)
6002 *exp_p++ = *p++;
6003 if (stringify == id_beg)
6004 error ("`#' operator should be followed by a macro argument name");
6009 if (!traditional && expected_delimiter == 0) {
6010 /* There is no trailing whitespace, so invent some in ANSI mode.
6011 But not if "inside a string" (which in ANSI mode
6012 happens only for -D option). */
6013 *exp_p++ = '\n';
6014 *exp_p++ = ' ';
6017 *exp_p = '\0';
6019 defn->length = exp_p - defn->expansion;
6021 /* Crash now if we overrun the allocated size. */
6022 if (defn->length + 1 > maxsize)
6023 abort ();
6025 #if 0
6026 /* This isn't worth the time it takes. */
6027 /* give back excess storage */
6028 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6029 #endif
6031 return defn;
6034 static int
6035 do_assert (buf, limit, op, keyword)
6036 U_CHAR *buf, *limit;
6037 FILE_BUF *op;
6038 struct directive *keyword;
6040 U_CHAR *bp; /* temp ptr into input buffer */
6041 U_CHAR *symname; /* remember where symbol name starts */
6042 int sym_length; /* and how long it is */
6043 struct arglist *tokens = NULL;
6045 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6046 pedwarn ("ANSI C does not allow `#assert'");
6048 bp = buf;
6050 while (is_hor_space[*bp])
6051 bp++;
6053 symname = bp; /* remember where it starts */
6054 sym_length = check_macro_name (bp, "assertion");
6055 bp += sym_length;
6056 /* #define doesn't do this, but we should. */
6057 SKIP_WHITE_SPACE (bp);
6059 /* Lossage will occur if identifiers or control tokens are broken
6060 across lines using backslash. This is not the right place to take
6061 care of that. */
6063 if (*bp != '(') {
6064 error ("missing token-sequence in `#assert'");
6065 return 1;
6069 int error_flag = 0;
6071 bp++; /* skip '(' */
6072 SKIP_WHITE_SPACE (bp);
6074 tokens = read_token_list (&bp, limit, &error_flag);
6075 if (error_flag)
6076 return 1;
6077 if (tokens == 0) {
6078 error ("empty token-sequence in `#assert'");
6079 return 1;
6082 ++bp; /* skip paren */
6083 SKIP_WHITE_SPACE (bp);
6086 /* If this name isn't already an assertion name, make it one.
6087 Error if it was already in use in some other way. */
6090 ASSERTION_HASHNODE *hp;
6091 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6092 struct tokenlist_list *value
6093 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6095 hp = assertion_lookup (symname, sym_length, hashcode);
6096 if (hp == NULL) {
6097 if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
6098 error ("`defined' redefined as assertion");
6099 hp = assertion_install (symname, sym_length, hashcode);
6102 /* Add the spec'd token-sequence to the list of such. */
6103 value->tokens = tokens;
6104 value->next = hp->value;
6105 hp->value = value;
6108 return 0;
6111 static int
6112 do_unassert (buf, limit, op, keyword)
6113 U_CHAR *buf, *limit;
6114 FILE_BUF *op;
6115 struct directive *keyword;
6117 U_CHAR *bp; /* temp ptr into input buffer */
6118 U_CHAR *symname; /* remember where symbol name starts */
6119 int sym_length; /* and how long it is */
6121 struct arglist *tokens = NULL;
6122 int tokens_specified = 0;
6124 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6125 pedwarn ("ANSI C does not allow `#unassert'");
6127 bp = buf;
6129 while (is_hor_space[*bp])
6130 bp++;
6132 symname = bp; /* remember where it starts */
6133 sym_length = check_macro_name (bp, "assertion");
6134 bp += sym_length;
6135 /* #define doesn't do this, but we should. */
6136 SKIP_WHITE_SPACE (bp);
6138 /* Lossage will occur if identifiers or control tokens are broken
6139 across lines using backslash. This is not the right place to take
6140 care of that. */
6142 if (*bp == '(') {
6143 int error_flag = 0;
6145 bp++; /* skip '(' */
6146 SKIP_WHITE_SPACE (bp);
6148 tokens = read_token_list (&bp, limit, &error_flag);
6149 if (error_flag)
6150 return 1;
6151 if (tokens == 0) {
6152 error ("empty token list in `#unassert'");
6153 return 1;
6156 tokens_specified = 1;
6158 ++bp; /* skip paren */
6159 SKIP_WHITE_SPACE (bp);
6163 ASSERTION_HASHNODE *hp;
6164 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6165 struct tokenlist_list *tail, *prev;
6167 hp = assertion_lookup (symname, sym_length, hashcode);
6168 if (hp == NULL)
6169 return 1;
6171 /* If no token list was specified, then eliminate this assertion
6172 entirely. */
6173 if (! tokens_specified) {
6174 struct tokenlist_list *next;
6175 for (tail = hp->value; tail; tail = next) {
6176 next = tail->next;
6177 free_token_list (tail->tokens);
6178 free (tail);
6180 delete_assertion (hp);
6181 } else {
6182 /* If a list of tokens was given, then delete any matching list. */
6184 tail = hp->value;
6185 prev = 0;
6186 while (tail) {
6187 struct tokenlist_list *next = tail->next;
6188 if (compare_token_lists (tail->tokens, tokens)) {
6189 if (prev)
6190 prev->next = next;
6191 else
6192 hp->value = tail->next;
6193 free_token_list (tail->tokens);
6194 free (tail);
6195 } else {
6196 prev = tail;
6198 tail = next;
6203 return 0;
6206 /* Test whether there is an assertion named NAME
6207 and optionally whether it has an asserted token list TOKENS.
6208 NAME is not null terminated; its length is SYM_LENGTH.
6209 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6212 check_assertion (name, sym_length, tokens_specified, tokens)
6213 U_CHAR *name;
6214 int sym_length;
6215 int tokens_specified;
6216 struct arglist *tokens;
6218 ASSERTION_HASHNODE *hp;
6219 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6221 if (pedantic && !instack[indepth].system_header_p)
6222 pedwarn ("ANSI C does not allow testing assertions");
6224 hp = assertion_lookup (name, sym_length, hashcode);
6225 if (hp == NULL)
6226 /* It is not an assertion; just return false. */
6227 return 0;
6229 /* If no token list was specified, then value is 1. */
6230 if (! tokens_specified)
6231 return 1;
6234 struct tokenlist_list *tail;
6236 tail = hp->value;
6238 /* If a list of tokens was given,
6239 then succeed if the assertion records a matching list. */
6241 while (tail) {
6242 if (compare_token_lists (tail->tokens, tokens))
6243 return 1;
6244 tail = tail->next;
6247 /* Fail if the assertion has no matching list. */
6248 return 0;
6252 /* Compare two lists of tokens for equality including order of tokens. */
6254 static int
6255 compare_token_lists (l1, l2)
6256 struct arglist *l1, *l2;
6258 while (l1 && l2) {
6259 if (l1->length != l2->length)
6260 return 0;
6261 if (strncmp (l1->name, l2->name, l1->length))
6262 return 0;
6263 l1 = l1->next;
6264 l2 = l2->next;
6267 /* Succeed if both lists end at the same time. */
6268 return l1 == l2;
6271 /* Read a space-separated list of tokens ending in a close parenthesis.
6272 Return a list of strings, in the order they were written.
6273 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6274 Parse the text starting at *BPP, and update *BPP.
6275 Don't parse beyond LIMIT. */
6277 static struct arglist *
6278 read_token_list (bpp, limit, error_flag)
6279 U_CHAR **bpp;
6280 U_CHAR *limit;
6281 int *error_flag;
6283 struct arglist *token_ptrs = 0;
6284 U_CHAR *bp = *bpp;
6285 int depth = 1;
6287 *error_flag = 0;
6289 /* Loop over the assertion value tokens. */
6290 while (depth > 0) {
6291 struct arglist *temp;
6292 int eofp = 0;
6293 U_CHAR *beg = bp;
6295 /* Find the end of the token. */
6296 if (*bp == '(') {
6297 bp++;
6298 depth++;
6299 } else if (*bp == ')') {
6300 depth--;
6301 if (depth == 0)
6302 break;
6303 bp++;
6304 } else if (*bp == '"' || *bp == '\'')
6305 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6306 else
6307 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6308 && *bp != '"' && *bp != '\'' && bp != limit)
6309 bp++;
6311 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6312 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6313 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6314 temp->name[bp - beg] = 0;
6315 temp->next = token_ptrs;
6316 token_ptrs = temp;
6317 temp->length = bp - beg;
6319 SKIP_WHITE_SPACE (bp);
6321 if (bp >= limit) {
6322 error ("unterminated token sequence in `#assert' or `#unassert'");
6323 *error_flag = -1;
6324 return 0;
6327 *bpp = bp;
6329 /* We accumulated the names in reverse order.
6330 Now reverse them to get the proper order. */
6332 register struct arglist *prev = 0, *this, *next;
6333 for (this = token_ptrs; this; this = next) {
6334 next = this->next;
6335 this->next = prev;
6336 prev = this;
6338 return prev;
6342 static void
6343 free_token_list (tokens)
6344 struct arglist *tokens;
6346 while (tokens) {
6347 struct arglist *next = tokens->next;
6348 free (tokens->name);
6349 free (tokens);
6350 tokens = next;
6355 * Install a name in the assertion hash table.
6357 * If LEN is >= 0, it is the length of the name.
6358 * Otherwise, compute the length by scanning the entire name.
6360 * If HASH is >= 0, it is the precomputed hash code.
6361 * Otherwise, compute the hash code.
6363 static ASSERTION_HASHNODE *
6364 assertion_install (name, len, hash)
6365 U_CHAR *name;
6366 int len;
6367 int hash;
6369 register ASSERTION_HASHNODE *hp;
6370 register int i, bucket;
6371 register U_CHAR *p, *q;
6373 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6374 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6375 bucket = hash;
6376 hp->bucket_hdr = &assertion_hashtab[bucket];
6377 hp->next = assertion_hashtab[bucket];
6378 assertion_hashtab[bucket] = hp;
6379 hp->prev = NULL;
6380 if (hp->next != NULL)
6381 hp->next->prev = hp;
6382 hp->length = len;
6383 hp->value = 0;
6384 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6385 p = hp->name;
6386 q = name;
6387 for (i = 0; i < len; i++)
6388 *p++ = *q++;
6389 hp->name[len] = 0;
6390 return hp;
6394 * find the most recent hash node for name name (ending with first
6395 * non-identifier char) installed by install
6397 * If LEN is >= 0, it is the length of the name.
6398 * Otherwise, compute the length by scanning the entire name.
6400 * If HASH is >= 0, it is the precomputed hash code.
6401 * Otherwise, compute the hash code.
6403 static ASSERTION_HASHNODE *
6404 assertion_lookup (name, len, hash)
6405 U_CHAR *name;
6406 int len;
6407 int hash;
6409 register ASSERTION_HASHNODE *bucket;
6411 bucket = assertion_hashtab[hash];
6412 while (bucket) {
6413 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
6414 return bucket;
6415 bucket = bucket->next;
6417 return NULL;
6420 static void
6421 delete_assertion (hp)
6422 ASSERTION_HASHNODE *hp;
6425 if (hp->prev != NULL)
6426 hp->prev->next = hp->next;
6427 if (hp->next != NULL)
6428 hp->next->prev = hp->prev;
6430 /* make sure that the bucket chain header that
6431 the deleted guy was on points to the right thing afterwards. */
6432 if (hp == *hp->bucket_hdr)
6433 *hp->bucket_hdr = hp->next;
6435 free (hp);
6439 * interpret #line command. Remembers previously seen fnames
6440 * in its very own hash table.
6442 #define FNAME_HASHSIZE 37
6444 static int
6445 do_line (buf, limit, op, keyword)
6446 U_CHAR *buf, *limit;
6447 FILE_BUF *op;
6448 struct directive *keyword;
6450 register U_CHAR *bp;
6451 FILE_BUF *ip = &instack[indepth];
6452 FILE_BUF tem;
6453 int new_lineno;
6454 enum file_change_code file_change = same_file;
6456 /* Expand any macros. */
6457 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6459 /* Point to macroexpanded line, which is null-terminated now. */
6460 bp = tem.buf;
6461 SKIP_WHITE_SPACE (bp);
6463 if (!isdigit (*bp)) {
6464 error ("invalid format `#line' command");
6465 return 0;
6468 /* The Newline at the end of this line remains to be processed.
6469 To put the next line at the specified line number,
6470 we must store a line number now that is one less. */
6471 new_lineno = atoi (bp) - 1;
6473 /* NEW_LINENO is one less than the actual line number here. */
6474 if (pedantic && new_lineno < 0)
6475 pedwarn ("line number out of range in `#line' command");
6477 /* skip over the line number. */
6478 while (isdigit (*bp))
6479 bp++;
6481 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6482 if (*bp && !is_space[*bp]) {
6483 error ("invalid format `#line' command");
6484 return;
6486 #endif
6488 SKIP_WHITE_SPACE (bp);
6490 if (*bp == '\"') {
6491 static HASHNODE *fname_table[FNAME_HASHSIZE];
6492 HASHNODE *hp, **hash_bucket;
6493 U_CHAR *fname, *p;
6494 int fname_length;
6496 fname = ++bp;
6498 /* Turn the file name, which is a character string literal,
6499 into a null-terminated string. Do this in place. */
6500 p = bp;
6501 for (;;)
6502 switch ((*p++ = *bp++)) {
6503 case '\0':
6504 error ("invalid format `#line' command");
6505 return 0;
6507 case '\\':
6509 char *bpc = (char *) bp;
6510 int c = parse_escape (&bpc);
6511 bp = (U_CHAR *) bpc;
6512 if (c < 0)
6513 p--;
6514 else
6515 p[-1] = c;
6517 break;
6519 case '\"':
6520 p[-1] = 0;
6521 goto fname_done;
6523 fname_done:
6524 fname_length = p - fname;
6526 SKIP_WHITE_SPACE (bp);
6527 if (*bp) {
6528 if (pedantic)
6529 pedwarn ("garbage at end of `#line' command");
6530 if (*bp == '1')
6531 file_change = enter_file;
6532 else if (*bp == '2')
6533 file_change = leave_file;
6534 else if (*bp == '3')
6535 ip->system_header_p = 1;
6536 else if (*bp == '4')
6537 ip->system_header_p = 2;
6538 else {
6539 error ("invalid format `#line' command");
6540 return 0;
6543 bp++;
6544 SKIP_WHITE_SPACE (bp);
6545 if (*bp == '3') {
6546 ip->system_header_p = 1;
6547 bp++;
6548 SKIP_WHITE_SPACE (bp);
6550 if (*bp == '4') {
6551 ip->system_header_p = 2;
6552 bp++;
6553 SKIP_WHITE_SPACE (bp);
6555 if (*bp) {
6556 error ("invalid format `#line' command");
6557 return 0;
6561 hash_bucket =
6562 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6563 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6564 if (hp->length == fname_length &&
6565 strncmp (hp->value.cpval, fname, fname_length) == 0) {
6566 ip->nominal_fname = hp->value.cpval;
6567 break;
6569 if (hp == 0) {
6570 /* Didn't find it; cons up a new one. */
6571 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6572 hp->next = *hash_bucket;
6573 *hash_bucket = hp;
6575 hp->length = fname_length;
6576 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6577 bcopy (fname, hp->value.cpval, fname_length);
6579 } else if (*bp) {
6580 error ("invalid format `#line' command");
6581 return 0;
6584 ip->lineno = new_lineno;
6585 output_line_command (ip, op, 0, file_change);
6586 check_expand (op, ip->length - (ip->bufp - ip->buf));
6587 return 0;
6591 * remove the definition of a symbol from the symbol table.
6592 * according to un*x /lib/cpp, it is not an error to undef
6593 * something that has no definitions, so it isn't one here either.
6596 static int
6597 do_undef (buf, limit, op, keyword)
6598 U_CHAR *buf, *limit;
6599 FILE_BUF *op;
6600 struct directive *keyword;
6602 int sym_length;
6603 HASHNODE *hp;
6604 U_CHAR *orig_buf = buf;
6606 /* If this is a precompiler run (with -pcp) pass thru #undef commands. */
6607 if (pcp_outfile && op)
6608 pass_thru_directive (buf, limit, op, keyword);
6610 SKIP_WHITE_SPACE (buf);
6611 sym_length = check_macro_name (buf, "macro");
6613 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6614 /* If we are generating additional info for debugging (with -g) we
6615 need to pass through all effective #undef commands. */
6616 if (debug_output && op)
6617 pass_thru_directive (orig_buf, limit, op, keyword);
6618 if (hp->type != T_MACRO)
6619 warning ("undefining `%s'", hp->name);
6620 delete_macro (hp);
6623 if (pedantic) {
6624 buf += sym_length;
6625 SKIP_WHITE_SPACE (buf);
6626 if (buf != limit)
6627 pedwarn ("garbage after `#undef' directive");
6629 return 0;
6633 * Report an error detected by the program we are processing.
6634 * Use the text of the line in the error message.
6635 * (We use error because it prints the filename & line#.)
6638 static int
6639 do_error (buf, limit, op, keyword)
6640 U_CHAR *buf, *limit;
6641 FILE_BUF *op;
6642 struct directive *keyword;
6644 int length = limit - buf;
6645 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6646 bcopy ((char *) buf, (char *) copy, length);
6647 copy[length] = 0;
6648 SKIP_WHITE_SPACE (copy);
6649 error ("#error %s", copy);
6650 return 0;
6654 * Report a warning detected by the program we are processing.
6655 * Use the text of the line in the warning message, then continue.
6656 * (We use error because it prints the filename & line#.)
6659 static int
6660 do_warning (buf, limit, op, keyword)
6661 U_CHAR *buf, *limit;
6662 FILE_BUF *op;
6663 struct directive *keyword;
6665 int length = limit - buf;
6666 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6667 bcopy ((char *) buf, (char *) copy, length);
6668 copy[length] = 0;
6669 SKIP_WHITE_SPACE (copy);
6670 warning ("#warning %s", copy);
6671 return 0;
6674 /* Remember the name of the current file being read from so that we can
6675 avoid ever including it again. */
6677 static int
6678 do_once ()
6680 int i;
6681 FILE_BUF *ip = NULL;
6683 for (i = indepth; i >= 0; i--)
6684 if (instack[i].fname != NULL) {
6685 ip = &instack[i];
6686 break;
6689 if (ip != NULL) {
6690 struct file_name_list *new;
6692 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6693 new->next = dont_repeat_files;
6694 dont_repeat_files = new;
6695 new->fname = savestring (ip->fname);
6696 new->control_macro = 0;
6697 new->got_name_map = 0;
6698 new->c_system_include_path = 0;
6700 return 0;
6703 /* #ident has already been copied to the output file, so just ignore it. */
6705 static int
6706 do_ident (buf, limit)
6707 U_CHAR *buf, *limit;
6709 FILE_BUF trybuf;
6710 int len;
6711 FILE_BUF *op = &outbuf;
6713 /* Allow #ident in system headers, since that's not user's fault. */
6714 if (pedantic && !instack[indepth].system_header_p)
6715 pedwarn ("ANSI C does not allow `#ident'");
6717 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6718 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6719 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6720 limit = buf + (trybuf.bufp - trybuf.buf);
6721 len = (limit - buf);
6722 free (trybuf.buf);
6724 /* Output directive name. */
6725 check_expand (op, 7);
6726 bcopy ("#ident ", (char *) op->bufp, 7);
6727 op->bufp += 7;
6729 /* Output the expanded argument line. */
6730 check_expand (op, len);
6731 bcopy ((char *) buf, (char *) op->bufp, len);
6732 op->bufp += len;
6734 return 0;
6737 /* #pragma and its argument line have already been copied to the output file.
6738 Just check for some recognized pragmas that need validation here. */
6740 static int
6741 do_pragma (buf, limit)
6742 U_CHAR *buf, *limit;
6744 SKIP_WHITE_SPACE (buf);
6745 if (!strncmp (buf, "once", 4)) {
6746 /* Allow #pragma once in system headers, since that's not the user's
6747 fault. */
6748 if (!instack[indepth].system_header_p)
6749 warning ("`#pragma once' is obsolete");
6750 do_once ();
6753 if (!strncmp (buf, "implementation", 14)) {
6754 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6755 been included yet. */
6756 struct file_name_list *ptr;
6757 U_CHAR *p = buf + 14, *fname, *inc_fname;
6758 SKIP_WHITE_SPACE (p);
6759 if (*p == '\n' || *p != '\"')
6760 return 0;
6762 fname = p + 1;
6763 if (p = (U_CHAR *) index (fname, '\"'))
6764 *p = '\0';
6766 for (ptr = all_include_files; ptr; ptr = ptr->next) {
6767 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
6768 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
6769 if (inc_fname && !strcmp (inc_fname, fname))
6770 warning ("`#pragma implementation' for `%s' appears after file is included",
6771 fname);
6775 return 0;
6778 #if 0
6779 /* This was a fun hack, but #pragma seems to start to be useful.
6780 By failing to recognize it, we pass it through unchanged to cc1. */
6783 * the behavior of the #pragma directive is implementation defined.
6784 * this implementation defines it as follows.
6787 static int
6788 do_pragma ()
6790 close (0);
6791 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6792 goto nope;
6793 close (1);
6794 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6795 goto nope;
6796 execl ("/usr/games/hack", "#pragma", 0);
6797 execl ("/usr/games/rogue", "#pragma", 0);
6798 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6799 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6800 nope:
6801 fatal ("You are in a maze of twisty compiler features, all different");
6803 #endif
6805 /* Just ignore #sccs, on systems where we define it at all. */
6807 static int
6808 do_sccs ()
6810 if (pedantic)
6811 pedwarn ("ANSI C does not allow `#sccs'");
6812 return 0;
6816 * handle #if command by
6817 * 1) inserting special `defined' keyword into the hash table
6818 * that gets turned into 0 or 1 by special_symbol (thus,
6819 * if the luser has a symbol called `defined' already, it won't
6820 * work inside the #if command)
6821 * 2) rescan the input into a temporary output buffer
6822 * 3) pass the output buffer to the yacc parser and collect a value
6823 * 4) clean up the mess left from steps 1 and 2.
6824 * 5) call conditional_skip to skip til the next #endif (etc.),
6825 * or not, depending on the value from step 3.
6828 static int
6829 do_if (buf, limit, op, keyword)
6830 U_CHAR *buf, *limit;
6831 FILE_BUF *op;
6832 struct directive *keyword;
6834 HOST_WIDE_INT value;
6835 FILE_BUF *ip = &instack[indepth];
6837 value = eval_if_expression (buf, limit - buf);
6838 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6839 return 0;
6843 * handle a #elif directive by not changing if_stack either.
6844 * see the comment above do_else.
6847 static int
6848 do_elif (buf, limit, op, keyword)
6849 U_CHAR *buf, *limit;
6850 FILE_BUF *op;
6851 struct directive *keyword;
6853 HOST_WIDE_INT value;
6854 FILE_BUF *ip = &instack[indepth];
6856 if (if_stack == instack[indepth].if_stack) {
6857 error ("`#elif' not within a conditional");
6858 return 0;
6859 } else {
6860 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6861 error ("`#elif' after `#else'");
6862 fprintf (stderr, " (matches line %d", if_stack->lineno);
6863 if (if_stack->fname != NULL && ip->fname != NULL &&
6864 strcmp (if_stack->fname, ip->nominal_fname) != 0)
6865 fprintf (stderr, ", file %s", if_stack->fname);
6866 fprintf (stderr, ")\n");
6868 if_stack->type = T_ELIF;
6871 if (if_stack->if_succeeded)
6872 skip_if_group (ip, 0, op);
6873 else {
6874 value = eval_if_expression (buf, limit - buf);
6875 if (value == 0)
6876 skip_if_group (ip, 0, op);
6877 else {
6878 ++if_stack->if_succeeded; /* continue processing input */
6879 output_line_command (ip, op, 1, same_file);
6882 return 0;
6886 * evaluate a #if expression in BUF, of length LENGTH,
6887 * then parse the result as a C expression and return the value as an int.
6889 static HOST_WIDE_INT
6890 eval_if_expression (buf, length)
6891 U_CHAR *buf;
6892 int length;
6894 FILE_BUF temp_obuf;
6895 HASHNODE *save_defined;
6896 HOST_WIDE_INT value;
6898 save_defined = install ("defined", -1, T_SPEC_DEFINED, NULL_PTR, -1);
6899 pcp_inside_if = 1;
6900 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6901 pcp_inside_if = 0;
6902 delete_macro (save_defined); /* clean up special symbol */
6904 value = parse_c_expression (temp_obuf.buf);
6906 free (temp_obuf.buf);
6908 return value;
6912 * routine to handle ifdef/ifndef. Try to look up the symbol,
6913 * then do or don't skip to the #endif/#else/#elif depending
6914 * on what directive is actually being processed.
6917 static int
6918 do_xifdef (buf, limit, op, keyword)
6919 U_CHAR *buf, *limit;
6920 FILE_BUF *op;
6921 struct directive *keyword;
6923 int skip;
6924 FILE_BUF *ip = &instack[indepth];
6925 U_CHAR *end;
6926 int start_of_file = 0;
6927 U_CHAR *control_macro = 0;
6929 /* Detect a #ifndef at start of file (not counting comments). */
6930 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
6931 U_CHAR *p = ip->buf;
6932 while (p != directive_start) {
6933 U_CHAR c = *p++;
6934 if (is_space[c])
6936 else if (c == '/' && p != ip->bufp && *p == '*') {
6937 /* Skip this comment. */
6938 int junk = 0;
6939 U_CHAR *save_bufp = ip->bufp;
6940 ip->bufp = p + 1;
6941 p = skip_to_end_of_comment (ip, &junk, 1);
6942 ip->bufp = save_bufp;
6943 } else {
6944 goto fail;
6947 /* If we get here, this conditional is the beginning of the file. */
6948 start_of_file = 1;
6949 fail: ;
6952 /* Discard leading and trailing whitespace. */
6953 SKIP_WHITE_SPACE (buf);
6954 while (limit != buf && is_hor_space[limit[-1]]) limit--;
6956 /* Find the end of the identifier at the beginning. */
6957 for (end = buf; is_idchar[*end]; end++);
6959 if (end == buf) {
6960 skip = (keyword->type == T_IFDEF);
6961 if (! traditional)
6962 pedwarn (end == limit ? "`#%s' with no argument"
6963 : "`#%s' argument starts with punctuation",
6964 keyword->name);
6965 } else {
6966 HASHNODE *hp;
6968 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
6969 pedwarn ("`#%s' argument starts with a digit", keyword->name);
6970 else if (end != limit && !traditional)
6971 pedwarn ("garbage at end of `#%s' argument", keyword->name);
6973 hp = lookup (buf, end-buf, -1);
6975 if (pcp_outfile) {
6976 /* Output a precondition for this macro. */
6977 if (hp &&
6978 (hp->type == T_CONST
6979 || (hp->type == T_MACRO && hp->value.defn->predefined)))
6980 fprintf (pcp_outfile, "#define %s\n", hp->name);
6981 else {
6982 U_CHAR *cp = buf;
6983 fprintf (pcp_outfile, "#undef ");
6984 while (is_idchar[*cp]) /* Ick! */
6985 fputc (*cp++, pcp_outfile);
6986 putc ('\n', pcp_outfile);
6990 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
6991 if (start_of_file && !skip) {
6992 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
6993 bcopy ((char *) buf, (char *) control_macro, end - buf);
6994 control_macro[end - buf] = 0;
6998 conditional_skip (ip, skip, T_IF, control_macro, op);
6999 return 0;
7002 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7003 If this is a #ifndef starting at the beginning of a file,
7004 CONTROL_MACRO is the macro name tested by the #ifndef.
7005 Otherwise, CONTROL_MACRO is 0. */
7007 static void
7008 conditional_skip (ip, skip, type, control_macro, op)
7009 FILE_BUF *ip;
7010 int skip;
7011 enum node_type type;
7012 U_CHAR *control_macro;
7013 FILE_BUF *op;
7015 IF_STACK_FRAME *temp;
7017 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7018 temp->fname = ip->nominal_fname;
7019 temp->lineno = ip->lineno;
7020 temp->next = if_stack;
7021 temp->control_macro = control_macro;
7022 if_stack = temp;
7024 if_stack->type = type;
7026 if (skip != 0) {
7027 skip_if_group (ip, 0, op);
7028 return;
7029 } else {
7030 ++if_stack->if_succeeded;
7031 output_line_command (ip, &outbuf, 1, same_file);
7036 * skip to #endif, #else, or #elif. adjust line numbers, etc.
7037 * leaves input ptr at the sharp sign found.
7038 * If ANY is nonzero, return at next directive of any sort.
7040 static void
7041 skip_if_group (ip, any, op)
7042 FILE_BUF *ip;
7043 int any;
7044 FILE_BUF *op;
7046 register U_CHAR *bp = ip->bufp, *cp;
7047 register U_CHAR *endb = ip->buf + ip->length;
7048 struct directive *kt;
7049 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7050 U_CHAR *beg_of_line = bp;
7051 register int ident_length;
7052 U_CHAR *ident, *after_ident;
7053 /* Save info about where the group starts. */
7054 U_CHAR *beg_of_group = bp;
7055 int beg_lineno = ip->lineno;
7057 if (output_conditionals && op != 0) {
7058 char *ptr = "#failed\n";
7059 int len = strlen (ptr);
7061 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7063 *op->bufp++ = '\n';
7064 op->lineno++;
7066 check_expand (op, len);
7067 bcopy (ptr, (char *) op->bufp, len);
7068 op->bufp += len;
7069 op->lineno++;
7070 output_line_command (ip, op, 1, 0);
7073 while (bp < endb) {
7074 switch (*bp++) {
7075 case '/': /* possible comment */
7076 if (*bp == '\\' && bp[1] == '\n')
7077 newline_fix (bp);
7078 if (*bp == '*'
7079 || (cplusplus_comments && *bp == '/')) {
7080 ip->bufp = ++bp;
7081 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7083 break;
7084 case '\"':
7085 case '\'':
7086 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7087 NULL_PTR, NULL_PTR);
7088 break;
7089 case '\\':
7090 /* Char after backslash loses its special meaning. */
7091 if (bp < endb) {
7092 if (*bp == '\n')
7093 ++ip->lineno; /* But do update the line-count. */
7094 bp++;
7096 break;
7097 case '\n':
7098 ++ip->lineno;
7099 beg_of_line = bp;
7100 break;
7101 case '%':
7102 if (beg_of_line == 0 || traditional)
7103 break;
7104 ip->bufp = bp - 1;
7105 while (bp[0] == '\\' && bp[1] == '\n')
7106 bp += 2;
7107 if (*bp == ':')
7108 goto hash_token;
7109 break;
7110 case '#':
7111 /* # keyword: a # must be first nonblank char on the line */
7112 if (beg_of_line == 0)
7113 break;
7114 ip->bufp = bp - 1;
7115 hash_token:
7116 /* Scan from start of line, skipping whitespace, comments
7117 and backslash-newlines, and see if we reach this #.
7118 If not, this # is not special. */
7119 bp = beg_of_line;
7120 /* If -traditional, require # to be at beginning of line. */
7121 if (!traditional) {
7122 while (1) {
7123 if (is_hor_space[*bp])
7124 bp++;
7125 else if (*bp == '\\' && bp[1] == '\n')
7126 bp += 2;
7127 else if (*bp == '/' && bp[1] == '*') {
7128 bp += 2;
7129 while (!(*bp == '*' && bp[1] == '/'))
7130 bp++;
7131 bp += 2;
7133 /* There is no point in trying to deal with C++ // comments here,
7134 because if there is one, then this # must be part of the
7135 comment and we would never reach here. */
7136 else break;
7139 if (bp != ip->bufp) {
7140 bp = ip->bufp + 1; /* Reset bp to after the #. */
7141 break;
7144 bp = ip->bufp + 1; /* Point after the '#' */
7145 if (ip->bufp[0] == '%') {
7146 /* Skip past the ':' again. */
7147 while (*bp == '\\') {
7148 ip->lineno++;
7149 bp += 2;
7151 bp++;
7154 /* Skip whitespace and \-newline. */
7155 while (1) {
7156 if (is_hor_space[*bp])
7157 bp++;
7158 else if (*bp == '\\' && bp[1] == '\n')
7159 bp += 2;
7160 else if (*bp == '/' && bp[1] == '*') {
7161 bp += 2;
7162 while (!(*bp == '*' && bp[1] == '/')) {
7163 if (*bp == '\n')
7164 ip->lineno++;
7165 bp++;
7167 bp += 2;
7168 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
7169 bp += 2;
7170 while (bp[-1] == '\\' || *bp != '\n') {
7171 if (*bp == '\n')
7172 ip->lineno++;
7173 bp++;
7176 else break;
7179 cp = bp;
7181 /* Now find end of directive name.
7182 If we encounter a backslash-newline, exchange it with any following
7183 symbol-constituents so that we end up with a contiguous name. */
7185 while (1) {
7186 if (is_idchar[*bp])
7187 bp++;
7188 else {
7189 if (*bp == '\\' && bp[1] == '\n')
7190 name_newline_fix (bp);
7191 if (is_idchar[*bp])
7192 bp++;
7193 else break;
7196 ident_length = bp - cp;
7197 ident = cp;
7198 after_ident = bp;
7200 /* A line of just `#' becomes blank. */
7202 if (ident_length == 0 && *after_ident == '\n') {
7203 continue;
7206 if (ident_length == 0 || !is_idstart[*ident]) {
7207 U_CHAR *p = ident;
7208 while (is_idchar[*p]) {
7209 if (*p < '0' || *p > '9')
7210 break;
7211 p++;
7213 /* Handle # followed by a line number. */
7214 if (p != ident && !is_idchar[*p]) {
7215 if (pedantic)
7216 pedwarn ("`#' followed by integer");
7217 continue;
7220 /* Avoid error for `###' and similar cases unless -pedantic. */
7221 if (p == ident) {
7222 while (*p == '#' || is_hor_space[*p]) p++;
7223 if (*p == '\n') {
7224 if (pedantic && !lang_asm)
7225 pedwarn ("invalid preprocessor directive");
7226 continue;
7230 if (!lang_asm && pedantic)
7231 pedwarn ("invalid preprocessor directive name");
7232 continue;
7235 for (kt = directive_table; kt->length >= 0; kt++) {
7236 IF_STACK_FRAME *temp;
7237 if (ident_length == kt->length
7238 && strncmp (cp, kt->name, kt->length) == 0) {
7239 /* If we are asked to return on next directive, do so now. */
7240 if (any)
7241 goto done;
7243 switch (kt->type) {
7244 case T_IF:
7245 case T_IFDEF:
7246 case T_IFNDEF:
7247 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7248 temp->next = if_stack;
7249 if_stack = temp;
7250 temp->lineno = ip->lineno;
7251 temp->fname = ip->nominal_fname;
7252 temp->type = kt->type;
7253 break;
7254 case T_ELSE:
7255 case T_ENDIF:
7256 if (pedantic && if_stack != save_if_stack)
7257 validate_else (bp);
7258 case T_ELIF:
7259 if (if_stack == instack[indepth].if_stack) {
7260 error ("`#%s' not within a conditional", kt->name);
7261 break;
7263 else if (if_stack == save_if_stack)
7264 goto done; /* found what we came for */
7266 if (kt->type != T_ENDIF) {
7267 if (if_stack->type == T_ELSE)
7268 error ("`#else' or `#elif' after `#else'");
7269 if_stack->type = kt->type;
7270 break;
7273 temp = if_stack;
7274 if_stack = if_stack->next;
7275 free (temp);
7276 break;
7278 break;
7281 /* Don't let erroneous code go by. */
7282 if (kt->length < 0 && !lang_asm && pedantic)
7283 pedwarn ("invalid preprocessor directive name");
7287 ip->bufp = bp;
7288 /* after this returns, rescan will exit because ip->bufp
7289 now points to the end of the buffer.
7290 rescan is responsible for the error message also. */
7292 done:
7293 if (output_conditionals && op != 0) {
7294 char *ptr = "#endfailed\n";
7295 int len = strlen (ptr);
7297 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7299 *op->bufp++ = '\n';
7300 op->lineno++;
7302 check_expand (op, beg_of_line - beg_of_group);
7303 bcopy ((char *) beg_of_group, (char *) op->bufp,
7304 beg_of_line - beg_of_group);
7305 op->bufp += beg_of_line - beg_of_group;
7306 op->lineno += ip->lineno - beg_lineno;
7307 check_expand (op, len);
7308 bcopy (ptr, (char *) op->bufp, len);
7309 op->bufp += len;
7310 op->lineno++;
7315 * handle a #else directive. Do this by just continuing processing
7316 * without changing if_stack ; this is so that the error message
7317 * for missing #endif's etc. will point to the original #if. It
7318 * is possible that something different would be better.
7321 static int
7322 do_else (buf, limit, op, keyword)
7323 U_CHAR *buf, *limit;
7324 FILE_BUF *op;
7325 struct directive *keyword;
7327 FILE_BUF *ip = &instack[indepth];
7329 if (pedantic) {
7330 SKIP_WHITE_SPACE (buf);
7331 if (buf != limit)
7332 pedwarn ("text following `#else' violates ANSI standard");
7335 if (if_stack == instack[indepth].if_stack) {
7336 error ("`#else' not within a conditional");
7337 return 0;
7338 } else {
7339 /* #ifndef can't have its special treatment for containing the whole file
7340 if it has a #else clause. */
7341 if_stack->control_macro = 0;
7343 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7344 error ("`#else' after `#else'");
7345 fprintf (stderr, " (matches line %d", if_stack->lineno);
7346 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7347 fprintf (stderr, ", file %s", if_stack->fname);
7348 fprintf (stderr, ")\n");
7350 if_stack->type = T_ELSE;
7353 if (if_stack->if_succeeded)
7354 skip_if_group (ip, 0, op);
7355 else {
7356 ++if_stack->if_succeeded; /* continue processing input */
7357 output_line_command (ip, op, 1, same_file);
7359 return 0;
7363 * unstack after #endif command
7366 static int
7367 do_endif (buf, limit, op, keyword)
7368 U_CHAR *buf, *limit;
7369 FILE_BUF *op;
7370 struct directive *keyword;
7372 if (pedantic) {
7373 SKIP_WHITE_SPACE (buf);
7374 if (buf != limit)
7375 pedwarn ("text following `#endif' violates ANSI standard");
7378 if (if_stack == instack[indepth].if_stack)
7379 error ("unbalanced `#endif'");
7380 else {
7381 IF_STACK_FRAME *temp = if_stack;
7382 if_stack = if_stack->next;
7383 if (temp->control_macro != 0) {
7384 /* This #endif matched a #ifndef at the start of the file.
7385 See if it is at the end of the file. */
7386 FILE_BUF *ip = &instack[indepth];
7387 U_CHAR *p = ip->bufp;
7388 U_CHAR *ep = ip->buf + ip->length;
7390 while (p != ep) {
7391 U_CHAR c = *p++;
7392 if (!is_space[c]) {
7393 if (c == '/' && p != ep && *p == '*') {
7394 /* Skip this comment. */
7395 int junk = 0;
7396 U_CHAR *save_bufp = ip->bufp;
7397 ip->bufp = p + 1;
7398 p = skip_to_end_of_comment (ip, &junk, 1);
7399 ip->bufp = save_bufp;
7400 } else
7401 goto fail;
7404 /* If we get here, this #endif ends a #ifndef
7405 that contains all of the file (aside from whitespace).
7406 Arrange not to include the file again
7407 if the macro that was tested is defined.
7409 Do not do this for the top-level file in a -include or any
7410 file in a -imacros. */
7411 if (indepth != 0
7412 && ! (indepth == 1 && no_record_file)
7413 && ! (no_record_file && no_output))
7414 record_control_macro (ip->fname, temp->control_macro);
7415 fail: ;
7417 free (temp);
7418 output_line_command (&instack[indepth], op, 1, same_file);
7420 return 0;
7423 /* When an #else or #endif is found while skipping failed conditional,
7424 if -pedantic was specified, this is called to warn about text after
7425 the command name. P points to the first char after the command name. */
7427 static void
7428 validate_else (p)
7429 register U_CHAR *p;
7431 /* Advance P over whitespace and comments. */
7432 while (1) {
7433 if (*p == '\\' && p[1] == '\n')
7434 p += 2;
7435 if (is_hor_space[*p])
7436 p++;
7437 else if (*p == '/') {
7438 if (p[1] == '\\' && p[2] == '\n')
7439 newline_fix (p + 1);
7440 if (p[1] == '*') {
7441 p += 2;
7442 /* Don't bother warning about unterminated comments
7443 since that will happen later. Just be sure to exit. */
7444 while (*p) {
7445 if (p[1] == '\\' && p[2] == '\n')
7446 newline_fix (p + 1);
7447 if (*p == '*' && p[1] == '/') {
7448 p += 2;
7449 break;
7451 p++;
7454 else if (cplusplus_comments && p[1] == '/') {
7455 p += 2;
7456 while (*p && (*p != '\n' || p[-1] == '\\'))
7457 p++;
7459 } else break;
7461 if (*p && *p != '\n')
7462 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7465 /* Skip a comment, assuming the input ptr immediately follows the
7466 initial slash-star. Bump *LINE_COUNTER for each newline.
7467 (The canonical line counter is &ip->lineno.)
7468 Don't use this routine (or the next one) if bumping the line
7469 counter is not sufficient to deal with newlines in the string.
7471 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7472 This feature is useful when processing a comment that is going to be
7473 processed or was processed at another point in the preprocessor,
7474 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7476 static U_CHAR *
7477 skip_to_end_of_comment (ip, line_counter, nowarn)
7478 register FILE_BUF *ip;
7479 int *line_counter; /* place to remember newlines, or NULL */
7480 int nowarn;
7482 register U_CHAR *limit = ip->buf + ip->length;
7483 register U_CHAR *bp = ip->bufp;
7484 FILE_BUF *op = &outbuf; /* JF */
7485 int output = put_out_comments && !line_counter;
7486 int start_line = line_counter ? *line_counter : 0;
7488 /* JF this line_counter stuff is a crock to make sure the
7489 comment is only put out once, no matter how many times
7490 the comment is skipped. It almost works */
7491 if (output) {
7492 *op->bufp++ = '/';
7493 *op->bufp++ = '*';
7495 if (cplusplus_comments && bp[-1] == '/') {
7496 if (output) {
7497 while (bp < limit) {
7498 *op->bufp++ = *bp;
7499 if (*bp == '\n' && bp[-1] != '\\')
7500 break;
7501 if (*bp == '\n') {
7502 ++*line_counter;
7503 ++op->lineno;
7505 bp++;
7507 op->bufp[-1] = '*';
7508 *op->bufp++ = '/';
7509 *op->bufp++ = '\n';
7510 } else {
7511 while (bp < limit) {
7512 if (bp[-1] != '\\' && *bp == '\n') {
7513 break;
7514 } else {
7515 if (*bp == '\n' && line_counter)
7516 ++*line_counter;
7517 bp++;
7521 ip->bufp = bp;
7522 return bp;
7524 while (bp < limit) {
7525 if (output)
7526 *op->bufp++ = *bp;
7527 switch (*bp++) {
7528 case '/':
7529 if (warn_comments && !nowarn && bp < limit && *bp == '*')
7530 warning ("`/*' within comment");
7531 break;
7532 case '\n':
7533 /* If this is the end of the file, we have an unterminated comment.
7534 Don't swallow the newline. We are guaranteed that there will be a
7535 trailing newline and various pieces assume it's there. */
7536 if (bp == limit)
7538 --bp;
7539 --limit;
7540 break;
7542 if (line_counter != NULL)
7543 ++*line_counter;
7544 if (output)
7545 ++op->lineno;
7546 break;
7547 case '*':
7548 if (*bp == '\\' && bp[1] == '\n')
7549 newline_fix (bp);
7550 if (*bp == '/') {
7551 if (output)
7552 *op->bufp++ = '/';
7553 ip->bufp = ++bp;
7554 return bp;
7556 break;
7560 if (!nowarn)
7561 error_with_line (line_for_error (start_line), "unterminated comment");
7562 ip->bufp = bp;
7563 return bp;
7567 * Skip over a quoted string. BP points to the opening quote.
7568 * Returns a pointer after the closing quote. Don't go past LIMIT.
7569 * START_LINE is the line number of the starting point (but it need
7570 * not be valid if the starting point is inside a macro expansion).
7572 * The input stack state is not changed.
7574 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7575 * for each newline passed.
7577 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7578 * if we pass a backslash-newline.
7580 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7582 static U_CHAR *
7583 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7584 register U_CHAR *bp;
7585 register U_CHAR *limit;
7586 int start_line;
7587 int *count_newlines;
7588 int *backslash_newlines_p;
7589 int *eofp;
7591 register U_CHAR c, match;
7593 match = *bp++;
7594 while (1) {
7595 if (bp >= limit) {
7596 error_with_line (line_for_error (start_line),
7597 "unterminated string or character constant");
7598 error_with_line (multiline_string_line,
7599 "possible real start of unterminated constant");
7600 multiline_string_line = 0;
7601 if (eofp)
7602 *eofp = 1;
7603 break;
7605 c = *bp++;
7606 if (c == '\\') {
7607 while (*bp == '\\' && bp[1] == '\n') {
7608 if (backslash_newlines_p)
7609 *backslash_newlines_p = 1;
7610 if (count_newlines)
7611 ++*count_newlines;
7612 bp += 2;
7614 if (*bp == '\n' && count_newlines) {
7615 if (backslash_newlines_p)
7616 *backslash_newlines_p = 1;
7617 ++*count_newlines;
7619 bp++;
7620 } else if (c == '\n') {
7621 if (traditional) {
7622 /* Unterminated strings and character constants are 'valid'. */
7623 bp--; /* Don't consume the newline. */
7624 if (eofp)
7625 *eofp = 1;
7626 break;
7628 if (pedantic || match == '\'') {
7629 error_with_line (line_for_error (start_line),
7630 "unterminated string or character constant");
7631 bp--;
7632 if (eofp)
7633 *eofp = 1;
7634 break;
7636 /* If not traditional, then allow newlines inside strings. */
7637 if (count_newlines)
7638 ++*count_newlines;
7639 if (multiline_string_line == 0)
7640 multiline_string_line = start_line;
7641 } else if (c == match)
7642 break;
7644 return bp;
7647 /* Place into DST a quoted string representing the string SRC.
7648 Return the address of DST's terminating null. */
7649 static char *
7650 quote_string (dst, src)
7651 char *dst, *src;
7653 U_CHAR c;
7655 *dst++ = '\"';
7656 for (;;)
7657 switch ((c = *src++))
7659 default:
7660 if (isprint (c))
7661 *dst++ = c;
7662 else
7664 sprintf (dst, "\\%03o", c);
7665 dst += 4;
7667 break;
7669 case '\"':
7670 case '\\':
7671 *dst++ = '\\';
7672 *dst++ = c;
7673 break;
7675 case '\0':
7676 *dst++ = '\"';
7677 *dst = '\0';
7678 return dst;
7682 /* Skip across a group of balanced parens, starting from IP->bufp.
7683 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7685 This does not handle newlines, because it's used for the arg of #if,
7686 where there aren't any newlines. Also, backslash-newline can't appear. */
7688 static U_CHAR *
7689 skip_paren_group (ip)
7690 register FILE_BUF *ip;
7692 U_CHAR *limit = ip->buf + ip->length;
7693 U_CHAR *p = ip->bufp;
7694 int depth = 0;
7695 int lines_dummy = 0;
7697 while (p != limit) {
7698 int c = *p++;
7699 switch (c) {
7700 case '(':
7701 depth++;
7702 break;
7704 case ')':
7705 depth--;
7706 if (depth == 0)
7707 return ip->bufp = p;
7708 break;
7710 case '/':
7711 if (*p == '*') {
7712 ip->bufp = p;
7713 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7714 p = ip->bufp;
7717 case '"':
7718 case '\'':
7720 int eofp = 0;
7721 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7722 if (eofp)
7723 return ip->bufp = p;
7725 break;
7729 ip->bufp = p;
7730 return p;
7734 * write out a #line command, for instance, after an #include file.
7735 * If CONDITIONAL is nonzero, we can omit the #line if it would
7736 * appear to be a no-op, and we can output a few newlines instead
7737 * if we want to increase the line number by a small amount.
7738 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7741 static void
7742 output_line_command (ip, op, conditional, file_change)
7743 FILE_BUF *ip, *op;
7744 int conditional;
7745 enum file_change_code file_change;
7747 int len;
7748 char *line_cmd_buf, *line_end;
7750 if (no_line_commands
7751 || ip->fname == NULL
7752 || no_output) {
7753 op->lineno = ip->lineno;
7754 return;
7757 if (conditional) {
7758 if (ip->lineno == op->lineno)
7759 return;
7761 /* If the inherited line number is a little too small,
7762 output some newlines instead of a #line command. */
7763 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7764 check_expand (op, 10);
7765 while (ip->lineno > op->lineno) {
7766 *op->bufp++ = '\n';
7767 op->lineno++;
7769 return;
7773 /* Don't output a line number of 0 if we can help it. */
7774 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7775 && *ip->bufp == '\n') {
7776 ip->lineno++;
7777 ip->bufp++;
7780 line_cmd_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7781 #ifdef OUTPUT_LINE_COMMANDS
7782 sprintf (line_cmd_buf, "#line %d ", ip->lineno);
7783 #else
7784 sprintf (line_cmd_buf, "# %d ", ip->lineno);
7785 #endif
7786 line_end = quote_string (line_cmd_buf + strlen (line_cmd_buf),
7787 ip->nominal_fname);
7788 if (file_change != same_file) {
7789 *line_end++ = ' ';
7790 *line_end++ = file_change == enter_file ? '1' : '2';
7792 /* Tell cc1 if following text comes from a system header file. */
7793 if (ip->system_header_p) {
7794 *line_end++ = ' ';
7795 *line_end++ = '3';
7797 #ifndef NO_IMPLICIT_EXTERN_C
7798 /* Tell cc1plus if following text should be treated as C. */
7799 if (ip->system_header_p == 2 && cplusplus) {
7800 *line_end++ = ' ';
7801 *line_end++ = '4';
7803 #endif
7804 *line_end++ = '\n';
7805 len = line_end - line_cmd_buf;
7806 check_expand (op, len + 1);
7807 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7808 *op->bufp++ = '\n';
7809 bcopy ((char *) line_cmd_buf, (char *) op->bufp, len);
7810 op->bufp += len;
7811 op->lineno = ip->lineno;
7814 /* This structure represents one parsed argument in a macro call.
7815 `raw' points to the argument text as written (`raw_length' is its length).
7816 `expanded' points to the argument's macro-expansion
7817 (its length is `expand_length').
7818 `stringified_length' is the length the argument would have
7819 if stringified.
7820 `use_count' is the number of times this macro arg is substituted
7821 into the macro. If the actual use count exceeds 10,
7822 the value stored is 10.
7823 `free1' and `free2', if nonzero, point to blocks to be freed
7824 when the macro argument data is no longer needed. */
7826 struct argdata {
7827 U_CHAR *raw, *expanded;
7828 int raw_length, expand_length;
7829 int stringified_length;
7830 U_CHAR *free1, *free2;
7831 char newlines;
7832 char comments;
7833 char use_count;
7836 /* Expand a macro call.
7837 HP points to the symbol that is the macro being called.
7838 Put the result of expansion onto the input stack
7839 so that subsequent input by our caller will use it.
7841 If macro wants arguments, caller has already verified that
7842 an argument list follows; arguments come from the input stack. */
7844 static void
7845 macroexpand (hp, op)
7846 HASHNODE *hp;
7847 FILE_BUF *op;
7849 int nargs;
7850 DEFINITION *defn = hp->value.defn;
7851 register U_CHAR *xbuf;
7852 int xbuf_len;
7853 int start_line = instack[indepth].lineno;
7854 int rest_args, rest_zero;
7856 CHECK_DEPTH (return;);
7858 /* it might not actually be a macro. */
7859 if (hp->type != T_MACRO) {
7860 special_symbol (hp, op);
7861 return;
7864 /* This macro is being used inside a #if, which means it must be */
7865 /* recorded as a precondition. */
7866 if (pcp_inside_if && pcp_outfile && defn->predefined)
7867 dump_single_macro (hp, pcp_outfile);
7869 nargs = defn->nargs;
7871 if (nargs >= 0) {
7872 register int i;
7873 struct argdata *args;
7874 char *parse_error = 0;
7876 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7878 for (i = 0; i < nargs; i++) {
7879 args[i].raw = (U_CHAR *) "";
7880 args[i].expanded = 0;
7881 args[i].raw_length = args[i].expand_length
7882 = args[i].stringified_length = 0;
7883 args[i].free1 = args[i].free2 = 0;
7884 args[i].use_count = 0;
7887 /* Parse all the macro args that are supplied. I counts them.
7888 The first NARGS args are stored in ARGS.
7889 The rest are discarded.
7890 If rest_args is set then we assume macarg absorbed the rest of the args.
7892 i = 0;
7893 rest_args = 0;
7894 do {
7895 /* Discard the open-parenthesis or comma before the next arg. */
7896 ++instack[indepth].bufp;
7897 if (rest_args)
7898 continue;
7899 if (i < nargs || (nargs == 0 && i == 0)) {
7900 /* if we are working on last arg which absorbs rest of args... */
7901 if (i == nargs - 1 && defn->rest_args)
7902 rest_args = 1;
7903 parse_error = macarg (&args[i], rest_args);
7905 else
7906 parse_error = macarg (NULL_PTR, 0);
7907 if (parse_error) {
7908 error_with_line (line_for_error (start_line), parse_error);
7909 break;
7911 i++;
7912 } while (*instack[indepth].bufp != ')');
7914 /* If we got one arg but it was just whitespace, call that 0 args. */
7915 if (i == 1) {
7916 register U_CHAR *bp = args[0].raw;
7917 register U_CHAR *lim = bp + args[0].raw_length;
7918 /* cpp.texi says for foo ( ) we provide one argument.
7919 However, if foo wants just 0 arguments, treat this as 0. */
7920 if (nargs == 0)
7921 while (bp != lim && is_space[*bp]) bp++;
7922 if (bp == lim)
7923 i = 0;
7926 /* Don't output an error message if we have already output one for
7927 a parse error above. */
7928 rest_zero = 0;
7929 if (nargs == 0 && i > 0) {
7930 if (! parse_error)
7931 error ("arguments given to macro `%s'", hp->name);
7932 } else if (i < nargs) {
7933 /* traditional C allows foo() if foo wants one argument. */
7934 if (nargs == 1 && i == 0 && traditional)
7936 /* the rest args token is allowed to absorb 0 tokens */
7937 else if (i == nargs - 1 && defn->rest_args)
7938 rest_zero = 1;
7939 else if (parse_error)
7941 else if (i == 0)
7942 error ("macro `%s' used without args", hp->name);
7943 else if (i == 1)
7944 error ("macro `%s' used with just one arg", hp->name);
7945 else
7946 error ("macro `%s' used with only %d args", hp->name, i);
7947 } else if (i > nargs) {
7948 if (! parse_error)
7949 error ("macro `%s' used with too many (%d) args", hp->name, i);
7952 /* Swallow the closeparen. */
7953 ++instack[indepth].bufp;
7955 /* If macro wants zero args, we parsed the arglist for checking only.
7956 Read directly from the macro definition. */
7957 if (nargs == 0) {
7958 xbuf = defn->expansion;
7959 xbuf_len = defn->length;
7960 } else {
7961 register U_CHAR *exp = defn->expansion;
7962 register int offset; /* offset in expansion,
7963 copied a piece at a time */
7964 register int totlen; /* total amount of exp buffer filled so far */
7966 register struct reflist *ap, *last_ap;
7968 /* Macro really takes args. Compute the expansion of this call. */
7970 /* Compute length in characters of the macro's expansion.
7971 Also count number of times each arg is used. */
7972 xbuf_len = defn->length;
7973 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
7974 if (ap->stringify)
7975 xbuf_len += args[ap->argno].stringified_length;
7976 else if (ap->raw_before || ap->raw_after || traditional)
7977 /* Add 4 for two newline-space markers to prevent
7978 token concatenation. */
7979 xbuf_len += args[ap->argno].raw_length + 4;
7980 else {
7981 /* We have an ordinary (expanded) occurrence of the arg.
7982 So compute its expansion, if we have not already. */
7983 if (args[ap->argno].expanded == 0) {
7984 FILE_BUF obuf;
7985 obuf = expand_to_temp_buffer (args[ap->argno].raw,
7986 args[ap->argno].raw + args[ap->argno].raw_length,
7987 1, 0);
7989 args[ap->argno].expanded = obuf.buf;
7990 args[ap->argno].expand_length = obuf.length;
7991 args[ap->argno].free2 = obuf.buf;
7994 /* Add 4 for two newline-space markers to prevent
7995 token concatenation. */
7996 xbuf_len += args[ap->argno].expand_length + 4;
7998 if (args[ap->argno].use_count < 10)
7999 args[ap->argno].use_count++;
8002 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8004 /* Generate in XBUF the complete expansion
8005 with arguments substituted in.
8006 TOTLEN is the total size generated so far.
8007 OFFSET is the index in the definition
8008 of where we are copying from. */
8009 offset = totlen = 0;
8010 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8011 last_ap = ap, ap = ap->next) {
8012 register struct argdata *arg = &args[ap->argno];
8013 int count_before = totlen;
8015 /* Add chars to XBUF. */
8016 for (i = 0; i < ap->nchars; i++, offset++)
8017 xbuf[totlen++] = exp[offset];
8019 /* If followed by an empty rest arg with concatenation,
8020 delete the last run of nonwhite chars. */
8021 if (rest_zero && totlen > count_before
8022 && ((ap->rest_args && ap->raw_before)
8023 || (last_ap != NULL && last_ap->rest_args
8024 && last_ap->raw_after))) {
8025 /* Delete final whitespace. */
8026 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8027 totlen--;
8030 /* Delete the nonwhites before them. */
8031 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8032 totlen--;
8036 if (ap->stringify != 0) {
8037 int arglen = arg->raw_length;
8038 int escaped = 0;
8039 int in_string = 0;
8040 int c;
8041 i = 0;
8042 while (i < arglen
8043 && (c = arg->raw[i], is_space[c]))
8044 i++;
8045 while (i < arglen
8046 && (c = arg->raw[arglen - 1], is_space[c]))
8047 arglen--;
8048 if (!traditional)
8049 xbuf[totlen++] = '\"'; /* insert beginning quote */
8050 for (; i < arglen; i++) {
8051 c = arg->raw[i];
8053 /* Special markers Newline Space
8054 generate nothing for a stringified argument. */
8055 if (c == '\n' && arg->raw[i+1] != '\n') {
8056 i++;
8057 continue;
8060 /* Internal sequences of whitespace are replaced by one space
8061 except within an string or char token. */
8062 if (! in_string
8063 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8064 while (1) {
8065 /* Note that Newline Space does occur within whitespace
8066 sequences; consider it part of the sequence. */
8067 if (c == '\n' && is_space[arg->raw[i+1]])
8068 i += 2;
8069 else if (c != '\n' && is_space[c])
8070 i++;
8071 else break;
8072 c = arg->raw[i];
8074 i--;
8075 c = ' ';
8078 if (escaped)
8079 escaped = 0;
8080 else {
8081 if (c == '\\')
8082 escaped = 1;
8083 if (in_string) {
8084 if (c == in_string)
8085 in_string = 0;
8086 } else if (c == '\"' || c == '\'')
8087 in_string = c;
8090 /* Escape these chars */
8091 if (c == '\"' || (in_string && c == '\\'))
8092 xbuf[totlen++] = '\\';
8093 if (isprint (c))
8094 xbuf[totlen++] = c;
8095 else {
8096 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8097 totlen += 4;
8100 if (!traditional)
8101 xbuf[totlen++] = '\"'; /* insert ending quote */
8102 } else if (ap->raw_before || ap->raw_after || traditional) {
8103 U_CHAR *p1 = arg->raw;
8104 U_CHAR *l1 = p1 + arg->raw_length;
8105 if (ap->raw_before) {
8106 while (p1 != l1 && is_space[*p1]) p1++;
8107 while (p1 != l1 && is_idchar[*p1])
8108 xbuf[totlen++] = *p1++;
8109 /* Delete any no-reexpansion marker that follows
8110 an identifier at the beginning of the argument
8111 if the argument is concatenated with what precedes it. */
8112 if (p1[0] == '\n' && p1[1] == '-')
8113 p1 += 2;
8114 } else if (!traditional) {
8115 /* Ordinary expanded use of the argument.
8116 Put in newline-space markers to prevent token pasting. */
8117 xbuf[totlen++] = '\n';
8118 xbuf[totlen++] = ' ';
8120 if (ap->raw_after) {
8121 /* Arg is concatenated after: delete trailing whitespace,
8122 whitespace markers, and no-reexpansion markers. */
8123 while (p1 != l1) {
8124 if (is_space[l1[-1]]) l1--;
8125 else if (l1[-1] == '-') {
8126 U_CHAR *p2 = l1 - 1;
8127 /* If a `-' is preceded by an odd number of newlines then it
8128 and the last newline are a no-reexpansion marker. */
8129 while (p2 != p1 && p2[-1] == '\n') p2--;
8130 if ((l1 - 1 - p2) & 1) {
8131 l1 -= 2;
8133 else break;
8135 else break;
8139 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8140 totlen += l1 - p1;
8141 if (!traditional && !ap->raw_after) {
8142 /* Ordinary expanded use of the argument.
8143 Put in newline-space markers to prevent token pasting. */
8144 xbuf[totlen++] = '\n';
8145 xbuf[totlen++] = ' ';
8147 } else {
8148 /* Ordinary expanded use of the argument.
8149 Put in newline-space markers to prevent token pasting. */
8150 if (!traditional) {
8151 xbuf[totlen++] = '\n';
8152 xbuf[totlen++] = ' ';
8154 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8155 arg->expand_length);
8156 totlen += arg->expand_length;
8157 if (!traditional) {
8158 xbuf[totlen++] = '\n';
8159 xbuf[totlen++] = ' ';
8161 /* If a macro argument with newlines is used multiple times,
8162 then only expand the newlines once. This avoids creating output
8163 lines which don't correspond to any input line, which confuses
8164 gdb and gcov. */
8165 if (arg->use_count > 1 && arg->newlines > 0) {
8166 /* Don't bother doing change_newlines for subsequent
8167 uses of arg. */
8168 arg->use_count = 1;
8169 arg->expand_length
8170 = change_newlines (arg->expanded, arg->expand_length);
8174 if (totlen > xbuf_len)
8175 abort ();
8178 /* if there is anything left of the definition
8179 after handling the arg list, copy that in too. */
8181 for (i = offset; i < defn->length; i++) {
8182 /* if we've reached the end of the macro */
8183 if (exp[i] == ')')
8184 rest_zero = 0;
8185 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8186 && last_ap->raw_after))
8187 xbuf[totlen++] = exp[i];
8190 xbuf[totlen] = 0;
8191 xbuf_len = totlen;
8193 for (i = 0; i < nargs; i++) {
8194 if (args[i].free1 != 0)
8195 free (args[i].free1);
8196 if (args[i].free2 != 0)
8197 free (args[i].free2);
8200 } else {
8201 xbuf = defn->expansion;
8202 xbuf_len = defn->length;
8205 /* Now put the expansion on the input stack
8206 so our caller will commence reading from it. */
8208 register FILE_BUF *ip2;
8210 ip2 = &instack[++indepth];
8212 ip2->fname = 0;
8213 ip2->nominal_fname = 0;
8214 /* This may not be exactly correct, but will give much better error
8215 messages for nested macro calls than using a line number of zero. */
8216 ip2->lineno = start_line;
8217 ip2->buf = xbuf;
8218 ip2->length = xbuf_len;
8219 ip2->bufp = xbuf;
8220 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8221 ip2->macro = hp;
8222 ip2->if_stack = if_stack;
8223 ip2->system_header_p = 0;
8225 /* Recursive macro use sometimes works traditionally.
8226 #define foo(x,y) bar (x (y,0), y)
8227 foo (foo, baz) */
8229 if (!traditional)
8230 hp->type = T_DISABLED;
8235 * Parse a macro argument and store the info on it into *ARGPTR.
8236 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8237 * Return nonzero to indicate a syntax error.
8240 static char *
8241 macarg (argptr, rest_args)
8242 register struct argdata *argptr;
8243 int rest_args;
8245 FILE_BUF *ip = &instack[indepth];
8246 int paren = 0;
8247 int newlines = 0;
8248 int comments = 0;
8250 /* Try to parse as much of the argument as exists at this
8251 input stack level. */
8252 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8253 &paren, &newlines, &comments, rest_args);
8255 /* If we find the end of the argument at this level,
8256 set up *ARGPTR to point at it in the input stack. */
8257 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8258 && bp != ip->buf + ip->length) {
8259 if (argptr != 0) {
8260 argptr->raw = ip->bufp;
8261 argptr->raw_length = bp - ip->bufp;
8262 argptr->newlines = newlines;
8264 ip->bufp = bp;
8265 } else {
8266 /* This input stack level ends before the macro argument does.
8267 We must pop levels and keep parsing.
8268 Therefore, we must allocate a temporary buffer and copy
8269 the macro argument into it. */
8270 int bufsize = bp - ip->bufp;
8271 int extra = newlines;
8272 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8273 int final_start = 0;
8275 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8276 ip->bufp = bp;
8277 ip->lineno += newlines;
8279 while (bp == ip->buf + ip->length) {
8280 if (instack[indepth].macro == 0) {
8281 free (buffer);
8282 return "unterminated macro call";
8284 ip->macro->type = T_MACRO;
8285 if (ip->free_ptr)
8286 free (ip->free_ptr);
8287 ip = &instack[--indepth];
8288 newlines = 0;
8289 comments = 0;
8290 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8291 &newlines, &comments, rest_args);
8292 final_start = bufsize;
8293 bufsize += bp - ip->bufp;
8294 extra += newlines;
8295 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8296 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8297 bp - ip->bufp);
8298 ip->bufp = bp;
8299 ip->lineno += newlines;
8302 /* Now, if arg is actually wanted, record its raw form,
8303 discarding comments and duplicating newlines in whatever
8304 part of it did not come from a macro expansion.
8305 EXTRA space has been preallocated for duplicating the newlines.
8306 FINAL_START is the index of the start of that part. */
8307 if (argptr != 0) {
8308 argptr->raw = buffer;
8309 argptr->raw_length = bufsize;
8310 argptr->free1 = buffer;
8311 argptr->newlines = newlines;
8312 argptr->comments = comments;
8313 if ((newlines || comments) && ip->fname != 0)
8314 argptr->raw_length
8315 = final_start +
8316 discard_comments (argptr->raw + final_start,
8317 argptr->raw_length - final_start,
8318 newlines);
8319 argptr->raw[argptr->raw_length] = 0;
8320 if (argptr->raw_length > bufsize + extra)
8321 abort ();
8325 /* If we are not discarding this argument,
8326 macroexpand it and compute its length as stringified.
8327 All this info goes into *ARGPTR. */
8329 if (argptr != 0) {
8330 register U_CHAR *buf, *lim;
8331 register int totlen;
8333 buf = argptr->raw;
8334 lim = buf + argptr->raw_length;
8336 while (buf != lim && is_space[*buf])
8337 buf++;
8338 while (buf != lim && is_space[lim[-1]])
8339 lim--;
8340 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8341 while (buf != lim) {
8342 register U_CHAR c = *buf++;
8343 totlen++;
8344 /* Internal sequences of whitespace are replaced by one space
8345 in most cases, but not always. So count all the whitespace
8346 in case we need to keep it all. */
8347 #if 0
8348 if (is_space[c])
8349 SKIP_ALL_WHITE_SPACE (buf);
8350 else
8351 #endif
8352 if (c == '\"' || c == '\\') /* escape these chars */
8353 totlen++;
8354 else if (!isprint (c))
8355 totlen += 3;
8357 argptr->stringified_length = totlen;
8359 return 0;
8362 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8363 counting parens in *DEPTHPTR,
8364 and return if reach LIMIT
8365 or before a `)' that would make *DEPTHPTR negative
8366 or before a comma when *DEPTHPTR is zero.
8367 Single and double quotes are matched and termination
8368 is inhibited within them. Comments also inhibit it.
8369 Value returned is pointer to stopping place.
8371 Increment *NEWLINES each time a newline is passed.
8372 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8373 Set *COMMENTS to 1 if a comment is seen. */
8375 static U_CHAR *
8376 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8377 U_CHAR *start;
8378 register U_CHAR *limit;
8379 int *depthptr, *newlines, *comments;
8380 int rest_args;
8382 register U_CHAR *bp = start;
8384 while (bp < limit) {
8385 switch (*bp) {
8386 case '(':
8387 (*depthptr)++;
8388 break;
8389 case ')':
8390 if (--(*depthptr) < 0)
8391 return bp;
8392 break;
8393 case '\\':
8394 /* Traditionally, backslash makes following char not special. */
8395 if (bp + 1 < limit && traditional)
8397 bp++;
8398 /* But count source lines anyway. */
8399 if (*bp == '\n')
8400 ++*newlines;
8402 break;
8403 case '\n':
8404 ++*newlines;
8405 break;
8406 case '/':
8407 if (bp[1] == '\\' && bp[2] == '\n')
8408 newline_fix (bp + 1);
8409 if (cplusplus_comments && bp[1] == '/') {
8410 *comments = 1;
8411 bp += 2;
8412 while (bp < limit && (*bp != '\n' || bp[-1] == '\\')) {
8413 if (*bp == '\n') ++*newlines;
8414 bp++;
8416 /* Now count the newline that we are about to skip. */
8417 ++*newlines;
8418 break;
8420 if (bp[1] != '*' || bp + 1 >= limit)
8421 break;
8422 *comments = 1;
8423 bp += 2;
8424 while (bp + 1 < limit) {
8425 if (bp[0] == '*'
8426 && bp[1] == '\\' && bp[2] == '\n')
8427 newline_fix (bp + 1);
8428 if (bp[0] == '*' && bp[1] == '/')
8429 break;
8430 if (*bp == '\n') ++*newlines;
8431 bp++;
8433 break;
8434 case '\'':
8435 case '\"':
8437 int quotec;
8438 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8439 if (*bp == '\\') {
8440 bp++;
8441 if (*bp == '\n')
8442 ++*newlines;
8443 while (*bp == '\\' && bp[1] == '\n') {
8444 bp += 2;
8446 } else if (*bp == '\n') {
8447 ++*newlines;
8448 if (quotec == '\'')
8449 break;
8453 break;
8454 case ',':
8455 /* if we've returned to lowest level and we aren't absorbing all args */
8456 if ((*depthptr) == 0 && rest_args == 0)
8457 return bp;
8458 break;
8460 bp++;
8463 return bp;
8466 /* Discard comments and duplicate newlines
8467 in the string of length LENGTH at START,
8468 except inside of string constants.
8469 The string is copied into itself with its beginning staying fixed.
8471 NEWLINES is the number of newlines that must be duplicated.
8472 We assume that that much extra space is available past the end
8473 of the string. */
8475 static int
8476 discard_comments (start, length, newlines)
8477 U_CHAR *start;
8478 int length;
8479 int newlines;
8481 register U_CHAR *ibp;
8482 register U_CHAR *obp;
8483 register U_CHAR *limit;
8484 register int c;
8486 /* If we have newlines to duplicate, copy everything
8487 that many characters up. Then, in the second part,
8488 we will have room to insert the newlines
8489 while copying down.
8490 NEWLINES may actually be too large, because it counts
8491 newlines in string constants, and we don't duplicate those.
8492 But that does no harm. */
8493 if (newlines > 0) {
8494 ibp = start + length;
8495 obp = ibp + newlines;
8496 limit = start;
8497 while (limit != ibp)
8498 *--obp = *--ibp;
8501 ibp = start + newlines;
8502 limit = start + length + newlines;
8503 obp = start;
8505 while (ibp < limit) {
8506 *obp++ = c = *ibp++;
8507 switch (c) {
8508 case '\n':
8509 /* Duplicate the newline. */
8510 *obp++ = '\n';
8511 break;
8513 case '\\':
8514 if (*ibp == '\n') {
8515 obp--;
8516 ibp++;
8518 break;
8520 case '/':
8521 if (*ibp == '\\' && ibp[1] == '\n')
8522 newline_fix (ibp);
8523 /* Delete any comment. */
8524 if (cplusplus_comments && ibp[0] == '/') {
8525 /* Comments are equivalent to spaces. */
8526 obp[-1] = ' ';
8527 ibp++;
8528 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8529 ibp++;
8530 break;
8532 if (ibp[0] != '*' || ibp + 1 >= limit)
8533 break;
8534 /* Comments are equivalent to spaces.
8535 For -traditional, a comment is equivalent to nothing. */
8536 if (traditional)
8537 obp--;
8538 else
8539 obp[-1] = ' ';
8540 ibp++;
8541 while (ibp + 1 < limit) {
8542 if (ibp[0] == '*'
8543 && ibp[1] == '\\' && ibp[2] == '\n')
8544 newline_fix (ibp + 1);
8545 if (ibp[0] == '*' && ibp[1] == '/')
8546 break;
8547 ibp++;
8549 ibp += 2;
8550 break;
8552 case '\'':
8553 case '\"':
8554 /* Notice and skip strings, so that we don't
8555 think that comments start inside them,
8556 and so we don't duplicate newlines in them. */
8558 int quotec = c;
8559 while (ibp < limit) {
8560 *obp++ = c = *ibp++;
8561 if (c == quotec)
8562 break;
8563 if (c == '\n' && quotec == '\'')
8564 break;
8565 if (c == '\\' && ibp < limit) {
8566 while (*ibp == '\\' && ibp[1] == '\n')
8567 ibp += 2;
8568 *obp++ = *ibp++;
8572 break;
8576 return obp - start;
8579 /* Turn newlines to spaces in the string of length LENGTH at START,
8580 except inside of string constants.
8581 The string is copied into itself with its beginning staying fixed. */
8583 static int
8584 change_newlines (start, length)
8585 U_CHAR *start;
8586 int length;
8588 register U_CHAR *ibp;
8589 register U_CHAR *obp;
8590 register U_CHAR *limit;
8591 register int c;
8593 ibp = start;
8594 limit = start + length;
8595 obp = start;
8597 while (ibp < limit) {
8598 *obp++ = c = *ibp++;
8599 switch (c) {
8600 case '\n':
8601 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8602 string. Skip past the newline and its duplicate.
8603 Put a space in the output. */
8604 if (*ibp == '\n')
8606 ibp++;
8607 obp--;
8608 *obp++ = ' ';
8610 break;
8612 case '\'':
8613 case '\"':
8614 /* Notice and skip strings, so that we don't delete newlines in them. */
8616 int quotec = c;
8617 while (ibp < limit) {
8618 *obp++ = c = *ibp++;
8619 if (c == quotec)
8620 break;
8621 if (c == '\n' && quotec == '\'')
8622 break;
8625 break;
8629 return obp - start;
8633 * my_strerror - return the descriptive text associated with an `errno' code.
8636 char *
8637 my_strerror (errnum)
8638 int errnum;
8640 char *result;
8642 #ifndef VMS
8643 #ifndef HAVE_STRERROR
8644 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8645 #else
8646 result = strerror (errnum);
8647 #endif
8648 #else /* VMS */
8649 /* VAXCRTL's strerror() takes an optional second argument, which only
8650 matters when the first argument is EVMSERR. However, it's simplest
8651 just to pass it unconditionally. `vaxc$errno' is declared in
8652 <errno.h>, and maintained by the library in parallel with `errno'.
8653 We assume that caller's `errnum' either matches the last setting of
8654 `errno' by the library or else does not have the value `EVMSERR'. */
8656 result = strerror (errnum, vaxc$errno);
8657 #endif
8659 if (!result)
8660 result = "undocumented I/O error";
8662 return result;
8666 * error - print error message and increment count of errors.
8669 void
8670 error (msg, arg1, arg2, arg3)
8671 char *msg;
8672 char *arg1, *arg2, *arg3;
8674 int i;
8675 FILE_BUF *ip = NULL;
8677 print_containing_files ();
8679 for (i = indepth; i >= 0; i--)
8680 if (instack[i].fname != NULL) {
8681 ip = &instack[i];
8682 break;
8685 if (ip != NULL)
8686 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8687 fprintf (stderr, msg, arg1, arg2, arg3);
8688 fprintf (stderr, "\n");
8689 errors++;
8692 /* Error including a message from `errno'. */
8694 static void
8695 error_from_errno (name)
8696 char *name;
8698 int i;
8699 FILE_BUF *ip = NULL;
8701 print_containing_files ();
8703 for (i = indepth; i >= 0; i--)
8704 if (instack[i].fname != NULL) {
8705 ip = &instack[i];
8706 break;
8709 if (ip != NULL)
8710 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8712 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8714 errors++;
8717 /* Print error message but don't count it. */
8719 void
8720 warning (msg, arg1, arg2, arg3)
8721 char *msg;
8722 char *arg1, *arg2, *arg3;
8724 int i;
8725 FILE_BUF *ip = NULL;
8727 if (inhibit_warnings)
8728 return;
8730 if (warnings_are_errors)
8731 errors++;
8733 print_containing_files ();
8735 for (i = indepth; i >= 0; i--)
8736 if (instack[i].fname != NULL) {
8737 ip = &instack[i];
8738 break;
8741 if (ip != NULL)
8742 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8743 fprintf (stderr, "warning: ");
8744 fprintf (stderr, msg, arg1, arg2, arg3);
8745 fprintf (stderr, "\n");
8748 static void
8749 error_with_line (line, msg, arg1, arg2, arg3)
8750 int line;
8751 char *msg;
8752 char *arg1, *arg2, *arg3;
8754 int i;
8755 FILE_BUF *ip = NULL;
8757 print_containing_files ();
8759 for (i = indepth; i >= 0; i--)
8760 if (instack[i].fname != NULL) {
8761 ip = &instack[i];
8762 break;
8765 if (ip != NULL)
8766 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8767 fprintf (stderr, msg, arg1, arg2, arg3);
8768 fprintf (stderr, "\n");
8769 errors++;
8772 static void
8773 warning_with_line (line, msg, arg1, arg2, arg3)
8774 int line;
8775 char *msg;
8776 char *arg1, *arg2, *arg3;
8778 int i;
8779 FILE_BUF *ip = NULL;
8781 if (inhibit_warnings)
8782 return;
8784 if (warnings_are_errors)
8785 errors++;
8787 print_containing_files ();
8789 for (i = indepth; i >= 0; i--)
8790 if (instack[i].fname != NULL) {
8791 ip = &instack[i];
8792 break;
8795 if (ip != NULL)
8796 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8797 fprintf (stderr, "warning: ");
8798 fprintf (stderr, msg, arg1, arg2, arg3);
8799 fprintf (stderr, "\n");
8802 /* print an error message and maybe count it. */
8804 void
8805 pedwarn (msg, arg1, arg2, arg3)
8806 char *msg;
8807 char *arg1, *arg2, *arg3;
8809 if (pedantic_errors)
8810 error (msg, arg1, arg2, arg3);
8811 else
8812 warning (msg, arg1, arg2, arg3);
8815 void
8816 pedwarn_with_line (line, msg, arg1, arg2, arg3)
8817 int line;
8818 char *msg;
8819 char *arg1, *arg2, *arg3;
8821 if (pedantic_errors)
8822 error_with_line (line, msg, arg1, arg2, arg3);
8823 else
8824 warning_with_line (line, msg, arg1, arg2, arg3);
8827 /* Report a warning (or an error if pedantic_errors)
8828 giving specified file name and line number, not current. */
8830 static void
8831 pedwarn_with_file_and_line (file, line, msg, arg1, arg2, arg3)
8832 char *file;
8833 int line;
8834 char *msg;
8835 char *arg1, *arg2, *arg3;
8837 if (!pedantic_errors && inhibit_warnings)
8838 return;
8839 if (file != NULL)
8840 fprintf (stderr, "%s:%d: ", file, line);
8841 if (pedantic_errors)
8842 errors++;
8843 if (!pedantic_errors)
8844 fprintf (stderr, "warning: ");
8845 fprintf (stderr, msg, arg1, arg2, arg3);
8846 fprintf (stderr, "\n");
8849 /* Print the file names and line numbers of the #include
8850 commands which led to the current file. */
8852 static void
8853 print_containing_files ()
8855 FILE_BUF *ip = NULL;
8856 int i;
8857 int first = 1;
8859 /* If stack of files hasn't changed since we last printed
8860 this info, don't repeat it. */
8861 if (last_error_tick == input_file_stack_tick)
8862 return;
8864 for (i = indepth; i >= 0; i--)
8865 if (instack[i].fname != NULL) {
8866 ip = &instack[i];
8867 break;
8870 /* Give up if we don't find a source file. */
8871 if (ip == NULL)
8872 return;
8874 /* Find the other, outer source files. */
8875 for (i--; i >= 0; i--)
8876 if (instack[i].fname != NULL) {
8877 ip = &instack[i];
8878 if (first) {
8879 first = 0;
8880 fprintf (stderr, "In file included");
8881 } else {
8882 fprintf (stderr, ",\n ");
8885 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
8887 if (! first)
8888 fprintf (stderr, ":\n");
8890 /* Record we have printed the status as of this time. */
8891 last_error_tick = input_file_stack_tick;
8894 /* Return the line at which an error occurred.
8895 The error is not necessarily associated with the current spot
8896 in the input stack, so LINE says where. LINE will have been
8897 copied from ip->lineno for the current input level.
8898 If the current level is for a file, we return LINE.
8899 But if the current level is not for a file, LINE is meaningless.
8900 In that case, we return the lineno of the innermost file. */
8902 static int
8903 line_for_error (line)
8904 int line;
8906 int i;
8907 int line1 = line;
8909 for (i = indepth; i >= 0; ) {
8910 if (instack[i].fname != 0)
8911 return line1;
8912 i--;
8913 if (i < 0)
8914 return 0;
8915 line1 = instack[i].lineno;
8917 abort ();
8918 /*NOTREACHED*/
8919 return 0;
8923 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
8925 * As things stand, nothing is ever placed in the output buffer to be
8926 * removed again except when it's KNOWN to be part of an identifier,
8927 * so flushing and moving down everything left, instead of expanding,
8928 * should work ok.
8931 /* You might think void was cleaner for the return type,
8932 but that would get type mismatch in check_expand in strict ANSI. */
8933 static int
8934 grow_outbuf (obuf, needed)
8935 register FILE_BUF *obuf;
8936 register int needed;
8938 register U_CHAR *p;
8939 int minsize;
8941 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
8942 return 0;
8944 /* Make it at least twice as big as it is now. */
8945 obuf->length *= 2;
8946 /* Make it have at least 150% of the free space we will need. */
8947 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
8948 if (minsize > obuf->length)
8949 obuf->length = minsize;
8951 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
8952 memory_full ();
8954 obuf->bufp = p + (obuf->bufp - obuf->buf);
8955 obuf->buf = p;
8957 return 0;
8960 /* Symbol table for macro names and special symbols */
8963 * install a name in the main hash table, even if it is already there.
8964 * name stops with first non alphanumeric, except leading '#'.
8965 * caller must check against redefinition if that is desired.
8966 * delete_macro () removes things installed by install () in fifo order.
8967 * this is important because of the `defined' special symbol used
8968 * in #if, and also if pushdef/popdef directives are ever implemented.
8970 * If LEN is >= 0, it is the length of the name.
8971 * Otherwise, compute the length by scanning the entire name.
8973 * If HASH is >= 0, it is the precomputed hash code.
8974 * Otherwise, compute the hash code.
8976 static HASHNODE *
8977 install (name, len, type, value, hash)
8978 U_CHAR *name;
8979 int len;
8980 enum node_type type;
8981 char *value;
8982 int hash;
8984 register HASHNODE *hp;
8985 register int i, bucket;
8986 register U_CHAR *p, *q;
8988 if (len < 0) {
8989 p = name;
8990 while (is_idchar[*p])
8991 p++;
8992 len = p - name;
8995 if (hash < 0)
8996 hash = hashf (name, len, HASHSIZE);
8998 i = sizeof (HASHNODE) + len + 1;
8999 hp = (HASHNODE *) xmalloc (i);
9000 bucket = hash;
9001 hp->bucket_hdr = &hashtab[bucket];
9002 hp->next = hashtab[bucket];
9003 hashtab[bucket] = hp;
9004 hp->prev = NULL;
9005 if (hp->next != NULL)
9006 hp->next->prev = hp;
9007 hp->type = type;
9008 hp->length = len;
9009 hp->value.cpval = value;
9010 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9011 p = hp->name;
9012 q = name;
9013 for (i = 0; i < len; i++)
9014 *p++ = *q++;
9015 hp->name[len] = 0;
9016 return hp;
9020 * find the most recent hash node for name name (ending with first
9021 * non-identifier char) installed by install
9023 * If LEN is >= 0, it is the length of the name.
9024 * Otherwise, compute the length by scanning the entire name.
9026 * If HASH is >= 0, it is the precomputed hash code.
9027 * Otherwise, compute the hash code.
9029 HASHNODE *
9030 lookup (name, len, hash)
9031 U_CHAR *name;
9032 int len;
9033 int hash;
9035 register U_CHAR *bp;
9036 register HASHNODE *bucket;
9038 if (len < 0) {
9039 for (bp = name; is_idchar[*bp]; bp++) ;
9040 len = bp - name;
9043 if (hash < 0)
9044 hash = hashf (name, len, HASHSIZE);
9046 bucket = hashtab[hash];
9047 while (bucket) {
9048 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
9049 return bucket;
9050 bucket = bucket->next;
9052 return NULL;
9056 * Delete a hash node. Some weirdness to free junk from macros.
9057 * More such weirdness will have to be added if you define more hash
9058 * types that need it.
9061 /* Note that the DEFINITION of a macro is removed from the hash table
9062 but its storage is not freed. This would be a storage leak
9063 except that it is not reasonable to keep undefining and redefining
9064 large numbers of macros many times.
9065 In any case, this is necessary, because a macro can be #undef'd
9066 in the middle of reading the arguments to a call to it.
9067 If #undef freed the DEFINITION, that would crash. */
9069 static void
9070 delete_macro (hp)
9071 HASHNODE *hp;
9074 if (hp->prev != NULL)
9075 hp->prev->next = hp->next;
9076 if (hp->next != NULL)
9077 hp->next->prev = hp->prev;
9079 /* make sure that the bucket chain header that
9080 the deleted guy was on points to the right thing afterwards. */
9081 if (hp == *hp->bucket_hdr)
9082 *hp->bucket_hdr = hp->next;
9084 #if 0
9085 if (hp->type == T_MACRO) {
9086 DEFINITION *d = hp->value.defn;
9087 struct reflist *ap, *nextap;
9089 for (ap = d->pattern; ap != NULL; ap = nextap) {
9090 nextap = ap->next;
9091 free (ap);
9093 free (d);
9095 #endif
9096 free (hp);
9100 * return hash function on name. must be compatible with the one
9101 * computed a step at a time, elsewhere
9103 static int
9104 hashf (name, len, hashsize)
9105 register U_CHAR *name;
9106 register int len;
9107 int hashsize;
9109 register int r = 0;
9111 while (len--)
9112 r = HASHSTEP (r, *name++);
9114 return MAKE_POS (r) % hashsize;
9118 /* Dump the definition of a single macro HP to OF. */
9119 static void
9120 dump_single_macro (hp, of)
9121 register HASHNODE *hp;
9122 FILE *of;
9124 register DEFINITION *defn = hp->value.defn;
9125 struct reflist *ap;
9126 int offset;
9127 int concat;
9130 /* Print the definition of the macro HP. */
9132 fprintf (of, "#define %s", hp->name);
9134 if (defn->nargs >= 0) {
9135 int i;
9137 fprintf (of, "(");
9138 for (i = 0; i < defn->nargs; i++) {
9139 dump_arg_n (defn, i, of);
9140 if (i + 1 < defn->nargs)
9141 fprintf (of, ", ");
9143 fprintf (of, ")");
9146 fprintf (of, " ");
9148 offset = 0;
9149 concat = 0;
9150 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9151 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9152 offset += ap->nchars;
9153 if (!traditional) {
9154 if (ap->nchars != 0)
9155 concat = 0;
9156 if (ap->stringify)
9157 fprintf (of, ap->stringify == '#' ? " #" : " %:");
9158 if (ap->raw_before && !concat)
9159 fprintf (of, ap->raw_before == '#' ? " ## " : " %:%: ");
9160 concat = 0;
9162 dump_arg_n (defn, ap->argno, of);
9163 if (!traditional && ap->raw_after) {
9164 fprintf (of, ap->raw_after == '#' ? " ## " : " %:%: ");
9165 concat = 1;
9168 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9169 fprintf (of, "\n");
9172 /* Dump all macro definitions as #defines to stdout. */
9174 static void
9175 dump_all_macros ()
9177 int bucket;
9179 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9180 register HASHNODE *hp;
9182 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9183 if (hp->type == T_MACRO)
9184 dump_single_macro (hp, stdout);
9189 /* Output to OF a substring of a macro definition.
9190 BASE is the beginning of the definition.
9191 Output characters START thru LENGTH.
9192 Unless traditional, discard newlines outside of strings, thus
9193 converting funny-space markers to ordinary spaces. */
9195 static void
9196 dump_defn_1 (base, start, length, of)
9197 U_CHAR *base;
9198 int start;
9199 int length;
9200 FILE *of;
9202 U_CHAR *p = base + start;
9203 U_CHAR *limit = base + start + length;
9205 if (traditional)
9206 fwrite (p, sizeof (*p), length, of);
9207 else {
9208 while (p < limit) {
9209 if (*p == '\"' || *p =='\'') {
9210 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9211 NULL_PTR, NULL_PTR);
9212 fwrite (p, sizeof (*p), p1 - p, of);
9213 p = p1;
9214 } else {
9215 if (*p != '\n')
9216 putc (*p, of);
9217 p++;
9223 /* Print the name of argument number ARGNUM of macro definition DEFN
9224 to OF.
9225 Recall that DEFN->args.argnames contains all the arg names
9226 concatenated in reverse order with comma-space in between. */
9228 static void
9229 dump_arg_n (defn, argnum, of)
9230 DEFINITION *defn;
9231 int argnum;
9232 FILE *of;
9234 register U_CHAR *p = defn->args.argnames;
9235 while (argnum + 1 < defn->nargs) {
9236 p = (U_CHAR *) index (p, ' ') + 1;
9237 argnum++;
9240 while (*p && *p != ',') {
9241 putc (*p, of);
9242 p++;
9246 /* Initialize syntactic classifications of characters. */
9248 static void
9249 initialize_char_syntax ()
9251 register int i;
9254 * Set up is_idchar and is_idstart tables. These should be
9255 * faster than saying (is_alpha (c) || c == '_'), etc.
9256 * Set up these things before calling any routines tthat
9257 * refer to them.
9259 for (i = 'a'; i <= 'z'; i++) {
9260 is_idchar[i - 'a' + 'A'] = 1;
9261 is_idchar[i] = 1;
9262 is_idstart[i - 'a' + 'A'] = 1;
9263 is_idstart[i] = 1;
9265 for (i = '0'; i <= '9'; i++)
9266 is_idchar[i] = 1;
9267 is_idchar['_'] = 1;
9268 is_idstart['_'] = 1;
9269 is_idchar['$'] = dollars_in_ident;
9270 is_idstart['$'] = dollars_in_ident;
9272 /* horizontal space table */
9273 is_hor_space[' '] = 1;
9274 is_hor_space['\t'] = 1;
9275 is_hor_space['\v'] = 1;
9276 is_hor_space['\f'] = 1;
9277 is_hor_space['\r'] = 1;
9279 is_space[' '] = 1;
9280 is_space['\t'] = 1;
9281 is_space['\v'] = 1;
9282 is_space['\f'] = 1;
9283 is_space['\n'] = 1;
9284 is_space['\r'] = 1;
9286 char_name['\v'] = "vertical tab";
9287 char_name['\f'] = "formfeed";
9288 char_name['\r'] = "carriage return";
9291 /* Initialize the built-in macros. */
9293 static void
9294 initialize_builtins (inp, outp)
9295 FILE_BUF *inp;
9296 FILE_BUF *outp;
9298 install ("__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9299 install ("__DATE__", -1, T_DATE, NULL_PTR, -1);
9300 install ("__FILE__", -1, T_FILE, NULL_PTR, -1);
9301 install ("__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9302 install ("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9303 install ("__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9304 #ifndef NO_BUILTIN_SIZE_TYPE
9305 install ("__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9306 #endif
9307 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9308 install ("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9309 #endif
9310 install ("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9311 install ("__USER_LABEL_PREFIX__",-1,T_USER_LABEL_PREFIX_TYPE, NULL_PTR, -1);
9312 install ("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, NULL_PTR, -1);
9313 install ("__TIME__", -1, T_TIME, NULL_PTR, -1);
9314 if (!traditional) {
9315 install ("__STDC__", -1, T_CONST, "1", -1);
9316 install ("__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9318 if (objc)
9319 install ("__OBJC__", -1, T_CONST, "1", -1);
9320 /* This is supplied using a -D by the compiler driver
9321 so that it is present only when truly compiling with GNU C. */
9322 /* install ("__GNUC__", -1, T_CONST, "2", -1); */
9324 if (debug_output)
9326 char directive[2048];
9327 register struct directive *dp = &directive_table[0];
9328 struct tm *timebuf = timestamp ();
9330 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9331 instack[0].nominal_fname);
9332 output_line_command (inp, outp, 0, same_file);
9333 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9335 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9336 output_line_command (inp, outp, 0, same_file);
9337 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9339 #ifndef NO_BUILTIN_SIZE_TYPE
9340 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9341 output_line_command (inp, outp, 0, same_file);
9342 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9343 #endif
9345 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9346 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9347 output_line_command (inp, outp, 0, same_file);
9348 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9349 #endif
9351 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9352 output_line_command (inp, outp, 0, same_file);
9353 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9355 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9356 monthnames[timebuf->tm_mon],
9357 timebuf->tm_mday, timebuf->tm_year + 1900);
9358 output_line_command (inp, outp, 0, same_file);
9359 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9361 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9362 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9363 output_line_command (inp, outp, 0, same_file);
9364 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9366 if (!traditional)
9368 sprintf (directive, " __STDC__ 1");
9369 output_line_command (inp, outp, 0, same_file);
9370 pass_thru_directive (directive, &directive[strlen (directive)],
9371 outp, dp);
9373 if (objc)
9375 sprintf (directive, " __OBJC__ 1");
9376 output_line_command (inp, outp, 0, same_file);
9377 pass_thru_directive (directive, &directive[strlen (directive)],
9378 outp, dp);
9384 * process a given definition string, for initialization
9385 * If STR is just an identifier, define it with value 1.
9386 * If STR has anything after the identifier, then it should
9387 * be identifier=definition.
9390 static void
9391 make_definition (str, op)
9392 U_CHAR *str;
9393 FILE_BUF *op;
9395 FILE_BUF *ip;
9396 struct directive *kt;
9397 U_CHAR *buf, *p;
9399 buf = str;
9400 p = str;
9401 if (!is_idstart[*p]) {
9402 error ("malformed option `-D %s'", str);
9403 return;
9405 while (is_idchar[*++p])
9407 if (*p == '(') {
9408 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9410 if (*p++ != ')')
9411 p = str; /* Error */
9413 if (*p == 0) {
9414 buf = (U_CHAR *) alloca (p - buf + 4);
9415 strcpy ((char *)buf, str);
9416 strcat ((char *)buf, " 1");
9417 } else if (*p != '=') {
9418 error ("malformed option `-D %s'", str);
9419 return;
9420 } else {
9421 U_CHAR *q;
9422 /* Copy the entire option so we can modify it. */
9423 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9424 strncpy (buf, str, p - str);
9425 /* Change the = to a space. */
9426 buf[p - str] = ' ';
9427 /* Scan for any backslash-newline and remove it. */
9428 p++;
9429 q = &buf[p - str];
9430 while (*p) {
9431 if (*p == '\"' || *p == '\'') {
9432 int unterminated = 0;
9433 U_CHAR *p1 = skip_quoted_string (p, p + strlen (p), 0,
9434 NULL_PTR, NULL_PTR, &unterminated);
9435 if (unterminated)
9436 return;
9437 while (p != p1)
9438 if (*p == '\\' && p[1] == '\n')
9439 p += 2;
9440 else
9441 *q++ = *p++;
9442 } else if (*p == '\\' && p[1] == '\n')
9443 p += 2;
9444 /* Change newline chars into newline-markers. */
9445 else if (*p == '\n')
9447 *q++ = '\n';
9448 *q++ = '\n';
9449 p++;
9451 else
9452 *q++ = *p++;
9454 *q = 0;
9457 ip = &instack[++indepth];
9458 ip->nominal_fname = ip->fname = "*Initialization*";
9460 ip->buf = ip->bufp = buf;
9461 ip->length = strlen (buf);
9462 ip->lineno = 1;
9463 ip->macro = 0;
9464 ip->free_ptr = 0;
9465 ip->if_stack = if_stack;
9466 ip->system_header_p = 0;
9468 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9471 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9472 do_define (buf, buf + strlen (buf), NULL_PTR, kt);
9473 --indepth;
9476 /* JF, this does the work for the -U option */
9478 static void
9479 make_undef (str, op)
9480 U_CHAR *str;
9481 FILE_BUF *op;
9483 FILE_BUF *ip;
9484 struct directive *kt;
9486 ip = &instack[++indepth];
9487 ip->nominal_fname = ip->fname = "*undef*";
9489 ip->buf = ip->bufp = str;
9490 ip->length = strlen (str);
9491 ip->lineno = 1;
9492 ip->macro = 0;
9493 ip->free_ptr = 0;
9494 ip->if_stack = if_stack;
9495 ip->system_header_p = 0;
9497 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9500 do_undef (str, str + strlen (str), op, kt);
9501 --indepth;
9504 /* Process the string STR as if it appeared as the body of a #assert.
9505 OPTION is the option name for which STR was the argument. */
9507 static void
9508 make_assertion (option, str)
9509 char *option;
9510 U_CHAR *str;
9512 FILE_BUF *ip;
9513 struct directive *kt;
9514 U_CHAR *buf, *p, *q;
9516 /* Copy the entire option so we can modify it. */
9517 buf = (U_CHAR *) alloca (strlen (str) + 1);
9518 strcpy ((char *) buf, str);
9519 /* Scan for any backslash-newline and remove it. */
9520 p = q = buf;
9521 while (*p) {
9522 if (*p == '\\' && p[1] == '\n')
9523 p += 2;
9524 else
9525 *q++ = *p++;
9527 *q = 0;
9529 p = buf;
9530 if (!is_idstart[*p]) {
9531 error ("malformed option `%s %s'", option, str);
9532 return;
9534 while (is_idchar[*++p])
9536 SKIP_WHITE_SPACE (p);
9537 if (! (*p == 0 || *p == '(')) {
9538 error ("malformed option `%s %s'", option, str);
9539 return;
9542 ip = &instack[++indepth];
9543 ip->nominal_fname = ip->fname = "*Initialization*";
9545 ip->buf = ip->bufp = buf;
9546 ip->length = strlen (buf);
9547 ip->lineno = 1;
9548 ip->macro = 0;
9549 ip->free_ptr = 0;
9550 ip->if_stack = if_stack;
9551 ip->system_header_p = 0;
9553 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9556 /* pass NULL as output ptr to do_define since we KNOW it never
9557 does any output.... */
9558 do_assert (buf, buf + strlen (buf) , NULL_PTR, kt);
9559 --indepth;
9562 /* Append a chain of `struct file_name_list's
9563 to the end of the main include chain.
9564 FIRST is the beginning of the chain to append, and LAST is the end. */
9566 static void
9567 append_include_chain (first, last)
9568 struct file_name_list *first, *last;
9570 struct file_name_list *dir;
9572 if (!first || !last)
9573 return;
9575 if (include == 0)
9576 include = first;
9577 else
9578 last_include->next = first;
9580 if (first_bracket_include == 0)
9581 first_bracket_include = first;
9583 for (dir = first; ; dir = dir->next) {
9584 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9585 if (len > max_include_len)
9586 max_include_len = len;
9587 if (dir == last)
9588 break;
9591 last->next = NULL;
9592 last_include = last;
9595 /* Add output to `deps_buffer' for the -M switch.
9596 STRING points to the text to be output.
9597 SPACER is ':' for targets, ' ' for dependencies, zero for text
9598 to be inserted literally. */
9600 static void
9601 deps_output (string, spacer)
9602 char *string;
9603 int spacer;
9605 int size = strlen (string);
9607 if (size == 0)
9608 return;
9610 #ifndef MAX_OUTPUT_COLUMNS
9611 #define MAX_OUTPUT_COLUMNS 72
9612 #endif
9613 if (spacer
9614 && deps_column > 0
9615 && (deps_column + size) > MAX_OUTPUT_COLUMNS)
9617 deps_output (" \\\n ", 0);
9618 deps_column = 0;
9621 if (deps_size + size + 8 > deps_allocated_size) {
9622 deps_allocated_size = (deps_size + size + 50) * 2;
9623 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
9625 if (spacer == ' ' && deps_column > 0)
9626 deps_buffer[deps_size++] = ' ';
9627 bcopy (string, &deps_buffer[deps_size], size);
9628 deps_size += size;
9629 deps_column += size;
9630 if (spacer == ':')
9631 deps_buffer[deps_size++] = ':';
9632 deps_buffer[deps_size] = 0;
9635 #if defined(USG) || defined(VMS)
9636 #ifndef BSTRING
9638 void
9639 bzero (b, length)
9640 register char *b;
9641 register unsigned length;
9643 while (length-- > 0)
9644 *b++ = 0;
9647 void
9648 bcopy (b1, b2, length)
9649 register char *b1;
9650 register char *b2;
9651 register unsigned length;
9653 while (length-- > 0)
9654 *b2++ = *b1++;
9658 bcmp (b1, b2, length) /* This could be a macro! */
9659 register char *b1;
9660 register char *b2;
9661 register unsigned length;
9663 while (length-- > 0)
9664 if (*b1++ != *b2++)
9665 return 1;
9667 return 0;
9669 #endif /* not BSTRING */
9670 #endif /* USG or VMS */
9673 static void
9674 fatal (str, arg)
9675 char *str, *arg;
9677 fprintf (stderr, "%s: ", progname);
9678 fprintf (stderr, str, arg);
9679 fprintf (stderr, "\n");
9680 exit (FAILURE_EXIT_CODE);
9683 /* More 'friendly' abort that prints the line and file.
9684 config.h can #define abort fancy_abort if you like that sort of thing. */
9686 void
9687 fancy_abort ()
9689 fatal ("Internal gcc abort.");
9692 static void
9693 perror_with_name (name)
9694 char *name;
9696 fprintf (stderr, "%s: ", progname);
9697 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9698 errors++;
9701 static void
9702 pfatal_with_name (name)
9703 char *name;
9705 perror_with_name (name);
9706 #ifdef VMS
9707 exit (vaxc$errno);
9708 #else
9709 exit (FAILURE_EXIT_CODE);
9710 #endif
9713 /* Handler for SIGPIPE. */
9715 static void
9716 pipe_closed (signo)
9717 /* If this is missing, some compilers complain. */
9718 int signo;
9720 fatal ("output pipe has been closed");
9723 static void
9724 memory_full ()
9726 fatal ("Memory exhausted.");
9730 char *
9731 xmalloc (size)
9732 unsigned size;
9734 register char *ptr = (char *) malloc (size);
9735 if (ptr != 0) return (ptr);
9736 memory_full ();
9737 /*NOTREACHED*/
9738 return 0;
9741 static char *
9742 xrealloc (old, size)
9743 char *old;
9744 unsigned size;
9746 register char *ptr = (char *) realloc (old, size);
9747 if (ptr != 0) return (ptr);
9748 memory_full ();
9749 /*NOTREACHED*/
9750 return 0;
9753 static char *
9754 xcalloc (number, size)
9755 unsigned number, size;
9757 register unsigned total = number * size;
9758 register char *ptr = (char *) malloc (total);
9759 if (ptr != 0) {
9760 if (total > 100)
9761 bzero (ptr, total);
9762 else {
9763 /* It's not too long, so loop, zeroing by longs.
9764 It must be safe because malloc values are always well aligned. */
9765 register long *zp = (long *) ptr;
9766 register long *zl = (long *) (ptr + total - 4);
9767 register int i = total - 4;
9768 while (zp < zl)
9769 *zp++ = 0;
9770 if (i < 0)
9771 i = 0;
9772 while (i < total)
9773 ptr[i++] = 0;
9775 return ptr;
9777 memory_full ();
9778 /*NOTREACHED*/
9779 return 0;
9782 static char *
9783 savestring (input)
9784 char *input;
9786 unsigned size = strlen (input);
9787 char *output = xmalloc (size + 1);
9788 strcpy (output, input);
9789 return output;
9792 /* Get the file-mode and data size of the file open on FD
9793 and store them in *MODE_POINTER and *SIZE_POINTER. */
9795 static int
9796 file_size_and_mode (fd, mode_pointer, size_pointer)
9797 int fd;
9798 int *mode_pointer;
9799 long int *size_pointer;
9801 struct stat sbuf;
9803 if (fstat (fd, &sbuf) < 0) return (-1);
9804 if (mode_pointer) *mode_pointer = sbuf.st_mode;
9805 if (size_pointer) *size_pointer = sbuf.st_size;
9806 return 0;
9809 static void
9810 output_dots (fd, depth)
9811 FILE* fd;
9812 int depth;
9814 while (depth > 0) {
9815 putc ('.', fd);
9816 depth--;
9821 #ifdef VMS
9823 /* Under VMS we need to fix up the "include" specification
9824 filename so that everything following the 1st slash is
9825 changed into its correct VMS file specification. */
9827 static void
9828 hack_vms_include_specification (fname)
9829 char *fname;
9831 register char *cp, *cp1, *cp2;
9832 int f, check_filename_before_returning, no_prefix_seen;
9833 char Local[512];
9835 check_filename_before_returning = 0;
9836 no_prefix_seen = 0;
9838 /* Ignore leading "./"s */
9839 while (fname[0] == '.' && fname[1] == '/') {
9840 strcpy (fname, fname+2);
9841 no_prefix_seen = 1; /* mark this for later */
9843 /* Look for the boundary between the VMS and UNIX filespecs */
9844 cp = rindex (fname, ']'); /* Look for end of dirspec. */
9845 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
9846 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
9847 if (cp) {
9848 cp++;
9849 } else {
9850 cp = index (fname, '/'); /* Look for the "/" */
9854 * Check if we have a vax-c style '#include filename'
9855 * and add the missing .h
9857 if (cp == 0) {
9858 if (index(fname,'.') == 0)
9859 strcat(fname, ".h");
9860 } else {
9861 if (index(cp,'.') == 0)
9862 strcat(cp, ".h");
9865 cp2 = Local; /* initialize */
9867 /* We are trying to do a number of things here. First of all, we are
9868 trying to hammer the filenames into a standard format, such that later
9869 processing can handle them.
9871 If the file name contains something like [dir.], then it recognizes this
9872 as a root, and strips the ".]". Later processing will add whatever is
9873 needed to get things working properly.
9875 If no device is specified, then the first directory name is taken to be
9876 a device name (or a rooted logical). */
9878 /* See if we found that 1st slash */
9879 if (cp == 0) return; /* Nothing to do!!! */
9880 if (*cp != '/') return; /* Nothing to do!!! */
9881 /* Point to the UNIX filename part (which needs to be fixed!) */
9882 cp1 = cp+1;
9883 /* If the directory spec is not rooted, we can just copy
9884 the UNIX filename part and we are done */
9885 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
9886 if (cp[-2] != '.') {
9888 * The VMS part ends in a `]', and the preceding character is not a `.'.
9889 * We strip the `]', and then splice the two parts of the name in the
9890 * usual way. Given the default locations for include files in cccp.c,
9891 * we will only use this code if the user specifies alternate locations
9892 * with the /include (-I) switch on the command line. */
9893 cp -= 1; /* Strip "]" */
9894 cp1--; /* backspace */
9895 } else {
9897 * The VMS part has a ".]" at the end, and this will not do. Later
9898 * processing will add a second directory spec, and this would be a syntax
9899 * error. Thus we strip the ".]", and thus merge the directory specs.
9900 * We also backspace cp1, so that it points to a '/'. This inhibits the
9901 * generation of the 000000 root directory spec (which does not belong here
9902 * in this case).
9904 cp -= 2; /* Strip ".]" */
9905 cp1--; }; /* backspace */
9906 } else {
9908 /* We drop in here if there is no VMS style directory specification yet.
9909 * If there is no device specification either, we make the first dir a
9910 * device and try that. If we do not do this, then we will be essentially
9911 * searching the users default directory (as if they did a #include "asdf.h").
9913 * Then all we need to do is to push a '[' into the output string. Later
9914 * processing will fill this in, and close the bracket.
9916 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
9917 *cp2++ = '['; /* Open the directory specification */
9920 /* at this point we assume that we have the device spec, and (at least
9921 the opening "[" for a directory specification. We may have directories
9922 specified already */
9924 /* If there are no other slashes then the filename will be
9925 in the "root" directory. Otherwise, we need to add
9926 directory specifications. */
9927 if (index (cp1, '/') == 0) {
9928 /* Just add "000000]" as the directory string */
9929 strcpy (cp2, "000000]");
9930 cp2 += strlen (cp2);
9931 check_filename_before_returning = 1; /* we might need to fool with this later */
9932 } else {
9933 /* As long as there are still subdirectories to add, do them. */
9934 while (index (cp1, '/') != 0) {
9935 /* If this token is "." we can ignore it */
9936 if ((cp1[0] == '.') && (cp1[1] == '/')) {
9937 cp1 += 2;
9938 continue;
9940 /* Add a subdirectory spec. Do not duplicate "." */
9941 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
9942 *cp2++ = '.';
9943 /* If this is ".." then the spec becomes "-" */
9944 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
9945 /* Add "-" and skip the ".." */
9946 *cp2++ = '-';
9947 cp1 += 3;
9948 continue;
9950 /* Copy the subdirectory */
9951 while (*cp1 != '/') *cp2++= *cp1++;
9952 cp1++; /* Skip the "/" */
9954 /* Close the directory specification */
9955 if (cp2[-1] == '.') /* no trailing periods */
9956 cp2--;
9957 *cp2++ = ']';
9959 /* Now add the filename */
9960 while (*cp1) *cp2++ = *cp1++;
9961 *cp2 = 0;
9962 /* Now append it to the original VMS spec. */
9963 strcpy (cp, Local);
9965 /* If we put a [000000] in the filename, try to open it first. If this fails,
9966 remove the [000000], and return that name. This provides flexibility
9967 to the user in that they can use both rooted and non-rooted logical names
9968 to point to the location of the file. */
9970 if (check_filename_before_returning && no_prefix_seen) {
9971 f = open (fname, O_RDONLY, 0666);
9972 if (f >= 0) {
9973 /* The file name is OK as it is, so return it as is. */
9974 close (f);
9975 return;
9977 /* The filename did not work. Try to remove the [000000] from the name,
9978 and return it. */
9979 cp = index (fname, '[');
9980 cp2 = index (fname, ']') + 1;
9981 strcpy (cp, cp2); /* this gets rid of it */
9983 return;
9985 #endif /* VMS */
9987 #ifdef VMS
9989 /* These are the read/write replacement routines for
9990 VAX-11 "C". They make read/write behave enough
9991 like their UNIX counterparts that CCCP will work */
9993 static int
9994 read (fd, buf, size)
9995 int fd;
9996 char *buf;
9997 int size;
9999 #undef read /* Get back the REAL read routine */
10000 register int i;
10001 register int total = 0;
10003 /* Read until the buffer is exhausted */
10004 while (size > 0) {
10005 /* Limit each read to 32KB */
10006 i = (size > (32*1024)) ? (32*1024) : size;
10007 i = read (fd, buf, i);
10008 if (i <= 0) {
10009 if (i == 0) return (total);
10010 return (i);
10012 /* Account for this read */
10013 total += i;
10014 buf += i;
10015 size -= i;
10017 return (total);
10020 static int
10021 write (fd, buf, size)
10022 int fd;
10023 char *buf;
10024 int size;
10026 #undef write /* Get back the REAL write routine */
10027 int i;
10028 int j;
10030 /* Limit individual writes to 32Kb */
10031 i = size;
10032 while (i > 0) {
10033 j = (i > (32*1024)) ? (32*1024) : i;
10034 if (write (fd, buf, j) < 0) return (-1);
10035 /* Account for the data written */
10036 buf += j;
10037 i -= j;
10039 return (size);
10042 /* The following wrapper functions supply additional arguments to the VMS
10043 I/O routines to optimize performance with file handling. The arguments
10044 are:
10045 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10046 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10047 "fop=tef"- Truncate unused portions of file when closing file.
10048 "shr=nil"- Disallow file sharing while file is open.
10051 static FILE *
10052 freopen (fname, type, oldfile)
10053 char *fname;
10054 char *type;
10055 FILE *oldfile;
10057 #undef freopen /* Get back the REAL fopen routine */
10058 if (strcmp (type, "w") == 0)
10059 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10060 return freopen (fname, type, oldfile, "mbc=16");
10063 static FILE *
10064 fopen (fname, type)
10065 char *fname;
10066 char *type;
10068 #undef fopen /* Get back the REAL fopen routine */
10069 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10070 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10071 pre-ANSI implmentation. This hack circumvents the mismatch problem. */
10072 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10074 if (*type == 'w')
10075 return (*vmslib_fopen) (fname, type, "mbc=32",
10076 "deq=64", "fop=tef", "shr=nil");
10077 else
10078 return (*vmslib_fopen) (fname, type, "mbc=32");
10081 static int
10082 open (fname, flags, prot)
10083 char *fname;
10084 int flags;
10085 int prot;
10087 #undef open /* Get back the REAL open routine */
10088 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10091 /* Avoid run-time library bug, where copying M out of N+M characters with
10092 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
10093 gcc-cpp exercises this particular bug. */
10095 static char *
10096 strncat (dst, src, cnt)
10097 char *dst;
10098 const char *src;
10099 unsigned cnt;
10101 register char *d = dst, *s = (char *) src;
10102 register int n = cnt; /* convert to _signed_ type */
10104 while (*d) d++; /* advance to end */
10105 while (--n >= 0)
10106 if (!(*d++ = *s++)) break;
10107 if (n < 0) *d = '\0';
10108 return dst;
10110 #endif /* VMS */