1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 1987, 1989, 1992 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
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
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;
28 #include "../src/config.h"
36 /* The macro EMACS is defined when cpp is distributed as part of Emacs,
37 for the sake of machines with limited C compilers. */
40 #endif /* not EMACS */
42 #ifndef STANDARD_INCLUDE_DIR
43 #define STANDARD_INCLUDE_DIR "/usr/include"
46 #ifndef LOCAL_INCLUDE_DIR
47 #define LOCAL_INCLUDE_DIR "/usr/local/include"
56 /* In case config.h defines these. */
61 #include <sys/types.h>
70 #include <sys/time.h> /* for __DATE__ and __TIME__ */
71 #include <sys/resource.h>
74 #define rindex strrchr
80 extern char *index ();
81 extern char *rindex ();
83 /* VMS-specific definitions */
86 #include <errno.h> /* This defines "errno" properly */
87 #include <perror.h> /* This defines sys_errlist/sys_nerr properly */
89 #define O_RDONLY 0 /* Open arg for Read/Only */
90 #define O_WRONLY 1 /* Open arg for Write/Only */
91 #define read(fd,buf,size) VMS_read(fd,buf,size)
92 #define write(fd,buf,size) VMS_write(fd,buf,size)
93 #define open(fname,mode,prot) VMS_open(fname,mode,prot)
94 #define fopen(fname,mode) VMS_fopen(fname,mode)
95 #define freopen(fname,mode,ofile) VMS_freopen(fname,mode,ofile)
96 static int VMS_read ();
97 static int VMS_write ();
98 static int VMS_open ();
99 static FILE * VMS_fopen ();
100 static FILE * VMS_freopen ();
101 static void hack_vms_include_specification ();
102 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
103 #define ino_t vms_ino_t
105 #define BSTRING /* VMS/GCC supplies the bstring routines */
106 #endif /* __GNUC__ */
115 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
116 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
119 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
122 /* Exported declarations. */
128 /* External declarations. */
130 extern char *getenv ();
131 extern FILE *fdopen ();
132 extern char *version_string;
133 extern struct tm *localtime ();
135 extern char *sys_errlist[];
141 /* Forward declarations. */
148 #if defined(USG) || defined(VMS)
156 /* These functions are declared to return int instead of void since they
157 are going to be placed in a table and some old compilers have trouble with
158 pointers to functions returning void. */
160 static int do_define ();
161 static int do_line ();
162 static int do_include ();
163 static int do_undef ();
164 static int do_error ();
165 static int do_pragma ();
166 static int do_ident ();
168 static int do_xifdef ();
169 static int do_else ();
170 static int do_elif ();
171 static int do_endif ();
172 static int do_sccs ();
173 static int do_once ();
174 static int do_assert ();
175 static int do_unassert ();
176 static int do_warning ();
178 static void add_import ();
179 static void deps_output ();
180 static void make_undef ();
181 static void make_definition ();
182 static void make_assertion ();
183 static void path_include ();
184 static void initialize_builtins ();
185 static void initialize_char_syntax ();
186 static void dump_arg_n ();
187 static void dump_defn_1 ();
188 static void delete_macro ();
189 static void trigraph_pcp ();
190 static void rescan ();
191 static void finclude ();
192 static void validate_else ();
193 static int comp_def_part ();
194 static void error_from_errno ();
195 static void error_with_line ();
197 static void pedwarn_with_file_and_line ();
198 static void fatal ();
200 static void pfatal_with_name ();
201 static void perror_with_name ();
202 static void print_containing_files ();
203 static int lookup_import ();
204 static int check_preconditions ();
205 static void pcfinclude ();
206 static void pcstring_used ();
207 static void write_output ();
208 static int check_macro_name ();
209 static int compare_defs ();
210 static int compare_token_lists ();
211 static int eval_if_expression ();
212 static int discard_comments ();
213 static int delete_newlines ();
214 static int line_for_error ();
216 static int file_size_and_mode ();
218 static struct arglist *read_token_list ();
219 static void free_token_list ();
221 static struct hashnode *install ();
222 struct hashnode *lookup ();
224 static struct assertion_hashnode *assertion_install ();
225 static struct assertion_hashnode *assertion_lookup ();
227 static char *xrealloc ();
228 static char *xcalloc ();
229 static char *savestring ();
231 static void delete_assertion ();
232 static void macroexpand ();
233 static void dump_all_macros ();
234 static void conditional_skip ();
235 static void skip_if_group ();
236 static void output_line_command ();
238 /* Last arg to output_line_command. */
239 enum file_change_code {same_file, enter_file, leave_file};
241 static int grow_outbuf ();
242 static int handle_directive ();
243 static void memory_full ();
245 static U_CHAR *macarg1 ();
246 static char *macarg ();
248 static U_CHAR *skip_to_end_of_comment ();
249 static U_CHAR *skip_quoted_string ();
250 static U_CHAR *skip_paren_group ();
252 static char *check_precompiled ();
253 static struct macrodef create_definition ();
254 static void dump_single_macro ();
256 #ifndef FAILURE_EXIT_CODE
257 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
260 #ifndef SUCCESS_EXIT_CODE
261 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
264 /* Name under which this program was invoked. */
266 static char *progname;
268 /* Nonzero means handle C++ comment syntax and use
269 extra default include directories for C++. */
271 static int cplusplus;
273 /* Nonzero means handle #import, for objective C. */
277 /* Nonzero means this is an assembly file, and allow
278 unknown directives, which could be comments. */
282 /* Current maximum length of directory names in the search path
283 for include files. (Altered as we get more of them.) */
285 static int max_include_len;
287 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
291 /* Nonzero means copy comments into the output file. */
293 static int put_out_comments = 0;
295 /* Nonzero means don't process the ANSI trigraph sequences. */
297 static int no_trigraphs = 0;
299 /* Nonzero means print the names of included files rather than
300 the preprocessed output. 1 means just the #include "...",
301 2 means #include <...> as well. */
303 static int print_deps = 0;
305 /* Nonzero means print names of header files (-H). */
307 static int print_include_names = 0;
309 /* Nonzero means don't output line number information. */
311 static int no_line_commands;
313 /* dump_only means inhibit output of the preprocessed text
314 and instead output the definitions of all user-defined
315 macros in a form suitable for use as input to cccp.
316 dump_names means pass #define and the macro name through to output.
317 dump_definitions means pass the whole definition (plus #define) through
320 static enum {dump_none, dump_only, dump_names, dump_definitions}
321 dump_macros = dump_none;
323 /* Nonzero means pass all #define and #undef directives which we actually
324 process through to the output stream. This feature is used primarily
325 to allow cc1 to record the #defines and #undefs for the sake of
326 debuggers which understand about preprocessor macros, but it may
327 also be useful with -E to figure out how symbols are defined, and
328 where they are defined. */
329 static int debug_output = 0;
331 /* Holds local startup time. */
332 static struct tm *timebuf = NULL;
334 /* Nonzero indicates special processing used by the pcp program. The
335 special effects of this mode are:
337 Inhibit all macro expansion, except those inside #if directives.
339 Process #define directives normally, and output their contents
342 Output preconditions to pcp_outfile indicating all the relevant
343 preconditions for use of this file in a later cpp run.
345 static FILE *pcp_outfile;
347 /* Nonzero means we are inside an IF during a -pcp run. In this mode
348 macro expansion is done, and preconditions are output for all macro
349 uses requiring them. */
350 static int pcp_inside_if;
352 /* Nonzero means never to include precompiled files. */
353 static int no_precomp;
355 /* Nonzero means give all the error messages the ANSI standard requires. */
359 /* Nonzero means try to make failure to fit ANSI C an error. */
361 static int pedantic_errors;
363 /* Nonzero means don't print warning messages. -w. */
365 static int inhibit_warnings = 0;
367 /* Nonzero means warn if slash-star appears in a comment. */
369 static int warn_comments;
371 /* Nonzero means warn if a macro argument is (or would be)
372 stringified with -traditional. */
374 static int warn_stringify;
376 /* Nonzero means warn if there are any trigraphs. */
378 static int warn_trigraphs;
380 /* Nonzero means warn if #import is used. */
382 static int warn_import = 1;
384 /* Nonzero means turn warnings into errors. */
386 static int warnings_are_errors;
388 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
392 /* Nonzero causes output not to be done,
393 but directives such as #define that have side effects
396 static int no_output;
398 /* Nonzero means that we have finished processing the command line options.
399 This flag is used to decide whether or not to issue certain errors
402 static int done_initializing = 0;
404 /* I/O buffer structure.
405 The `fname' field is nonzero for source files and #include files
406 and for the dummy text used for -D and -U.
407 It is zero for rescanning results of macro expansion
408 and for expanding macro arguments. */
409 #define INPUT_STACK_MAX 200
410 static struct file_buf {
412 /* Filename specified with #line command. */
414 /* Record where in the search path this file was found.
415 For #include_next. */
416 struct file_name_list *dir;
421 /* Macro that this level is the expansion of.
422 Included so that we can reenable the macro
423 at the end of this level. */
424 struct hashnode *macro;
425 /* Value of if_stack at start of this file.
426 Used to prohibit unmatched #endif (etc) in an include file. */
427 struct if_stack *if_stack;
428 /* Object to be freed at end of input at this level. */
430 /* True if this is a header file included using <FILENAME>. */
431 char system_header_p;
432 } instack[INPUT_STACK_MAX];
434 static int last_error_tick; /* Incremented each time we print it. */
435 static int input_file_stack_tick; /* Incremented when the status changes. */
437 /* Current nesting level of input sources.
438 `instack[indepth]' is the level currently being read. */
439 static int indepth = -1;
440 #define CHECK_DEPTH(code) \
441 if (indepth >= (INPUT_STACK_MAX - 1)) \
443 error_with_line (line_for_error (instack[indepth].lineno), \
444 "macro or `#include' recursion too deep"); \
448 /* Current depth in #include directives that use <...>. */
449 static int system_include_depth = 0;
451 typedef struct file_buf FILE_BUF;
453 /* The output buffer. Its LENGTH field is the amount of room allocated
454 for the buffer, not the number of chars actually present. To get
455 that, subtract outbuf.buf from outbuf.bufp. */
457 #define OUTBUF_SIZE 10 /* initial size of output buffer */
458 static FILE_BUF outbuf;
460 /* Grow output buffer OBUF points at
461 so it can hold at least NEEDED more chars. */
463 #define check_expand(OBUF, NEEDED) \
464 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
465 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
467 struct file_name_list
469 struct file_name_list *next;
471 /* If the following is nonzero, it is a macro name.
472 Don't include the file again if that macro is defined. */
473 U_CHAR *control_macro;
476 /* #include "file" looks in source file dir, then stack. */
477 /* #include <file> just looks in the stack. */
478 /* -I directories are added to the end, then the defaults are added. */
479 static struct default_include { char *fname; int cplusplus; } include_defaults_array[]
480 #ifdef INCLUDE_DEFAULTS
484 /* Pick up GNU C++ specific include files. */
485 { GPLUSPLUS_INCLUDE_DIR, 1},
486 { GCC_INCLUDE_DIR, 0},
488 /* For cross-compilation, this dir name is generated
489 automatically in Makefile.in. */
490 { CROSS_INCLUDE_DIR, 0 },
491 #else /* not CROSS_COMPILE */
492 { LOCAL_INCLUDE_DIR, 0},
493 /* Some systems have an extra dir of include files. */
494 #ifdef SYSTEM_INCLUDE_DIR
495 { SYSTEM_INCLUDE_DIR, 0},
497 { STANDARD_INCLUDE_DIR, 0},
498 #endif /* not CROSS_COMPILE */
501 #endif /* no INCLUDE_DEFAULTS */
503 /* The code looks at the defaults through this pointer, rather than through
504 the constant structure above. This pointer gets changed if an environment
505 variable specifies other defaults. */
506 static struct default_include *include_defaults = include_defaults_array;
508 static struct file_name_list *include = 0; /* First dir to search */
509 /* First dir to search for <file> */
510 static struct file_name_list *first_bracket_include = 0;
511 static struct file_name_list *last_include = 0; /* Last in chain */
513 /* Chain of include directories to put at the end of the other chain. */
514 static struct file_name_list *after_include = 0;
515 static struct file_name_list *last_after_include = 0; /* Last in chain */
517 /* List of included files that contained #pragma once. */
518 static struct file_name_list *dont_repeat_files = 0;
520 /* List of other included files.
521 If ->control_macro if nonzero, the file had a #ifndef
522 around the entire contents, and ->control_macro gives the macro name. */
523 static struct file_name_list *all_include_files = 0;
525 /* Global list of strings read in from precompiled files. This list
526 is kept in the order the strings are read in, with new strings being
527 added at the end through stringlist_tailp. We use this list to output
528 the strings at the end of the run.
530 static STRINGDEF *stringlist;
531 static STRINGDEF **stringlist_tailp = &stringlist;
534 /* Structure returned by create_definition */
535 typedef struct macrodef MACRODEF;
538 struct definition *defn;
544 /* Structure allocated for every #define. For a simple replacement
547 nargs = -1, the `pattern' list is null, and the expansion is just
548 the replacement text. Nargs = 0 means a functionlike macro with no args,
550 #define getchar() getc (stdin) .
551 When there are args, the expansion is the replacement text with the
552 args squashed out, and the reflist is a list describing how to
553 build the output from the input: e.g., "3 chars, then the 1st arg,
554 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
555 The chars here come from the expansion. Whatever is left of the
556 expansion after the last arg-occurrence is copied after that arg.
557 Note that the reflist can be arbitrarily long---
558 its length depends on the number of times the arguments appear in
559 the replacement text, not how many args there are. Example:
560 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
562 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
563 where (x, y) means (nchars, argno). */
565 typedef struct definition DEFINITION;
568 int length; /* length of expansion string */
569 int predefined; /* True if the macro was builtin or */
570 /* came from the command line */
572 int line; /* Line number of definition */
573 char *file; /* File of definition */
575 struct reflist *next;
576 char stringify; /* nonzero if this arg was preceded by a
578 char raw_before; /* Nonzero if a ## operator before arg. */
579 char raw_after; /* Nonzero if a ## operator after arg. */
580 int nchars; /* Number of literal chars to copy before
581 this arg occurrence. */
582 int argno; /* Number of arg to substitute (origin-0) */
585 /* Names of macro args, concatenated in reverse order
586 with comma-space between them.
587 The only use of this is that we warn on redefinition
588 if this differs between the old and new definitions. */
593 /* different kinds of things that can appear in the value field
594 of a hash node. Actually, this may be useless now. */
603 /* The structure of a node in the hash table. The hash table
604 has entries for all tokens defined by #define commands (type T_MACRO),
605 plus some special tokens like __LINE__ (these each have their own
606 type, and the appropriate code is run when that type of node is seen.
607 It does not contain control words like "#define", which are recognized
608 by a separate piece of code. */
610 /* different flavors of hash nodes --- also used in keyword table */
612 T_DEFINE = 1, /* the `#define' keyword */
613 T_INCLUDE, /* the `#include' keyword */
614 T_INCLUDE_NEXT, /* the `#include_next' keyword */
615 T_IMPORT, /* the `#import' keyword */
616 T_IFDEF, /* the `#ifdef' keyword */
617 T_IFNDEF, /* the `#ifndef' keyword */
618 T_IF, /* the `#if' keyword */
619 T_ELSE, /* `#else' */
620 T_PRAGMA, /* `#pragma' */
621 T_ELIF, /* `#elif' */
622 T_UNDEF, /* `#undef' */
623 T_LINE, /* `#line' */
624 T_ERROR, /* `#error' */
625 T_WARNING, /* `#warning' */
626 T_ENDIF, /* `#endif' */
627 T_SCCS, /* `#sccs', used on system V. */
628 T_IDENT, /* `#ident', used on system V. */
629 T_ASSERT, /* `#assert', taken from system V. */
630 T_UNASSERT, /* `#unassert', taken from system V. */
631 T_SPECLINE, /* special symbol `__LINE__' */
632 T_DATE, /* `__DATE__' */
633 T_FILE, /* `__FILE__' */
634 T_BASE_FILE, /* `__BASE_FILE__' */
635 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
636 T_VERSION, /* `__VERSION__' */
637 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
638 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
639 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
640 T_TIME, /* `__TIME__' */
641 T_CONST, /* Constant value, used by `__STDC__' */
642 T_MACRO, /* macro defined by `#define' */
643 T_DISABLED, /* macro temporarily turned off for rescan */
644 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
645 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
646 T_UNUSED /* Used for something not defined. */
650 struct hashnode *next; /* double links for easy deletion */
651 struct hashnode *prev;
652 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
653 chain is kept, in case the node is the head
654 of the chain and gets deleted. */
655 enum node_type type; /* type of special token */
656 int length; /* length of token, for quick comparison */
657 U_CHAR *name; /* the actual name */
658 union hashval value; /* pointer to expansion, or whatever */
661 typedef struct hashnode HASHNODE;
663 /* Some definitions for the hash table. The hash function MUST be
664 computed as shown in hashf () below. That is because the rescan
665 loop computes the hash value `on the fly' for most tokens,
666 in order to avoid the overhead of a lot of procedure calls to
667 the hashf () function. Hashf () only exists for the sake of
668 politeness, for use when speed isn't so important. */
670 #define HASHSIZE 1403
671 static HASHNODE *hashtab[HASHSIZE];
672 #define HASHSTEP(old, c) ((old << 2) + c)
673 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
675 /* Symbols to predefine. */
677 #ifdef CPP_PREDEFINES
678 static char *predefs = CPP_PREDEFINES;
680 static char *predefs = "";
683 /* We let tm.h override the types used here, to handle trivial differences
684 such as the choice of unsigned int or long unsigned int for size_t.
685 When machines start needing nontrivial differences in the size type,
686 it would be best to do something here to figure out automatically
687 from other information what type to use. */
689 /* The string value for __size_type__. */
692 #define SIZE_TYPE "long unsigned int"
695 /* The string value for __ptrdiff_type__. */
698 #define PTRDIFF_TYPE "long int"
701 /* The string value for __wchar_type__. */
704 #define WCHAR_TYPE "int"
707 /* In the definition of a #assert name, this structure forms
708 a list of the individual values asserted.
709 Each value is itself a list of "tokens".
710 These are strings that are compared by name. */
712 struct tokenlist_list {
713 struct tokenlist_list *next;
714 struct arglist *tokens;
717 struct assertion_hashnode {
718 struct assertion_hashnode *next; /* double links for easy deletion */
719 struct assertion_hashnode *prev;
720 /* also, a back pointer to this node's hash
721 chain is kept, in case the node is the head
722 of the chain and gets deleted. */
723 struct assertion_hashnode **bucket_hdr;
724 int length; /* length of token, for quick comparison */
725 U_CHAR *name; /* the actual name */
726 /* List of token-sequences. */
727 struct tokenlist_list *value;
730 typedef struct assertion_hashnode ASSERTION_HASHNODE;
732 /* Some definitions for the hash table. The hash function MUST be
733 computed as shown in hashf () below. That is because the rescan
734 loop computes the hash value `on the fly' for most tokens,
735 in order to avoid the overhead of a lot of procedure calls to
736 the hashf () function. Hashf () only exists for the sake of
737 politeness, for use when speed isn't so important. */
739 #define ASSERTION_HASHSIZE 37
740 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
742 /* Nonzero means inhibit macroexpansion of what seem to be
743 assertion tests, in rescan. For #if. */
744 static int assertions_flag;
746 /* `struct directive' defines one #-directive, including how to handle it. */
749 int length; /* Length of name */
750 int (*func)(); /* Function to handle directive */
751 char *name; /* Name of directive */
752 enum node_type type; /* Code which describes which directive. */
753 char angle_brackets; /* Nonzero => <...> is special. */
754 char traditional_comments; /* Nonzero: keep comments if -traditional. */
755 char pass_thru; /* Copy preprocessed directive to output file. */
758 /* Here is the actual list of #-directives, most-often-used first. */
760 static struct directive directive_table[] = {
761 { 6, do_define, "define", T_DEFINE, 0, 1},
762 { 2, do_if, "if", T_IF},
763 { 5, do_xifdef, "ifdef", T_IFDEF},
764 { 6, do_xifdef, "ifndef", T_IFNDEF},
765 { 5, do_endif, "endif", T_ENDIF},
766 { 4, do_else, "else", T_ELSE},
767 { 4, do_elif, "elif", T_ELIF},
768 { 4, do_line, "line", T_LINE},
769 { 7, do_include, "include", T_INCLUDE, 1},
770 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
771 { 6, do_include, "import", T_IMPORT, 1},
772 { 5, do_undef, "undef", T_UNDEF},
773 { 5, do_error, "error", T_ERROR},
774 { 7, do_warning, "warning", T_WARNING},
775 #ifdef SCCS_DIRECTIVE
776 { 4, do_sccs, "sccs", T_SCCS},
778 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
779 { 5, do_ident, "ident", T_IDENT, 0, 0, 1},
780 { 6, do_assert, "assert", T_ASSERT},
781 { 8, do_unassert, "unassert", T_UNASSERT},
782 { -1, 0, "", T_UNUSED},
785 /* When a directive handler is called,
786 this points to the # that started the directive. */
787 U_CHAR *directive_start;
789 /* table to tell if char can be part of a C identifier. */
790 U_CHAR is_idchar[256];
791 /* table to tell if char can be first char of a c identifier. */
792 U_CHAR is_idstart[256];
793 /* table to tell if c is horizontal space. */
794 U_CHAR is_hor_space[256];
795 /* table to tell if c is horizontal or vertical space. */
796 static U_CHAR is_space[256];
798 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
799 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
801 static int errors = 0; /* Error counter for exit code */
803 /* Zero means dollar signs are punctuation.
804 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
805 This must be 0 for correct processing of this ANSI C program:
807 #define lose(b) foo(b)
810 static int dollars_in_ident;
811 #ifndef DOLLARS_IN_IDENTIFIERS
812 #define DOLLARS_IN_IDENTIFIERS 1
815 static FILE_BUF expand_to_temp_buffer ();
817 static DEFINITION *collect_expansion ();
819 /* Stack of conditionals currently in progress
820 (including both successful and failing conditionals). */
823 struct if_stack *next; /* for chaining to the next stack frame */
824 char *fname; /* copied from input when frame is made */
825 int lineno; /* similarly */
826 int if_succeeded; /* true if a leg of this if-group
827 has been passed through rescan */
828 U_CHAR *control_macro; /* For #ifndef at start of file,
829 this is the macro name tested. */
830 enum node_type type; /* type of last directive seen in this group */
832 typedef struct if_stack IF_STACK_FRAME;
833 static IF_STACK_FRAME *if_stack = NULL;
835 /* Buffer of -M output. */
836 static char *deps_buffer;
838 /* Number of bytes allocated in above. */
839 static int deps_allocated_size;
841 /* Number of bytes used. */
842 static int deps_size;
844 /* Number of bytes since the last newline. */
845 static int deps_column;
847 /* File name which deps are being written to.
848 This is 0 if deps are being written to stdout. */
849 static char *deps_file = 0;
851 /* Nonzero means -I- has been seen,
852 so don't look for #include "foo" the source-file directory. */
853 static int ignore_srcdir;
855 /* Handler for SIGPIPE. */
859 /* If this is missing, some compilers complain. */
862 fatal ("output pipe has been closed");
872 char *in_fname, *out_fname;
876 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
877 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
878 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
879 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
880 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
882 /* Record the option used with each element of pend_assertions.
883 This is preparation for supporting more than one option for making
885 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
886 int inhibit_predefs = 0;
887 int no_standard_includes = 0;
888 int missing_newline = 0;
890 /* Non-0 means don't output the preprocessed program. */
891 int inhibit_output = 0;
893 /* Stream on which to print the dependency information. */
894 FILE *deps_stream = 0;
895 /* Target-name to write with the dependency information. */
896 char *deps_target = 0;
899 /* Get rid of any avoidable limit on stack size. */
903 /* Set the stack limit huge so that alloca (particularly stringtab
904 * in dbxread.c) does not fail. */
905 getrlimit (RLIMIT_STACK, &rlim);
906 rlim.rlim_cur = rlim.rlim_max;
907 setrlimit (RLIMIT_STACK, &rlim);
909 #endif /* RLIMIT_STACK defined */
914 /* Remove directories from PROGNAME. */
917 progname = savestring (argv[0]);
919 if (!(s = rindex (progname, ']')))
920 s = rindex (progname, ':');
922 strcpy (progname, s+1);
923 if (s = rindex (progname, '.'))
931 /* Initialize is_idchar to allow $. */
932 dollars_in_ident = 1;
933 initialize_char_syntax ();
934 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
936 no_line_commands = 0;
938 dump_macros = dump_none;
943 signal (SIGPIPE, pipe_closed);
946 for (i = 0; include_defaults[i].fname; i++)
947 max_include_len = MAX (max_include_len,
948 strlen (include_defaults[i].fname));
949 /* Leave room for making file name longer when converting to VMS syntax. */
951 max_include_len += 10;
954 bzero (pend_files, argc * sizeof (char *));
955 bzero (pend_defs, argc * sizeof (char *));
956 bzero (pend_undefs, argc * sizeof (char *));
957 bzero (pend_assertions, argc * sizeof (char *));
958 bzero (pend_includes, argc * sizeof (char *));
960 /* Process switches and find input file name. */
962 for (i = 1; i < argc; i++) {
963 if (argv[i][0] != '-') {
964 if (out_fname != NULL)
965 fatal ("Usage: %s [switches] input output", argv[0]);
966 else if (in_fname != NULL)
971 switch (argv[i][1]) {
974 if (!strcmp (argv[i], "-include")) {
976 fatal ("Filename missing after -include option");
978 pend_includes[i] = argv[i+1], i++;
980 if (!strcmp (argv[i], "-imacros")) {
982 fatal ("Filename missing after -imacros option");
984 pend_files[i] = argv[i+1], i++;
986 /* Add directory to end of path for includes. */
987 if (!strcmp (argv[i], "-idirafter")) {
988 struct file_name_list *dirtmp;
990 dirtmp = (struct file_name_list *)
991 xmalloc (sizeof (struct file_name_list));
992 dirtmp->next = 0; /* New one goes on the end */
993 dirtmp->control_macro = 0;
994 if (after_include == 0)
995 after_include = dirtmp;
997 last_after_include->next = dirtmp;
998 last_after_include = dirtmp; /* Tail follows the last one */
1001 fatal ("Directory name missing after -idirafter option");
1003 dirtmp->fname = argv[++i];
1005 if (strlen (dirtmp->fname) > max_include_len)
1006 max_include_len = strlen (dirtmp->fname);
1011 if (out_fname != NULL)
1012 fatal ("Output filename specified twice");
1014 fatal ("Filename missing after -o option");
1015 out_fname = argv[++i];
1016 if (!strcmp (out_fname, "-"))
1021 if (!strcmp (argv[i], "-pedantic"))
1023 else if (!strcmp (argv[i], "-pedantic-errors")) {
1025 pedantic_errors = 1;
1026 } else if (!strcmp (argv[i], "-pcp")) {
1027 char *pcp_fname = argv[++i];
1029 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1030 ? fopen (pcp_fname, "w")
1031 : fdopen (dup (fileno (stdout)), "w"));
1032 if (pcp_outfile == 0)
1033 pfatal_with_name (pcp_fname);
1039 if (!strcmp (argv[i], "-traditional")) {
1041 if (dollars_in_ident > 0)
1042 dollars_in_ident = 1;
1043 } else if (!strcmp (argv[i], "-trigraphs")) {
1049 if (! strcmp (argv[i], "-lang-c"))
1050 cplusplus = 0, objc = 0;
1051 if (! strcmp (argv[i], "-lang-c++"))
1052 cplusplus = 1, objc = 0;
1053 if (! strcmp (argv[i], "-lang-objc"))
1054 objc = 1, cplusplus = 0;
1055 if (! strcmp (argv[i], "-lang-objc++"))
1056 objc = 1, cplusplus = 1;
1057 if (! strcmp (argv[i], "-lang-asm"))
1059 if (! strcmp (argv[i], "-lint"))
1068 inhibit_warnings = 1;
1072 if (!strcmp (argv[i], "-Wtrigraphs"))
1074 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1076 else if (!strcmp (argv[i], "-Wcomment"))
1078 else if (!strcmp (argv[i], "-Wno-comment"))
1080 else if (!strcmp (argv[i], "-Wcomments"))
1082 else if (!strcmp (argv[i], "-Wno-comments"))
1084 else if (!strcmp (argv[i], "-Wtraditional"))
1086 else if (!strcmp (argv[i], "-Wno-traditional"))
1088 else if (!strcmp (argv[i], "-Wimport"))
1090 else if (!strcmp (argv[i], "-Wno-import"))
1092 else if (!strcmp (argv[i], "-Werror"))
1093 warnings_are_errors = 1;
1094 else if (!strcmp (argv[i], "-Wno-error"))
1095 warnings_are_errors = 0;
1096 else if (!strcmp (argv[i], "-Wall"))
1104 if (!strcmp (argv[i], "-M"))
1106 else if (!strcmp (argv[i], "-MM"))
1108 else if (!strcmp (argv[i], "-MD"))
1110 else if (!strcmp (argv[i], "-MMD"))
1112 /* For -MD and -MMD options, write deps on file named by next arg. */
1113 if (!strcmp (argv[i], "-MD")
1114 || !strcmp (argv[i], "-MMD")) {
1116 deps_file = argv[i];
1117 deps_stream = fopen (argv[i], "a");
1118 if (deps_stream == 0)
1119 pfatal_with_name (argv[i]);
1121 /* For -M and -MM, write deps on standard output
1122 and suppress the usual output. */
1123 deps_stream = stdout;
1130 char *p = argv[i] + 2;
1133 /* Arg to -d specifies what parts of macros to dump */
1136 dump_macros = dump_only;
1140 dump_macros = dump_names;
1143 dump_macros = dump_definitions;
1151 if (argv[i][2] == '3')
1156 fprintf (stderr, "GNU CPP version %s", version_string);
1157 #ifdef TARGET_VERSION
1160 fprintf (stderr, "\n");
1164 print_include_names = 1;
1171 if (argv[i][2] != 0)
1173 else if (i + 1 == argc)
1174 fatal ("Macro name missing after -D option");
1186 if (argv[i][2] != 0)
1188 else if (i + 1 == argc)
1189 fatal ("Assertion missing after -A option");
1193 if (!strcmp (p, "-")) {
1194 /* -A- eliminates all predefined macros and assertions.
1195 Let's include also any that were specified earlier
1196 on the command line. That way we can get rid of any
1197 that were passed automatically in from GCC. */
1199 inhibit_predefs = 1;
1200 for (j = 0; j < i; j++)
1201 pend_defs[j] = pend_assertions[j] = 0;
1203 pend_assertions[i] = p;
1204 pend_assertion_options[i] = "-A";
1209 case 'U': /* JF #undef something */
1210 if (argv[i][2] != 0)
1211 pend_undefs[i] = argv[i] + 2;
1212 else if (i + 1 == argc)
1213 fatal ("Macro name missing after -U option");
1215 pend_undefs[i] = argv[i+1], i++;
1219 put_out_comments = 1;
1222 case 'E': /* -E comes from cc -E; ignore it. */
1226 no_line_commands = 1;
1229 case '$': /* Don't include $ in identifiers. */
1230 dollars_in_ident = 0;
1233 case 'I': /* Add directory to path for includes. */
1235 struct file_name_list *dirtmp;
1237 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-"))
1240 dirtmp = (struct file_name_list *)
1241 xmalloc (sizeof (struct file_name_list));
1242 dirtmp->next = 0; /* New one goes on the end */
1243 dirtmp->control_macro = 0;
1247 last_include->next = dirtmp;
1248 last_include = dirtmp; /* Tail follows the last one */
1249 if (argv[i][2] != 0)
1250 dirtmp->fname = argv[i] + 2;
1251 else if (i + 1 == argc)
1252 fatal ("Directory name missing after -I option");
1254 dirtmp->fname = argv[++i];
1255 if (strlen (dirtmp->fname) > max_include_len)
1256 max_include_len = strlen (dirtmp->fname);
1257 if (ignore_srcdir && first_bracket_include == 0)
1258 first_bracket_include = dirtmp;
1264 if (!strcmp (argv[i], "-nostdinc"))
1265 /* -nostdinc causes no default include directories.
1266 You must specify all include-file directories with -I. */
1267 no_standard_includes = 1;
1268 else if (!strcmp (argv[i], "-noprecomp"))
1273 /* Sun compiler passes undocumented switch "-undef".
1274 Let's assume it means to inhibit the predefined symbols. */
1275 inhibit_predefs = 1;
1278 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1279 if (in_fname == NULL) {
1282 } else if (out_fname == NULL) {
1285 } /* else fall through into error */
1288 fatal ("Invalid option `%s'", argv[i]);
1293 /* Add dirs from CPATH after dirs from -I. */
1294 /* There seems to be confusion about what CPATH should do,
1295 so for the moment it is not documented. */
1296 /* Some people say that CPATH should replace the standard include dirs,
1297 but that seems pointless: it comes before them, so it overrides them
1299 p = (char *) getenv ("CPATH");
1300 if (p != 0 && ! no_standard_includes)
1303 /* Now that dollars_in_ident is known, initialize is_idchar. */
1304 initialize_char_syntax ();
1306 /* Initialize output buffer */
1308 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1309 outbuf.bufp = outbuf.buf;
1310 outbuf.length = OUTBUF_SIZE;
1312 /* Do partial setup of input buffer for the sake of generating
1313 early #line directives (when -g is in effect). */
1315 fp = &instack[++indepth];
1316 if (in_fname == NULL)
1318 fp->nominal_fname = fp->fname = in_fname;
1321 /* Install __LINE__, etc. Must follow initialize_char_syntax
1322 and option processing. */
1323 initialize_builtins (fp, &outbuf);
1325 /* Do standard #defines and assertions
1326 that identify system and machine type. */
1328 if (!inhibit_predefs) {
1329 char *p = (char *) alloca (strlen (predefs) + 1);
1330 strcpy (p, predefs);
1333 while (*p == ' ' || *p == '\t')
1335 /* Handle -D options. */
1336 if (p[0] == '-' && p[1] == 'D') {
1338 while (*p && *p != ' ' && *p != '\t')
1343 output_line_command (fp, &outbuf, 0, same_file);
1344 make_definition (q, &outbuf);
1345 while (*p == ' ' || *p == '\t')
1347 } else if (p[0] == '-' && p[1] == 'A') {
1348 /* Handle -A options (assertions). */
1357 past_name = assertion;
1358 /* Locate end of name. */
1359 while (*past_name && *past_name != ' '
1360 && *past_name != '\t' && *past_name != '(')
1362 /* Locate `(' at start of value. */
1364 while (*value && (*value == ' ' || *value == '\t'))
1366 if (*value++ != '(')
1368 while (*value && (*value == ' ' || *value == '\t'))
1371 /* Locate end of value. */
1372 while (*past_value && *past_value != ' '
1373 && *past_value != '\t' && *past_value != ')')
1375 termination = past_value;
1376 while (*termination && (*termination == ' ' || *termination == '\t'))
1378 if (*termination++ != ')')
1380 if (*termination && *termination != ' ' && *termination != '\t')
1382 /* Temporarily null-terminate the value. */
1383 save_char = *termination;
1384 *termination = '\0';
1385 /* Install the assertion. */
1386 make_assertion ("-A", assertion);
1387 *termination = (char) save_char;
1389 while (*p == ' ' || *p == '\t')
1397 /* Now handle the command line options. */
1399 /* Do assertions specified with -A. */
1400 for (i = 1; i < argc; i++)
1401 if (pend_assertions[i])
1402 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1404 /* Do defines specified with -D. */
1405 for (i = 1; i < argc; i++)
1408 output_line_command (fp, &outbuf, 0, same_file);
1409 make_definition (pend_defs[i], &outbuf);
1412 /* Do undefines specified with -U. */
1413 for (i = 1; i < argc; i++)
1414 if (pend_undefs[i]) {
1416 output_line_command (fp, &outbuf, 0, same_file);
1417 make_undef (pend_undefs[i], &outbuf);
1420 done_initializing = 1;
1422 { /* read the appropriate environment variable and if it exists
1423 replace include_defaults with the listed path. */
1425 switch ((objc << 1) + cplusplus)
1428 epath = getenv ("C_INCLUDE_PATH");
1431 epath = getenv ("CPLUS_INCLUDE_PATH");
1434 epath = getenv ("OBJC_INCLUDE_PATH");
1437 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1440 /* If the environment var for this language is set,
1441 add to the default list of include directories. */
1443 char *nstore = (char *) alloca (strlen (epath) + 2);
1445 char *startp, *endp;
1447 for (num_dirs = 1, startp = epath; *startp; startp++)
1451 = (struct default_include *) xmalloc ((num_dirs
1452 * sizeof (struct default_include))
1453 + sizeof (include_defaults_array));
1454 startp = endp = epath;
1457 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1460 && (endp-startp != 1 || !isalpha (*startp)))
1464 strncpy (nstore, startp, endp-startp);
1466 strcpy (nstore, ".");
1468 nstore[endp-startp] = '\0';
1470 max_include_len = MAX (max_include_len, endp-startp+2);
1471 include_defaults[num_dirs].fname = savestring (nstore);
1472 include_defaults[num_dirs].cplusplus = cplusplus;
1476 endp = startp = endp + 1;
1480 /* Put the usual defaults back in at the end. */
1481 bcopy (include_defaults_array, &include_defaults[num_dirs],
1482 sizeof (include_defaults_array));
1486 /* Unless -fnostdinc,
1487 tack on the standard include file dirs to the specified list */
1488 if (!no_standard_includes) {
1489 struct default_include *p = include_defaults;
1490 char *specd_prefix = getenv ("GCC_EXEC_PREFIX");
1491 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1492 int default_len = 0;
1493 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1494 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1495 default_len = strlen (default_prefix) - 7;
1496 default_prefix[default_len] = 0;
1498 /* Search "translated" versions of GNU directories.
1499 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1500 if (specd_prefix != 0 && default_len != 0)
1501 for (p = include_defaults; p->fname; p++) {
1502 /* Some standard dirs are only for C++. */
1503 if (!p->cplusplus || cplusplus) {
1504 /* Does this dir start with the prefix? */
1505 if (!strncmp (p->fname, default_prefix, default_len)) {
1506 /* Yes; change prefix and add to search list. */
1507 struct file_name_list *new
1508 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1509 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
1510 char *str = (char *) xmalloc (this_len + 1);
1511 strcpy (str, specd_prefix);
1512 strcat (str, p->fname + default_len);
1514 new->control_macro = 0;
1516 /* Add elt to tail of list. */
1520 last_include->next = new;
1521 /* Make sure list for #include <...> also has the standard dirs. */
1522 if (ignore_srcdir && first_bracket_include == 0)
1523 first_bracket_include = new;
1524 /* Record new tail. */
1526 /* Update max_include_len if necessary. */
1527 if (this_len > max_include_len)
1528 max_include_len = this_len;
1532 /* Search ordinary names for GNU include directories. */
1533 for (p = include_defaults; p->fname; p++) {
1534 /* Some standard dirs are only for C++. */
1535 if (!p->cplusplus || cplusplus) {
1536 struct file_name_list *new
1537 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1538 new->control_macro = 0;
1539 /* Add elt to tail of list. */
1543 last_include->next = new;
1544 /* Make sure list for #include <...> also has the standard dirs. */
1545 if (ignore_srcdir && first_bracket_include == 0)
1546 first_bracket_include = new;
1547 /* Record new tail. */
1549 new->fname = p->fname;
1554 /* Tack the after_include chain at the end of the include chain. */
1556 last_include->next = after_include;
1558 include = after_include;
1559 if (ignore_srcdir && first_bracket_include == 0)
1560 first_bracket_include = after_include;
1562 /* Terminate the after_include chain. */
1563 if (last_after_include)
1564 last_after_include->next = 0;
1566 /* Scan the -imacros files before the main input.
1567 Much like #including them, but with no_output set
1568 so that only their macro definitions matter. */
1571 for (i = 1; i < argc; i++)
1572 if (pend_files[i]) {
1573 int fd = open (pend_files[i], O_RDONLY, 0666);
1575 perror_with_name (pend_files[i]);
1576 return FAILURE_EXIT_CODE;
1578 finclude (fd, pend_files[i], &outbuf, 0, 0);
1582 /* Copy the entire contents of the main input file into
1583 the stacked input buffer previously allocated for it. */
1585 /* JF check for stdin */
1586 if (in_fname == NULL || *in_fname == 0) {
1589 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
1592 /* Either of two environment variables can specify output of deps.
1593 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1594 where OUTPUT_FILE is the file to write deps info to
1595 and DEPS_TARGET is the target to mention in the deps. */
1598 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1599 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1600 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1605 spec = getenv ("SUNPRO_DEPENDENCIES");
1612 /* Find the space before the DEPS_TARGET, if there is one. */
1613 /* Don't use `index'; that causes trouble on USG. */
1614 while (*s != 0 && *s != ' ') s++;
1616 deps_target = s + 1;
1617 output_file = (char *) xmalloc (s - spec + 1);
1618 bcopy (spec, output_file, s - spec);
1619 output_file[s - spec] = 0;
1626 deps_file = output_file;
1627 deps_stream = fopen (output_file, "a");
1628 if (deps_stream == 0)
1629 pfatal_with_name (output_file);
1632 /* For -M, print the expected object file name
1633 as the target of this Make-rule. */
1635 deps_allocated_size = 200;
1636 deps_buffer = (char *) xmalloc (deps_allocated_size);
1642 deps_output (deps_target, 0);
1643 deps_output (":", 0);
1644 } else if (*in_fname == 0)
1645 deps_output ("-: ", 0);
1650 /* Discard all directory prefixes from P. */
1656 /* Output P, but remove known suffixes. */
1658 if (p[len - 2] == '.' && p[len - 1] == 'c')
1659 deps_output (p, len - 2);
1660 else if (p[len - 2] == '.' && p[len - 1] == 'C')
1661 deps_output (p, len - 2);
1662 else if (p[len - 3] == '.'
1663 && p[len - 2] == 'c'
1664 && p[len - 1] == 'c')
1665 deps_output (p, len - 3);
1666 else if (p[len - 2] == '.' && p[len - 1] == 's')
1667 deps_output (p, len - 2);
1668 else if (p[len - 2] == '.' && p[len - 1] == 'S')
1669 deps_output (p, len - 2);
1670 else if (p[len - 2] == '.' && p[len - 1] == 'm')
1671 deps_output (p, len - 2);
1674 /* Supply our own suffix. */
1675 deps_output (".o : ", 0);
1676 deps_output (in_fname, 0);
1677 deps_output (" ", 0);
1681 file_size_and_mode (f, &st_mode, &st_size);
1682 fp->nominal_fname = fp->fname = in_fname;
1684 fp->system_header_p = 0;
1685 /* JF all this is mine about reading pipes and ttys */
1686 if (! S_ISREG (st_mode)) {
1687 /* Read input from a file that is not a normal disk file.
1688 We cannot preallocate a buffer with the correct size,
1689 so we must read in the file a piece at the time and make it bigger. */
1697 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
1700 cnt = read (f, bufp, bsize - size);
1701 if (cnt < 0) goto perror; /* error! */
1702 if (cnt == 0) break; /* End of file */
1705 if (bsize == size) { /* Buffer is full! */
1707 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
1708 bufp = fp->buf + size; /* May have moved */
1713 /* Read a file whose size we can determine in advance.
1714 For the sake of VMS, st_size is just an upper bound. */
1717 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
1719 while (st_size > 0) {
1720 i = read (f, fp->buf + fp->length, st_size);
1730 fp->if_stack = if_stack;
1732 /* Make sure data ends with a newline. And put a null after it. */
1734 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
1735 /* Backslash-newline at end is not good enough. */
1736 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
1737 fp->buf[fp->length++] = '\n';
1738 missing_newline = 1;
1740 fp->buf[fp->length] = '\0';
1742 /* Unless inhibited, convert trigraphs in the input. */
1747 /* Now that we know the input file is valid, open the output. */
1749 if (!out_fname || !strcmp (out_fname, ""))
1750 out_fname = "stdout";
1751 else if (! freopen (out_fname, "w", stdout))
1752 pfatal_with_name (out_fname);
1754 output_line_command (fp, &outbuf, 0, same_file);
1756 /* Scan the -include files before the main input. */
1758 for (i = 1; i < argc; i++)
1759 if (pend_includes[i]) {
1760 int fd = open (pend_includes[i], O_RDONLY, 0666);
1762 perror_with_name (pend_includes[i]);
1763 return FAILURE_EXIT_CODE;
1765 finclude (fd, pend_includes[i], &outbuf, 0, 0);
1768 /* Scan the input, processing macros and directives. */
1770 rescan (&outbuf, 0);
1772 if (pedantic && missing_newline)
1773 pedwarn ("file does not end in newline");
1775 /* Now we have processed the entire input
1776 Write whichever kind of output has been requested. */
1778 if (dump_macros == dump_only)
1780 else if (! inhibit_output) {
1785 /* Don't actually write the deps file if compilation has failed.
1786 Delete it instead. */
1787 if (errors > 0 && deps_file != 0)
1790 fputs (deps_buffer, deps_stream);
1791 putc ('\n', deps_stream);
1792 if (deps_stream != stdout) {
1793 fclose (deps_stream);
1794 if (ferror (deps_stream))
1795 fatal ("I/O error on output");
1800 if (ferror (stdout))
1801 fatal ("I/O error on output");
1804 exit (FAILURE_EXIT_CODE);
1805 exit (SUCCESS_EXIT_CODE);
1808 pfatal_with_name (in_fname);
1812 /* Given a colon-separated list of file names PATH,
1813 add all the names to the search path for include files. */
1827 struct file_name_list *dirtmp;
1829 /* Find the end of this name. */
1831 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1832 while (*q != 0 && (*q != ':' || (q - p == 1 && isalpha (*p)))) q++;
1834 while (*q != 0 && *q != ':') q++;
1837 /* An empty name in the path stands for the current directory. */
1838 name = (char *) xmalloc (2);
1842 /* Otherwise use the directory that is named. */
1843 name = (char *) xmalloc (q - p + 1);
1844 bcopy (p, name, q - p);
1848 dirtmp = (struct file_name_list *)
1849 xmalloc (sizeof (struct file_name_list));
1850 dirtmp->next = 0; /* New one goes on the end */
1851 dirtmp->control_macro = 0;
1855 last_include->next = dirtmp;
1856 last_include = dirtmp; /* Tail follows the last one */
1857 dirtmp->fname = name;
1858 if (strlen (dirtmp->fname) > max_include_len)
1859 max_include_len = strlen (dirtmp->fname);
1860 if (ignore_srcdir && first_bracket_include == 0)
1861 first_bracket_include = dirtmp;
1863 /* Advance past this name. */
1867 /* Skip the colon. */
1872 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
1873 before main CCCP processing. Name `pcp' is also in honor of the
1874 drugs the trigraph designers must have been on.
1876 Using an extra pass through the buffer takes a little extra time,
1877 but is infinitely less hairy than trying to handle trigraphs inside
1878 strings, etc. everywhere, and also makes sure that trigraphs are
1879 only translated in the top level of processing. */
1885 register U_CHAR c, *fptr, *bptr, *sptr;
1888 fptr = bptr = sptr = buf->buf;
1889 while ((sptr = (U_CHAR *) index (sptr, '?')) != NULL) {
1926 len = sptr - fptr - 2;
1927 if (bptr != fptr && len > 0)
1928 bcopy (fptr, bptr, len); /* BSD doc says bcopy () works right
1929 for overlapping strings. In ANSI
1930 C, this will be memmove (). */
1935 len = buf->length - (fptr - buf->buf);
1936 if (bptr != fptr && len > 0)
1937 bcopy (fptr, bptr, len);
1938 buf->length -= fptr - bptr;
1939 buf->buf[buf->length] = '\0';
1940 if (warn_trigraphs && fptr != bptr)
1941 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
1944 /* Move all backslash-newline pairs out of embarrassing places.
1945 Exchange all such pairs following BP
1946 with any potentially-embarrassing characters that follow them.
1947 Potentially-embarrassing characters are / and *
1948 (because a backslash-newline inside a comment delimiter
1949 would cause it not to be recognized). */
1955 register U_CHAR *p = bp;
1956 register int count = 0;
1958 /* First count the backslash-newline pairs here. */
1964 else if (p[1] == '\r' && p[2] == '\n')
1972 /* What follows the backslash-newlines is not embarrassing. */
1974 if (count == 0 || (*p != '/' && *p != '*'))
1977 /* Copy all potentially embarrassing characters
1978 that follow the backslash-newline pairs
1979 down to where the pairs originally started. */
1981 while (*p == '*' || *p == '/')
1984 /* Now write the same number of pairs after the embarrassing chars. */
1985 while (count-- > 0) {
1991 /* Like newline_fix but for use within a directive-name.
1992 Move any backslash-newlines up past any following symbol constituents. */
1995 name_newline_fix (bp)
1998 register U_CHAR *p = bp;
1999 register int count = 0;
2001 /* First count the backslash-newline pairs here. */
2006 else if (p[1] == '\r' && p[2] == '\n')
2014 /* What follows the backslash-newlines is not embarrassing. */
2016 if (count == 0 || !is_idchar[*p])
2019 /* Copy all potentially embarrassing characters
2020 that follow the backslash-newline pairs
2021 down to where the pairs originally started. */
2023 while (is_idchar[*p])
2026 /* Now write the same number of pairs after the embarrassing chars. */
2027 while (count-- > 0) {
2033 /* Look for lint commands in comments.
2035 When we come in here, ibp points into a comment. Limit is as one expects.
2036 scan within the comment -- it should start, after lwsp, with a lint command.
2037 If so that command is returned as a (constant) string.
2039 Upon return, any arg will be pointed to with argstart and will be
2040 arglen long. Note that we don't parse that arg since it will just
2041 be printed out again.
2045 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2046 register U_CHAR *ibp;
2047 register U_CHAR *limit;
2048 U_CHAR **argstart; /* point to command arg */
2049 int *arglen, *cmdlen; /* how long they are */
2052 register U_CHAR *numptr; /* temp for arg parsing */
2056 SKIP_WHITE_SPACE (ibp);
2058 if (ibp >= limit) return NULL;
2060 linsize = limit - ibp;
2062 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2063 if ((linsize >= 10) && !strncmp (ibp, "NOTREACHED", 10)) {
2065 return "NOTREACHED";
2067 if ((linsize >= 8) && !strncmp (ibp, "ARGSUSED", 8)) {
2071 if ((linsize >= 11) && !strncmp (ibp, "LINTLIBRARY", 8)) {
2073 return "LINTLIBRARY";
2075 if ((linsize >= 7) && !strncmp (ibp, "VARARGS", 7)) {
2077 ibp += 7; linsize -= 7;
2078 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2080 /* OK, read a number */
2081 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2083 *arglen = numptr - *argstart;
2090 * The main loop of the program.
2092 * Read characters from the input stack, transferring them to the
2095 * Macros are expanded and push levels on the input stack.
2096 * At the end of such a level it is popped off and we keep reading.
2097 * At the end of any other kind of level, we return.
2098 * #-directives are handled, except within macros.
2100 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2101 * and insert them when appropriate. This is set while scanning macro
2102 * arguments before substitution. It is zero when scanning for final output.
2103 * There are three types of Newline markers:
2104 * * Newline - follows a macro name that was not expanded
2105 * because it appeared inside an expansion of the same macro.
2106 * This marker prevents future expansion of that identifier.
2107 * When the input is rescanned into the final output, these are deleted.
2108 * These are also deleted by ## concatenation.
2109 * * Newline Space (or Newline and any other whitespace character)
2110 * stands for a place that tokens must be separated or whitespace
2111 * is otherwise desirable, but where the ANSI standard specifies there
2112 * is no whitespace. This marker turns into a Space (or whichever other
2113 * whitespace char appears in the marker) in the final output,
2114 * but it turns into nothing in an argument that is stringified with #.
2115 * Such stringified arguments are the only place where the ANSI standard
2116 * specifies with precision that whitespace may not appear.
2118 * During this function, IP->bufp is kept cached in IBP for speed of access.
2119 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2120 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2121 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2122 * explicitly, and before RECACHE, since RECACHE uses OBP.
2126 rescan (op, output_marks)
2130 /* Character being scanned in main loop. */
2133 /* Length of pending accumulated identifier. */
2134 register int ident_length = 0;
2136 /* Hash code of pending accumulated identifier. */
2137 register int hash = 0;
2139 /* Current input level (&instack[indepth]). */
2142 /* Pointer for scanning input. */
2143 register U_CHAR *ibp;
2145 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2146 register U_CHAR *limit;
2148 /* Pointer for storing output. */
2149 register U_CHAR *obp;
2151 /* REDO_CHAR is nonzero if we are processing an identifier
2152 after backing up over the terminating character.
2153 Sometimes we process an identifier without backing up over
2154 the terminating character, if the terminating character
2155 is not special. Backing up is done so that the terminating character
2156 will be dispatched on again once the identifier is dealt with. */
2159 /* 1 if within an identifier inside of which a concatenation
2160 marker (Newline -) has been seen. */
2161 int concatenated = 0;
2163 /* While scanning a comment or a string constant,
2164 this records the line it started on, for error messages. */
2167 /* Line where a newline was first seen in a string constant. */
2168 int multiline_string_line = 0;
2170 /* Record position of last `real' newline. */
2171 U_CHAR *beg_of_line;
2173 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2176 do { ip->macro->type = T_MACRO; \
2177 if (ip->free_ptr) free (ip->free_ptr); \
2178 --indepth; } while (0)
2180 /* Reload `rescan's local variables that describe the current
2181 level of the input stack. */
2184 do { ip = &instack[indepth]; \
2186 limit = ip->buf + ip->length; \
2188 check_expand (op, limit - ibp); \
2190 obp = op->bufp; } while (0)
2192 if (no_output && instack[indepth].fname != 0)
2193 skip_if_group (&instack[indepth], 1);
2199 /* Our caller must always put a null after the end of
2200 the input at each input stack level. */
2213 /* Always merge lines ending with backslash-newline,
2214 even in middle of identifier. */
2217 --obp; /* remove backslash from obuf */
2220 /* Otherwise, backslash suppresses specialness of following char,
2221 so copy it here to prevent the switch from seeing it.
2222 But first get any pending identifier processed. */
2223 if (ident_length > 0)
2229 if (assertions_flag) {
2230 /* Copy #foo (bar lose) without macro expansion. */
2231 SKIP_WHITE_SPACE (ibp);
2232 while (is_idchar[*ibp])
2234 SKIP_WHITE_SPACE (ibp);
2237 skip_paren_group (ip);
2238 bcopy (ibp, obp, ip->bufp - ibp);
2239 obp += ip->bufp - ibp;
2244 /* If this is expanding a macro definition, don't recognize
2245 preprocessor directives. */
2251 /* # keyword: a # must be first nonblank char on the line */
2252 if (beg_of_line == 0)
2257 /* Scan from start of line, skipping whitespace, comments
2258 and backslash-newlines, and see if we reach this #.
2259 If not, this # is not special. */
2262 if (is_hor_space[*bp])
2264 else if (*bp == '\\' && bp[1] == '\n')
2266 else if (*bp == '/' && bp[1] == '*') {
2268 while (!(*bp == '*' && bp[1] == '/'))
2272 else if ((cplusplus || objc) && *bp == '/' && bp[1] == '/') {
2274 while (*bp++ != '\n') ;
2282 /* This # can start a directive. */
2284 --obp; /* Don't copy the '#' */
2288 if (! handle_directive (ip, op)) {
2292 /* Not a known directive: treat it as ordinary text.
2293 IP, OP, IBP, etc. have not been changed. */
2294 if (no_output && instack[indepth].fname) {
2295 /* If not generating expanded output,
2296 what we do with ordinary text is skip it.
2297 Discard everything until next # directive. */
2298 skip_if_group (&instack[indepth], 1);
2303 ++obp; /* Copy the '#' after all */
2309 /* A # directive has been successfully processed. */
2310 /* If not generating expanded output, ignore everything until
2311 next # directive. */
2312 if (no_output && instack[indepth].fname)
2313 skip_if_group (&instack[indepth], 1);
2319 case '\"': /* skip quoted string */
2321 /* A single quoted string is treated like a double -- some
2322 programs (e.g., troff) are perverse this way */
2327 start_line = ip->lineno;
2329 /* Skip ahead to a matching quote. */
2334 if (ip->macro != 0) {
2335 /* try harder: this string crosses a macro expansion boundary */
2341 error_with_line (line_for_error (start_line),
2342 "unterminated string or character constant");
2343 error_with_line (multiline_string_line,
2344 "possible real start of unterminated constant");
2345 multiline_string_line = 0;
2354 /* Traditionally, end of line ends a string constant with no error.
2355 So exit the loop and record the new line. */
2360 if (pedantic || c == '\'') {
2361 error_with_line (line_for_error (start_line),
2362 "unterminated string or character constant");
2365 if (multiline_string_line == 0)
2366 multiline_string_line = ip->lineno - 1;
2373 /* Backslash newline is replaced by nothing at all,
2374 but keep the line counts correct. */
2379 /* ANSI stupidly requires that in \\ the second \
2380 is *not* prevented from combining with a newline. */
2381 while (*ibp == '\\' && ibp[1] == '\n') {
2400 if (*ibp == '\\' && ibp[1] == '\n')
2404 && !((cplusplus || objc) && *ibp == '/'))
2412 /* C++ style comment... */
2413 start_line = ip->lineno;
2415 --ibp; /* Back over the slash */
2418 /* Comments are equivalent to spaces. */
2419 if (! put_out_comments)
2422 /* must fake up a comment here */
2427 U_CHAR *before_bp = ibp+2;
2429 while (ibp < limit) {
2430 if (*ibp++ == '\n') {
2432 if (put_out_comments) {
2433 bcopy (before_bp, obp, ibp - before_bp);
2434 obp += ibp - before_bp;
2443 /* Ordinary C comment. Skip it, optionally copying it to output. */
2445 start_line = ip->lineno;
2447 ++ibp; /* Skip the star. */
2449 /* If this cpp is for lint, we peek inside the comments: */
2453 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2455 if (lintcmd != NULL) {
2456 /* I believe it is always safe to emit this newline: */
2458 bcopy ("#pragma lint ", obp, 13);
2460 bcopy (lintcmd, obp, cmdlen);
2465 bcopy (argbp, obp, arglen);
2469 /* OK, now bring us back to the state we were in before we entered
2470 this branch. We need #line b/c the newline for the pragma
2471 could fuck things up. */
2472 output_line_command (ip, op, 0, same_file);
2473 *(obp++) = ' '; /* just in case, if comments are copied thru */
2478 /* Comments are equivalent to spaces.
2479 Note that we already output the slash; we might not want it.
2480 For -traditional, a comment is equivalent to nothing. */
2481 if (! put_out_comments) {
2491 U_CHAR *before_bp = ibp;
2493 while (ibp < limit) {
2496 if (warn_comments && ibp < limit && *ibp == '*')
2497 warning("`/*' within comment");
2500 if (*ibp == '\\' && ibp[1] == '\n')
2502 if (ibp >= limit || *ibp == '/')
2507 /* Copy the newline into the output buffer, in order to
2508 avoid the pain of a #line every time a multiline comment
2510 if (!put_out_comments)
2518 error_with_line (line_for_error (start_line),
2519 "unterminated comment");
2522 if (put_out_comments) {
2523 bcopy (before_bp, obp, ibp - before_bp);
2524 obp += ibp - before_bp;
2531 if (!dollars_in_ident)
2535 case '0': case '1': case '2': case '3': case '4':
2536 case '5': case '6': case '7': case '8': case '9':
2537 /* If digit is not part of identifier, it starts a number,
2538 which means that following letters are not an identifier.
2539 "0x5" does not refer to an identifier "x5".
2540 So copy all alphanumerics that follow without accumulating
2541 as an identifier. Periods also, for sake of "3.e7". */
2543 if (ident_length == 0) {
2544 while (ibp < limit) {
2545 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
2550 /* ".." terminates a preprocessing number. This is useless for C
2551 code but useful for preprocessing other things. */
2552 if (!isalnum (c) && (c != '.' || *ibp == '.') && c != '_') {
2557 /* A sign can be part of a preprocessing number
2558 if it follows an e. */
2559 if (c == 'e' || c == 'E') {
2560 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
2564 if (ibp < limit && (*ibp == '+' || *ibp == '-')) {
2566 /* But traditional C does not let the token go past the sign. */
2577 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2578 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2579 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
2580 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2582 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2583 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
2584 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
2585 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2589 /* Compute step of hash function, to avoid a proc call on every token */
2590 hash = HASHSTEP (hash, c);
2594 /* If reprocessing a macro expansion, newline is a special marker. */
2595 if (ip->macro != 0) {
2596 /* Newline White is a "funny space" to separate tokens that are
2597 supposed to be separate but without space between.
2598 Here White means any whitespace character.
2599 Newline - marks a recursive macro use that is not
2600 supposed to be expandable. */
2603 /* Newline - inhibits expansion of preceding token.
2604 If expanding a macro arg, we keep the newline -.
2605 In final output, it is deleted. */
2606 if (! concatenated) {
2611 if (!output_marks) {
2614 /* If expanding a macro arg, keep the newline -. */
2617 } else if (is_space[*ibp]) {
2618 /* Newline Space does not prevent expansion of preceding token
2619 so expand the preceding token and then come back. */
2620 if (ident_length > 0)
2623 /* If generating final output, newline space makes a space. */
2624 if (!output_marks) {
2626 /* And Newline Newline makes a newline, so count it. */
2627 if (obp[-1] == '\n')
2630 /* If expanding a macro arg, keep the newline space.
2631 If the arg gets stringified, newline space makes nothing. */
2634 } else abort (); /* Newline followed by something random? */
2638 /* If there is a pending identifier, handle it and come back here. */
2639 if (ident_length > 0)
2644 /* Update the line counts and output a #line if necessary. */
2647 if (ip->lineno != op->lineno) {
2649 output_line_command (ip, op, 1, same_file);
2650 check_expand (op, ip->length - (ip->bufp - ip->buf));
2655 /* Come here either after (1) a null character that is part of the input
2656 or (2) at the end of the input, because there is a null there. */
2659 /* Our input really contains a null character. */
2662 /* At end of a macro-expansion level, pop it and read next level. */
2663 if (ip->macro != 0) {
2666 /* If traditional, and we have an identifier that ends here,
2667 process it now, so we get the right error for recursion. */
2668 if (traditional && ident_length
2669 && ! is_idchar[*instack[indepth - 1].bufp]) {
2678 /* If we don't have a pending identifier,
2679 return at end of input. */
2680 if (ident_length == 0) {
2688 /* If we do have a pending identifier, just consider this null
2689 a special character and arrange to dispatch on it again.
2690 The second time, IDENT_LENGTH will be zero so we will return. */
2696 /* Handle the case of a character such as /, ', " or null
2697 seen following an identifier. Back over it so that
2698 after the identifier is processed the special char
2699 will be dispatched on again. */
2709 if (ident_length > 0) {
2710 register HASHNODE *hp;
2712 /* We have just seen an identifier end. If it's a macro, expand it.
2714 IDENT_LENGTH is the length of the identifier
2715 and HASH is its hash code.
2717 The identifier has already been copied to the output,
2718 so if it is a macro we must remove it.
2720 If REDO_CHAR is 0, the char that terminated the identifier
2721 has been skipped in the output and the input.
2722 OBP-IDENT_LENGTH-1 points to the identifier.
2723 If the identifier is a macro, we must back over the terminator.
2725 If REDO_CHAR is 1, the terminating char has already been
2726 backed over. OBP-IDENT_LENGTH points to the identifier. */
2728 if (!pcp_outfile || pcp_inside_if) {
2730 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
2733 if (hp->length == ident_length) {
2734 int obufp_before_macroname;
2735 int op_lineno_before_macroname;
2736 register int i = ident_length;
2737 register U_CHAR *p = hp->name;
2738 register U_CHAR *q = obp - i;
2744 do { /* All this to avoid a strncmp () */
2749 /* We found a use of a macro name.
2750 see if the context shows it is a macro call. */
2752 /* Back up over terminating character if not already done. */
2758 /* Save this as a displacement from the beginning of the output
2759 buffer. We can not save this as a position in the output
2760 buffer, because it may get realloc'ed by RECACHE. */
2761 obufp_before_macroname = (obp - op->buf) - ident_length;
2762 op_lineno_before_macroname = op->lineno;
2764 if (hp->type == T_PCSTRING) {
2765 pcstring_used (hp); /* Mark the definition of this key
2766 as needed, ensuring that it
2768 break; /* Exit loop, since the key cannot have a
2769 definition any longer. */
2772 /* Record whether the macro is disabled. */
2773 disabled = hp->type == T_DISABLED;
2775 /* This looks like a macro ref, but if the macro was disabled,
2776 just copy its name and put in a marker if requested. */
2780 /* This error check caught useful cases such as
2781 #define foo(x,y) bar(x(y,0), y)
2784 error ("recursive use of macro `%s'", hp->name);
2788 check_expand (op, limit - ibp + 2);
2795 /* If macro wants an arglist, verify that a '(' follows.
2796 first skip all whitespace, copying it to the output
2797 after the macro name. Then, if there is no '(',
2798 decide this is not a macro call and leave things that way. */
2799 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
2800 && hp->value.defn->nargs >= 0)
2802 U_CHAR *old_ibp = ibp;
2803 U_CHAR *old_obp = obp;
2804 int old_iln = ip->lineno;
2805 int old_oln = op->lineno;
2808 /* Scan forward over whitespace, copying it to the output. */
2809 if (ibp == limit && ip->macro != 0) {
2814 old_iln = ip->lineno;
2815 old_oln = op->lineno;
2817 /* A comment: copy it unchanged or discard it. */
2818 else if (*ibp == '/' && ibp+1 != limit && ibp[1] == '*') {
2819 if (put_out_comments) {
2822 } else if (! traditional) {
2826 while (ibp + 1 != limit
2827 && !(ibp[0] == '*' && ibp[1] == '/')) {
2828 /* We need not worry about newline-marks,
2829 since they are never found in comments. */
2831 /* Newline in a file. Count it. */
2835 if (put_out_comments)
2841 if (put_out_comments) {
2846 else if (is_space[*ibp]) {
2848 if (ibp[-1] == '\n') {
2849 if (ip->macro == 0) {
2850 /* Newline in a file. Count it. */
2853 } else if (!output_marks) {
2854 /* A newline mark, and we don't want marks
2855 in the output. If it is newline-hyphen,
2856 discard it entirely. Otherwise, it is
2857 newline-whitechar, so keep the whitechar. */
2867 /* A newline mark; copy both chars to the output. */
2875 /* It isn't a macro call.
2876 Put back the space that we just skipped. */
2879 ip->lineno = old_iln;
2880 op->lineno = old_oln;
2881 /* Exit the for loop. */
2886 /* This is now known to be a macro call.
2887 Discard the macro name from the output,
2888 along with any following whitespace just copied. */
2889 obp = op->buf + obufp_before_macroname;
2890 op->lineno = op_lineno_before_macroname;
2892 /* Expand the macro, reading arguments as needed,
2893 and push the expansion on the input stack. */
2896 macroexpand (hp, op);
2898 /* Reexamine input stack, since macroexpand has pushed
2899 a new level on it. */
2906 } /* End hash-table-search loop */
2908 ident_length = hash = 0; /* Stop collecting identifier */
2911 } /* End if (ident_length > 0) */
2913 } /* End per-char loop */
2915 /* Come here to return -- but first give an error message
2916 if there was an unterminated successful conditional. */
2918 if (if_stack != ip->if_stack) {
2920 switch (if_stack->type) {
2937 error_with_line (line_for_error (if_stack->lineno),
2938 "unterminated `#%s' conditional", str);
2940 if_stack = ip->if_stack;
2944 * Rescan a string into a temporary buffer and return the result
2945 * as a FILE_BUF. Note this function returns a struct, not a pointer.
2947 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
2948 * and insert such markers when appropriate. See `rescan' for details.
2949 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
2950 * before substitution; it is 0 for other uses.
2953 expand_to_temp_buffer (buf, limit, output_marks, assertions)
2954 U_CHAR *buf, *limit;
2955 int output_marks, assertions;
2957 register FILE_BUF *ip;
2959 int length = limit - buf;
2961 int odepth = indepth;
2962 int save_assertions_flag = assertions_flag;
2964 assertions_flag = assertions;
2969 /* Set up the input on the input stack. */
2971 buf1 = (U_CHAR *) alloca (length + 1);
2973 register U_CHAR *p1 = buf;
2974 register U_CHAR *p2 = buf1;
2981 /* Set up to receive the output. */
2983 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
2984 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
2989 CHECK_DEPTH ({return obuf;});
2993 ip = &instack[indepth];
2995 ip->nominal_fname = 0;
2996 ip->system_header_p = 0;
2999 ip->length = length;
3000 ip->buf = ip->bufp = buf1;
3001 ip->if_stack = if_stack;
3003 ip->lineno = obuf.lineno = 1;
3005 /* Scan the input, create the output. */
3006 rescan (&obuf, output_marks);
3008 /* Pop input stack to original state. */
3011 if (indepth != odepth)
3014 /* Record the output. */
3015 obuf.length = obuf.bufp - obuf.buf;
3017 assertions_flag = save_assertions_flag;
3022 * Process a # directive. Expects IP->bufp to point after the '#', as in
3023 * `#define foo bar'. Passes to the command handler
3024 * (do_define, do_include, etc.): the addresses of the 1st and
3025 * last chars of the command (starting immediately after the #
3026 * keyword), plus op and the keyword table pointer. If the command
3027 * contains comments it is copied into a temporary buffer sans comments
3028 * and the temporary buffer is passed to the command handler instead.
3029 * Likewise for backslash-newlines.
3031 * Returns nonzero if this was a known # directive.
3032 * Otherwise, returns zero, without advancing the input pointer.
3036 handle_directive (ip, op)
3039 register U_CHAR *bp, *cp;
3040 register struct directive *kt;
3041 register int ident_length;
3044 /* Nonzero means we must copy the entire command
3045 to get rid of comments or backslash-newlines. */
3046 int copy_command = 0;
3048 U_CHAR *ident, *after_ident;
3052 /* Record where the directive started. do_xifdef needs this. */
3053 directive_start = bp - 1;
3055 /* Skip whitespace and \-newline. */
3057 if (is_hor_space[*bp]) {
3058 if ((*bp == '\f' || *bp == '\v') && pedantic)
3059 pedwarn ("%s in preprocessing directive",
3060 *bp == '\f' ? "formfeed" : "vertical tab");
3062 } else if (*bp == '/' && bp[1] == '*') {
3064 skip_to_end_of_comment (ip, &ip->lineno, 0);
3066 } else if (*bp == '\\' && bp[1] == '\n') {
3067 bp += 2; ip->lineno++;
3071 /* Now find end of directive name.
3072 If we encounter a backslash-newline, exchange it with any following
3073 symbol-constituents so that we end up with a contiguous name. */
3080 if (*cp == '\\' && cp[1] == '\n')
3081 name_newline_fix (cp);
3087 ident_length = cp - bp;
3091 /* A line of just `#' becomes blank. */
3093 if (ident_length == 0 && *after_ident == '\n') {
3094 ip->bufp = after_ident;
3098 if (ident_length == 0 || !is_idstart[*ident]) {
3100 while (is_idchar[*p]) {
3101 if (*p < '0' || *p > '9')
3105 /* Handle # followed by a line number. */
3106 if (p != ident && !is_idchar[*p]) {
3107 static struct directive line_directive_table[] = {
3108 { 4, do_line, "line", T_LINE},
3111 pedwarn ("`#' followed by integer");
3112 after_ident = ident;
3113 kt = line_directive_table;
3117 /* Avoid error for `###' and similar cases unless -pedantic. */
3119 while (*p == '#' || is_hor_space[*p]) p++;
3121 if (pedantic && !lang_asm)
3122 warning ("invalid preprocessor directive");
3128 error ("invalid preprocessor directive name");
3134 * Decode the keyword and call the appropriate expansion
3135 * routine, after moving the input pointer up to the next line.
3137 for (kt = directive_table; kt->length > 0; kt++) {
3138 if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length)) {
3139 register U_CHAR *buf;
3140 register U_CHAR *limit;
3143 int *already_output = 0;
3145 /* Nonzero means do not delete comments within the directive.
3146 #define needs this when -traditional. */
3151 limit = ip->buf + ip->length;
3153 keep_comments = traditional && kt->traditional_comments;
3154 /* #import is defined only in Objective C, or when on the NeXT. */
3155 if (kt->type == T_IMPORT && !(objc || lookup ("__NeXT__", -1, -1)))
3158 /* Find the end of this command (first newline not backslashed
3159 and not in a string or comment).
3160 Set COPY_COMMAND if the command must be copied
3161 (it contains a backslash-newline or a comment). */
3163 buf = bp = after_ident;
3164 while (bp < limit) {
3165 register U_CHAR c = *bp++;
3179 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_command, &unterminated);
3180 /* Don't bother calling the directive if we already got an error
3181 message due to unterminated string. Skip everything and pretend
3182 we called the directive. */
3185 /* Traditional preprocessing permits unterminated strings. */
3194 /* <...> is special for #include. */
3196 if (!kt->angle_brackets)
3198 while (*bp && *bp != '>') bp++;
3202 if (*bp == '\\' && bp[1] == '\n')
3205 || ((cplusplus || objc) && *bp == '/')) {
3206 U_CHAR *obp = bp - 1;
3208 skip_to_end_of_comment (ip, &ip->lineno, 0);
3210 /* No need to copy the command because of a comment at the end;
3211 just don't include the comment in the directive. */
3212 if (bp == limit || *bp == '\n') {
3216 /* Don't remove the comments if -traditional. */
3217 if (! keep_comments)
3225 pedwarn ("%s in preprocessing directive",
3226 c == '\f' ? "formfeed" : "vertical tab");
3230 --bp; /* Point to the newline */
3238 resume_p = ip->bufp;
3239 /* BP is the end of the directive.
3240 RESUME_P is the next interesting data after the directive.
3241 A comment may come between. */
3243 /* If a directive should be copied through, and -E was given,
3244 pass it through before removing comments. */
3245 if (!no_output && kt->pass_thru && put_out_comments) {
3248 /* Output directive name. */
3249 check_expand (op, kt->length + 2);
3250 /* Make sure # is at the start of a line */
3251 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3256 bcopy (kt->name, op->bufp, kt->length);
3257 op->bufp += kt->length;
3259 /* Output arguments. */
3261 check_expand (op, len);
3262 bcopy (buf, op->bufp, len);
3264 /* Take account of any (escaped) newlines just output. */
3266 if (buf[len] == '\n')
3269 already_output = &junk;
3270 } /* Don't we need a newline or #line? */
3273 register U_CHAR *xp = buf;
3274 /* Need to copy entire command into temp buffer before dispatching */
3276 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
3280 /* Copy to the new buffer, deleting comments
3281 and backslash-newlines (and whitespace surrounding the latter). */
3284 register U_CHAR c = *xp++;
3289 abort (); /* A bare newline should never part of the line. */
3292 /* <...> is special for #include. */
3294 if (!kt->angle_brackets)
3296 while (xp < bp && c != '>') {
3298 if (c == '\\' && xp < bp && *xp == '\n')
3309 if (cp != buf && is_space[cp[-1]]) {
3310 while (cp != buf && is_space[cp[-1]]) cp--;
3312 SKIP_WHITE_SPACE (xp);
3313 } else if (is_space[*xp]) {
3315 SKIP_WHITE_SPACE (xp);
3323 register U_CHAR *bp1
3324 = skip_quoted_string (xp - 1, limit, ip->lineno, 0, 0, 0);
3338 || ((cplusplus || objc) && *xp == '/')) {
3340 /* If we already copied the command through,
3341 already_output != 0 prevents outputting comment now. */
3342 skip_to_end_of_comment (ip, already_output, 0);
3344 while (xp != ip->bufp)
3346 /* Delete or replace the slash. */
3347 else if (traditional)
3356 /* Null-terminate the copy. */
3362 ip->bufp = resume_p;
3364 /* Some directives should be written out for cc1 to process,
3365 just as if they were not defined. And sometimes we're copying
3366 definitions through. */
3368 if (!no_output && already_output == 0
3370 || (kt->type == T_DEFINE
3371 && (dump_macros == dump_names
3372 || dump_macros == dump_definitions)))) {
3375 /* Output directive name. */
3376 check_expand (op, kt->length + 1);
3378 bcopy (kt->name, op->bufp, kt->length);
3379 op->bufp += kt->length;
3381 if (kt->pass_thru || dump_macros == dump_definitions) {
3382 /* Output arguments. */
3384 check_expand (op, len);
3385 bcopy (buf, op->bufp, len);
3388 } /* Don't we need a newline or #line? */
3390 /* Call the appropriate command handler. buf now points to
3391 either the appropriate place in the input buffer, or to
3392 the temp buffer if it was necessary to make one. cp
3393 points to the first char after the contents of the (possibly
3394 copied) command, in either case. */
3395 (*kt->func) (buf, cp, op, kt);
3396 check_expand (op, ip->length - (ip->bufp - ip->buf));
3402 /* It is deliberate that we don't warn about undefined directives.
3403 That is the responsibility of cc1. */
3407 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3408 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3412 * expand things like __FILE__. Place the expansion into the output
3413 * buffer *without* rescanning.
3417 special_symbol (hp, op)
3424 FILE_BUF *ip = NULL;
3426 int paren = 0; /* For special `defined' keyword */
3428 if (pcp_outfile && pcp_inside_if
3429 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
3430 error ("Predefined macro `%s' used inside `#if' during precompilation",
3433 for (i = indepth; i >= 0; i--)
3434 if (instack[i].fname != NULL) {
3439 error ("cccp error: not in any file?!");
3440 return; /* the show must go on */
3448 if (hp->type == T_FILE)
3449 string = ip->nominal_fname;
3451 string = instack[0].nominal_fname;
3455 buf = (char *) alloca (3 + strlen (string));
3456 sprintf (buf, "\"%s\"", string);
3464 case T_INCLUDE_LEVEL:
3466 for (i = indepth; i >= 0; i--)
3467 if (instack[i].fname != NULL)
3470 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
3471 sprintf (buf, "%d", true_indepth - 1);
3475 buf = (char *) alloca (3 + strlen (version_string));
3476 sprintf (buf, "\"%s\"", version_string);
3480 buf = (char *) alloca (3 + strlen (SIZE_TYPE));
3481 sprintf (buf, "%s", SIZE_TYPE);
3484 case T_PTRDIFF_TYPE:
3485 buf = (char *) alloca (3 + strlen (PTRDIFF_TYPE));
3486 sprintf (buf, "%s", PTRDIFF_TYPE);
3490 buf = (char *) alloca (3 + strlen (WCHAR_TYPE));
3491 sprintf (buf, "%s", WCHAR_TYPE);
3495 buf = (char *) alloca (4 * sizeof (int));
3496 sprintf (buf, "%d", hp->value.ival);
3497 if (pcp_inside_if && pcp_outfile)
3498 /* Output a precondition for this macro use */
3499 fprintf (pcp_outfile, "#define %s %d\n", hp->name, hp->value.ival);
3503 buf = (char *) alloca (10);
3504 sprintf (buf, "%d", ip->lineno);
3509 buf = (char *) alloca (20);
3510 if (hp->type == T_DATE)
3511 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3512 timebuf->tm_mday, timebuf->tm_year + 1900);
3514 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3518 case T_SPEC_DEFINED:
3519 buf = " 0 "; /* Assume symbol is not defined */
3520 ip = &instack[indepth];
3521 SKIP_WHITE_SPACE (ip->bufp);
3522 if (*ip->bufp == '(') {
3524 ip->bufp++; /* Skip over the paren */
3525 SKIP_WHITE_SPACE (ip->bufp);
3528 if (!is_idstart[*ip->bufp])
3530 if (hp = lookup (ip->bufp, -1, -1)) {
3531 if (pcp_outfile && pcp_inside_if
3532 && hp->value.defn->predefined)
3533 /* Output a precondition for this macro use. */
3534 fprintf (pcp_outfile, "#define %s\n", hp->name);
3538 if (pcp_outfile && pcp_inside_if) {
3539 /* Output a precondition for this macro use */
3540 U_CHAR *cp = ip->bufp;
3541 fprintf (pcp_outfile, "#undef ");
3542 while (is_idchar[*cp]) /* Ick! */
3543 fputc (*cp++, pcp_outfile);
3544 putc ('\n', pcp_outfile);
3546 while (is_idchar[*ip->bufp])
3548 SKIP_WHITE_SPACE (ip->bufp);
3550 if (*ip->bufp != ')')
3558 error ("`defined' without an identifier");
3562 error ("cccp error: invalid special hash type"); /* time for gdb */
3566 check_expand (op, len);
3567 bcopy (buf, op->bufp, len);
3574 /* Routines to handle #directives */
3576 /* Handle #include and #import.
3577 This function expects to see "fname" or <fname> on the input. */
3580 do_include (buf, limit, op, keyword)
3581 U_CHAR *buf, *limit;
3583 struct directive *keyword;
3585 int importing = (keyword->type == T_IMPORT);
3586 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3587 static int import_warning = 0;
3588 char *fname; /* Dynamically allocated fname buffer */
3591 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
3593 struct file_name_list *search_start = include; /* Chain of dirs to search */
3594 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3595 struct file_name_list *searchptr;
3598 int f; /* file number */
3600 int retried = 0; /* Have already tried macro
3601 expanding the include line*/
3602 FILE_BUF trybuf; /* It got expanded into here */
3603 int system_header_p = 0; /* 0 for "...", 1 for <...> */
3608 f= -1; /* JF we iz paranoid! */
3610 if (importing && warn_import
3611 && !instack[indepth].system_header_p && !import_warning) {
3613 warning ("using `#import' is not recommended");
3614 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
3615 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
3616 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
3617 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
3618 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
3619 fprintf (stderr, " ... <real contents of file> ...\n");
3620 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
3621 fprintf (stderr, "Then users can use `#include' any number of times.\n");
3622 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
3623 fprintf (stderr, "when it is equipped with such a conditional.\n");
3629 SKIP_WHITE_SPACE (fbeg);
3630 /* Discard trailing whitespace so we can easily see
3631 if we have parsed all the significant chars we were given. */
3632 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
3637 while (fend != limit && *fend != '\"')
3639 if (*fend == '\"' && fend + 1 == limit) {
3642 /* We have "filename". Figure out directory this source
3643 file is coming from and put it on the front of the list. */
3645 /* If -I- was specified, don't search current dir, only spec'd ones. */
3646 if (ignore_srcdir) break;
3648 for (fp = &instack[indepth]; fp >= instack; fp--)
3653 if ((nam = fp->nominal_fname) != NULL) {
3654 /* Found a named file. Figure out dir of the file,
3655 and put it in front of the search list. */
3656 dsp[0].next = search_start;
3659 ep = rindex (nam, '/');
3661 ep = rindex (nam, ']');
3662 if (ep == NULL) ep = rindex (nam, '>');
3663 if (ep == NULL) ep = rindex (nam, ':');
3664 if (ep != NULL) ep++;
3668 dsp[0].fname = (char *) alloca (n + 1);
3669 strncpy (dsp[0].fname, nam, n);
3670 dsp[0].fname[n] = '\0';
3671 if (n > max_include_len) max_include_len = n;
3673 dsp[0].fname = 0; /* Current directory */
3684 while (fend != limit && *fend != '>') fend++;
3685 if (*fend == '>' && fend + 1 == limit) {
3686 system_header_p = 1;
3687 /* If -I-, start with the first -I dir after the -I-. */
3688 if (first_bracket_include)
3689 search_start = first_bracket_include;
3698 error ("`#import' expects \"fname\" or <fname>");
3700 error ("`#include' expects \"fname\" or <fname>");
3703 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
3704 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
3705 bcopy (trybuf.buf, buf, trybuf.bufp - trybuf.buf);
3706 limit = buf + (trybuf.bufp - trybuf.buf);
3713 /* For #include_next, skip in the search path
3714 past the dir in which the containing file was found. */
3717 for (fp = &instack[indepth]; fp >= instack; fp--)
3718 if (fp->fname != NULL) {
3719 /* fp->dir is null if the containing file was specified
3720 with an absolute file name. In that case, don't skip anything. */
3722 search_start = fp->dir->next;
3728 /* Allocate this permanently, because it gets stored in the definitions
3730 fname = (char *) xmalloc (max_include_len + flen + 2);
3731 /* + 2 above for slash and terminating null. */
3733 /* See if we already included this file and we can tell in advance
3734 (from a #ifndef around its contents last time)
3735 that there is no need to include it again. */
3737 struct file_name_list *l = all_include_files;
3738 strncpy (fname, fbeg, flen);
3740 for (; l; l = l->next)
3741 if (! strcmp (fname, l->fname)
3743 && lookup (l->control_macro, -1, -1))
3747 /* If specified file name is absolute, just open it. */
3750 strncpy (fname, fbeg, flen);
3753 f = lookup_import (fname);
3755 f = open (fname, O_RDONLY, 0666);
3757 return 0; /* Already included this file */
3759 /* Search directory path, trying to open the file.
3760 Copy each filename tried into FNAME. */
3762 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
3763 if (searchptr->fname) {
3764 /* The empty string in a search path is ignored.
3765 This makes it possible to turn off entirely
3766 a standard piece of the list. */
3767 if (searchptr->fname[0] == 0)
3769 strcpy (fname, searchptr->fname);
3770 strcat (fname, "/");
3771 fname[strlen (fname) + flen] = 0;
3775 strncat (fname, fbeg, flen);
3777 /* Change this 1/2 Unix 1/2 VMS file specification into a
3778 full VMS file specification */
3779 if (searchptr->fname && (searchptr->fname[0] != 0)) {
3780 /* Fix up the filename */
3781 hack_vms_include_specification (fname);
3783 /* This is a normal VMS filespec, so use it unchanged. */
3784 strncpy (fname, fbeg, flen);
3789 f = lookup_import (fname);
3791 f = open (fname, O_RDONLY, 0666);
3793 return 0; /* Already included this file */
3800 /* A file that was not found. */
3802 strncpy (fname, fbeg, flen);
3804 error_from_errno (fname);
3806 /* For -M, add this file to the dependencies. */
3807 if (print_deps > (system_header_p || (system_include_depth > 0))) {
3808 /* Break the line before this. */
3809 deps_output ("", 0);
3811 /* If it was requested as a system header file,
3812 then assume it belongs in the first place to look for such. */
3813 if (system_header_p) {
3814 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
3815 if (searchptr->fname) {
3816 if (searchptr->fname[0] == 0)
3818 deps_output (searchptr->fname, 0);
3819 deps_output ("/", 0);
3824 /* Otherwise, omit the directory, as if the file existed
3825 in the directory with the source. */
3826 deps_output (fbeg, flen);
3827 deps_output (" ", 0);
3832 /* Check to see if this include file is a once-only include file.
3835 struct file_name_list* ptr;
3837 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
3838 if (!strcmp (ptr->fname, fname)) {
3840 return 0; /* This file was once'd. */
3844 for (ptr = all_include_files; ptr; ptr = ptr->next) {
3845 if (!strcmp (ptr->fname, fname))
3846 break; /* This file was included before. */
3850 /* This is the first time for this file. */
3851 /* Add it to list of files included. */
3853 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
3854 ptr->control_macro = 0;
3855 ptr->next = all_include_files;
3856 all_include_files = ptr;
3857 ptr->fname = savestring (fname);
3859 /* For -M, add this file to the dependencies. */
3860 if (print_deps > (system_header_p || (system_include_depth > 0))) {
3861 deps_output ("", 0);
3862 deps_output (fname, 0);
3863 deps_output (" ", 0);
3867 /* Handle -H option. */
3868 if (print_include_names)
3869 fprintf (stderr, "%s\n", fname);
3871 if (system_header_p)
3872 system_include_depth++;
3874 /* Actually process the file. */
3875 add_import (f, fname); /* Record file on "seen" list for #import. */
3877 pcftry = (char *) alloca (strlen (fname) + 30);
3885 sprintf (pcftry, "%s%d", fname, pcfnum++);
3887 pcf = open (pcftry, O_RDONLY, 0666);
3893 if (bcmp (&stat_f.st_ino, &s.st_ino, sizeof (s.st_ino))
3894 || stat_f.st_dev != s.st_dev)
3896 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
3897 /* Don't need it any more. */
3902 /* Don't need it at all. */
3907 } while (pcf != -1 && !pcfbuf);
3909 /* Actually process the file */
3911 pcfname = xmalloc (strlen (pcftry) + 1);
3912 strcpy (pcfname, pcftry);
3913 pcfinclude (pcfbuf, pcfbuflimit, fname, op);
3916 finclude (f, fname, op, system_header_p, searchptr);
3918 if (system_header_p)
3919 system_include_depth--;
3924 /* Process the contents of include file FNAME, already open on descriptor F,
3926 SYSTEM_HEADER_P is 1 if this file was specified using <...>.
3927 DIRPTR is the link in the dir path through which this file was found,
3928 or 0 if the file name was absolute. */
3931 finclude (f, fname, op, system_header_p, dirptr)
3935 int system_header_p;
3936 struct file_name_list *dirptr;
3941 FILE_BUF *fp; /* For input stack frame */
3942 int missing_newline = 0;
3944 CHECK_DEPTH (return;);
3946 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
3947 goto nope; /* Impossible? */
3949 fp = &instack[indepth + 1];
3950 bzero (fp, sizeof (FILE_BUF));
3951 fp->nominal_fname = fp->fname = fname;
3954 fp->if_stack = if_stack;
3955 fp->system_header_p = system_header_p;
3958 if (S_ISREG (st_mode)) {
3959 fp->buf = (U_CHAR *) alloca (st_size + 2);
3962 /* Read the file contents, knowing that st_size is an upper bound
3963 on the number of bytes we can read. */
3964 while (st_size > 0) {
3965 i = read (f, fp->buf + fp->length, st_size);
3975 /* Cannot count its file size before reading.
3976 First read the entire file into heap and
3977 copy them into buffer on stack. */
3984 basep = (U_CHAR *) xmalloc (bsize + 2);
3988 i = read (f, bufp, bsize - st_size);
3990 goto nope; /* error! */
3992 break; /* End of file */
3995 if (bsize == st_size) { /* Buffer is full! */
3997 basep = (U_CHAR *) xrealloc (basep, bsize + 2);
3998 bufp = basep + st_size; /* May have moved */
4001 fp->buf = (U_CHAR *) alloca (st_size + 2);
4003 bcopy (basep, fp->buf, st_size);
4004 fp->length = st_size;
4008 /* Close descriptor now, so nesting does not use lots of descriptors. */
4014 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
4015 /* Backslash-newline at end is not good enough. */
4016 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
4017 fp->buf[fp->length++] = '\n';
4018 missing_newline = 1;
4020 fp->buf[fp->length] = '\0';
4023 input_file_stack_tick++;
4025 output_line_command (fp, op, 0, enter_file);
4028 if (pedantic && missing_newline)
4029 pedwarn ("file does not end in newline");
4032 input_file_stack_tick++;
4033 output_line_command (&instack[indepth], op, 0, leave_file);
4038 perror_with_name (fname);
4042 /* Record that inclusion of the file named FILE
4043 should be controlled by the macro named MACRO_NAME.
4044 This means that trying to include the file again
4045 will do something if that macro is defined. */
4048 record_control_macro (file, macro_name)
4052 struct file_name_list *new;
4054 for (new = all_include_files; new; new = new->next) {
4055 if (!strcmp (new->fname, file)) {
4056 new->control_macro = macro_name;
4061 /* If the file is not in all_include_files, something's wrong. */
4065 /* Maintain and search list of included files, for #import. */
4067 #define IMPORT_HASH_SIZE 31
4069 struct import_file {
4073 struct import_file *next;
4076 /* Hash table of files already included with #include or #import. */
4078 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
4080 /* Hash a file name for import_hash_table. */
4088 while (*f) val += *f++;
4089 return (val%IMPORT_HASH_SIZE);
4092 /* Search for file FILENAME in import_hash_table.
4093 Return -2 if found, either a matching name or a matching inode.
4094 Otherwise, open the file and return a file descriptor if successful
4095 or -1 if unsuccessful. */
4098 lookup_import (filename)
4101 struct import_file *i;
4107 hashval = import_hash (filename);
4109 /* Attempt to find file in list of already included files */
4110 i = import_hash_table[hashval];
4113 if (!strcmp (filename, i->name))
4114 return -2; /* return found */
4117 /* Open it and try a match on inode/dev */
4118 fd = open (filename, O_RDONLY, 0666);
4122 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
4123 i = import_hash_table[h];
4125 /* Compare the inode and the device.
4126 Supposedly on some systems the inode is not a scalar. */
4127 if (!bcmp (&i->inode, &sb.st_ino, sizeof (sb.st_ino))
4128 && i->dev == sb.st_dev) {
4130 return -2; /* return found */
4135 return fd; /* Not found, return open file */
4138 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
4141 add_import (fd, fname)
4145 struct import_file *i;
4149 hashval = import_hash (fname);
4151 i = (struct import_file *)xmalloc (sizeof (struct import_file));
4152 i->name = (char *)xmalloc (strlen (fname)+1);
4153 strcpy (i->name, fname);
4154 bcopy (&sb.st_ino, &i->inode, sizeof (sb.st_ino));
4156 i->next = import_hash_table[hashval];
4157 import_hash_table[hashval] = i;
4160 /* Load the specified precompiled header into core, and verify its
4161 preconditions. PCF indicates the file descriptor to read, which must
4162 be a regular file. FNAME indicates the file name of the original
4163 header. *LIMIT will be set to an address one past the end of the file.
4164 If the preconditions of the file are not satisfied, the buffer is
4165 freed and we return 0. If the preconditions are satisfied, return
4166 the address of the buffer following the preconditions. The buffer, in
4167 this case, should never be freed because various pieces of it will
4168 be referred to until all precompiled strings are output at the end of
4172 check_precompiled (pcf, fname, limit)
4188 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
4191 if (S_ISREG (st_mode))
4193 buf = xmalloc (st_size + 2);
4196 i = read (pcf, buf + length, st_size);
4208 if (length > 0 && buf[length-1] != '\n')
4209 buf[length++] = '\n';
4212 *limit = buf + length;
4214 /* File is in core. Check the preconditions. */
4215 if (!check_preconditions (buf))
4217 for (cp = buf; *cp; cp++)
4220 fprintf (stderr, "Using preinclude %s\n", fname);
4226 fprintf (stderr, "Cannot use preinclude %s\n", fname);
4232 /* PREC (null terminated) points to the preconditions of a
4233 precompiled header. These are a series of #define and #undef
4234 lines which must match the current contents of the hash
4237 check_preconditions (prec)
4244 lineend = (char *) index (prec, '\n');
4246 if (*prec++ != '#') {
4247 error ("Bad format encountered while reading precompiled file");
4250 if (!strncmp (prec, "define", 6)) {
4254 mdef = create_definition (prec, lineend, 0);
4259 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
4260 || (hp->type != T_MACRO && hp->type != T_CONST)
4261 || (hp->type == T_MACRO
4262 && !compare_defs (mdef.defn, hp->value.defn)
4263 && (mdef.defn->length != 2
4264 || mdef.defn->expansion[0] != '\n'
4265 || mdef.defn->expansion[1] != ' ')))
4267 } else if (!strncmp (prec, "undef", 5)) {
4272 while (is_hor_space[*prec])
4275 while (is_idchar[*prec])
4279 if (lookup (name, len, -1))
4282 error ("Bad format encountered while reading precompiled file");
4287 /* They all passed successfully */
4291 /* Process the main body of a precompiled file. BUF points to the
4292 string section of the file, following the preconditions. LIMIT is one
4293 character past the end. NAME is the name of the file being read
4294 in. OP is the main output buffer */
4296 pcfinclude (buf, limit, name, op)
4297 U_CHAR *buf, *limit, *name;
4304 /* First in the file comes 4 bytes indicating the number of strings, */
4305 /* in network byte order. (MSB first). */
4307 nstrings = (nstrings << 8) | *cp++;
4308 nstrings = (nstrings << 8) | *cp++;
4309 nstrings = (nstrings << 8) | *cp++;
4311 /* Looping over each string... */
4312 while (nstrings--) {
4313 U_CHAR *string_start;
4314 U_CHAR *endofthiskey;
4318 /* Each string starts with a STRINGDEF structure (str), followed */
4319 /* by the text of the string (string_start) */
4321 /* First skip to a longword boundary */
4323 cp += 4 - ((int)cp & 3);
4325 /* Now get the string. */
4326 str = (STRINGDEF *) cp;
4327 string_start = cp += sizeof (STRINGDEF);
4329 for (; *cp; cp++) /* skip the string */
4332 /* We need to macro expand the string here to ensure that the
4333 proper definition environment is in place. If it were only
4334 expanded when we find out it is needed, macros necessary for
4335 its proper expansion might have had their definitions changed. */
4336 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
4337 /* Lineno is already set in the precompiled file */
4338 str->contents = tmpbuf.buf;
4339 str->len = tmpbuf.length;
4341 str->filename = name;
4342 str->output_mark = outbuf.bufp - outbuf.buf;
4345 *stringlist_tailp = str;
4346 stringlist_tailp = &str->chain;
4348 /* Next comes a fourbyte number indicating the number of keys */
4349 /* for this string. */
4351 nkeys = (nkeys << 8) | *cp++;
4352 nkeys = (nkeys << 8) | *cp++;
4353 nkeys = (nkeys << 8) | *cp++;
4355 /* If this number is -1, then the string is mandatory. */
4359 /* Otherwise, for each key, */
4360 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
4361 KEYDEF *kp = (KEYDEF *) cp;
4364 /* It starts with a KEYDEF structure */
4365 cp += sizeof (KEYDEF);
4367 /* Find the end of the key. At the end of this for loop we
4368 advance CP to the start of the next key using this variable. */
4369 endofthiskey = cp + strlen (cp);
4372 /* Expand the key, and enter it into the hash table. */
4373 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
4374 tmpbuf.bufp = tmpbuf.buf;
4376 while (is_hor_space[*tmpbuf.bufp])
4378 if (!is_idstart[*tmpbuf.bufp]
4379 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
4384 hp = lookup (tmpbuf.bufp, -1, -1);
4387 install (tmpbuf.bufp, -1, T_PCSTRING, (int) kp, -1);
4389 else if (hp->type == T_PCSTRING) {
4390 kp->chain = hp->value.keydef;
4391 hp->value.keydef = kp;
4397 /* This output_line_command serves to switch us back to the current
4398 input file in case some of these strings get output (which will
4399 result in line commands for the header file being output). */
4400 output_line_command (&instack[indepth], op, 0, enter_file);
4403 /* Called from rescan when it hits a key for strings. Mark them all */
4404 /* used and clean up. */
4411 for (kp = hp->value.keydef; kp; kp = kp->chain)
4412 kp->str->writeflag = 1;
4416 /* Write the output, interspersing precompiled strings in their */
4417 /* appropriate places. */
4421 STRINGDEF *next_string;
4422 U_CHAR *cur_buf_loc;
4423 int line_command_len = 80;
4424 char *line_command = xmalloc (line_command_len);
4427 /* In each run through the loop, either cur_buf_loc == */
4428 /* next_string_loc, in which case we print a series of strings, or */
4429 /* it is less than next_string_loc, in which case we write some of */
4431 cur_buf_loc = outbuf.buf;
4432 next_string = stringlist;
4434 while (cur_buf_loc < outbuf.bufp || next_string) {
4436 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
4437 if (next_string->writeflag) {
4438 len = strlen (next_string->filename);
4439 if (len > line_command_len)
4440 line_command = xrealloc (line_command,
4441 line_command_len *= 2);
4442 sprintf (line_command, "\n# %d \"%s\"\n",
4443 next_string->lineno, next_string->filename);
4444 write (fileno (stdout), line_command,
4445 strlen (line_command));
4446 write (fileno (stdout),
4447 next_string->contents, next_string->len);
4449 next_string = next_string->chain;
4453 ? (next_string->output_mark
4454 - (cur_buf_loc - outbuf.buf))
4455 : outbuf.bufp - cur_buf_loc);
4457 write (fileno (stdout), cur_buf_loc, len);
4463 /* Pass a directive through to the output file.
4464 BUF points to the contents of the directive, as a contiguous string.
4465 LIMIT points to the first character past the end of the directive.
4466 KEYWORD is the keyword-table entry for the directive. */
4469 pass_thru_directive (buf, limit, op, keyword)
4470 U_CHAR *buf, *limit;
4472 struct directive *keyword;
4474 register unsigned keyword_length = keyword->length;
4476 check_expand (op, 1 + keyword_length + (limit - buf));
4478 bcopy (keyword->name, op->bufp, keyword_length);
4479 op->bufp += keyword_length;
4480 if (limit != buf && buf[0] != ' ')
4482 bcopy (buf, op->bufp, limit - buf);
4483 op->bufp += (limit - buf);
4487 /* The arglist structure is built by do_define to tell
4488 collect_definition where the argument names begin. That
4489 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
4490 would contain pointers to the strings x, y, and z.
4491 Collect_definition would then build a DEFINITION node,
4492 with reflist nodes pointing to the places x, y, and z had
4493 appeared. So the arglist is just convenience data passed
4494 between these two routines. It is not kept around after
4495 the current #define has been processed and entered into the
4499 struct arglist *next;
4505 /* Create a DEFINITION node from a #define directive. Arguments are
4506 as for do_define. */
4508 create_definition (buf, limit, op)
4509 U_CHAR *buf, *limit;
4512 U_CHAR *bp; /* temp ptr into input buffer */
4513 U_CHAR *symname; /* remember where symbol name starts */
4514 int sym_length; /* and how long it is */
4515 int line = instack[indepth].lineno;
4516 char *file = instack[indepth].nominal_fname;
4519 int arglengths = 0; /* Accumulate lengths of arg names
4520 plus number of args. */
4525 while (is_hor_space[*bp])
4528 symname = bp; /* remember where it starts */
4529 sym_length = check_macro_name (bp, "macro");
4532 /* Lossage will occur if identifiers or control keywords are broken
4533 across lines using backslash. This is not the right place to take
4537 struct arglist *arg_ptrs = NULL;
4540 bp++; /* skip '(' */
4541 SKIP_WHITE_SPACE (bp);
4543 /* Loop over macro argument names. */
4544 while (*bp != ')') {
4545 struct arglist *temp;
4547 temp = (struct arglist *) alloca (sizeof (struct arglist));
4549 temp->next = arg_ptrs;
4550 temp->argno = argno++;
4553 if (!is_idstart[*bp])
4554 pedwarn ("parameter name starts with a digit in `#define'");
4556 /* Find the end of the arg name. */
4557 while (is_idchar[*bp]) {
4560 temp->length = bp - temp->name;
4561 arglengths += temp->length + 2;
4562 SKIP_WHITE_SPACE (bp);
4563 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
4564 error ("badly punctuated parameter list in `#define'");
4569 SKIP_WHITE_SPACE (bp);
4572 error ("unterminated parameter list in `#define'");
4576 struct arglist *otemp;
4578 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
4579 if (temp->length == otemp->length &&
4580 strncmp(temp->name, otemp->name, temp->length) == 0) {
4583 name = (U_CHAR *) alloca(temp->length + 1);
4584 (void) strncpy(name, temp->name, temp->length);
4585 name[temp->length] = '\0';
4586 error ("duplicate argument name `%s' in `#define'", name);
4592 ++bp; /* skip paren */
4593 /* Skip exactly one space or tab if any. */
4594 if (bp < limit && (*bp == ' ' || *bp == '\t')) ++bp;
4595 /* now everything from bp before limit is the definition. */
4596 defn = collect_expansion (bp, limit, argno, arg_ptrs);
4598 /* Now set defn->args.argnames to the result of concatenating
4599 the argument names in reverse order
4600 with comma-space between them. */
4601 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
4603 struct arglist *temp;
4605 for (temp = arg_ptrs; temp; temp = temp->next) {
4606 bcopy (temp->name, &defn->args.argnames[i], temp->length);
4608 if (temp->next != 0) {
4609 defn->args.argnames[i++] = ',';
4610 defn->args.argnames[i++] = ' ';
4613 defn->args.argnames[i] = 0;
4616 /* simple expansion or empty definition; gobble it */
4617 if (is_hor_space[*bp])
4618 ++bp; /* skip exactly one blank/tab char */
4619 /* now everything from bp before limit is the definition. */
4620 defn = collect_expansion (bp, limit, -1, 0);
4621 defn->args.argnames = (U_CHAR *) "";
4627 /* OP is null if this is a predefinition */
4628 defn->predefined = !op;
4630 mdef.symnam = symname;
4631 mdef.symlen = sym_length;
4640 /* Process a #define command.
4641 BUF points to the contents of the #define command, as a contiguous string.
4642 LIMIT points to the first character past the end of the definition.
4643 KEYWORD is the keyword-table entry for #define. */
4646 do_define (buf, limit, op, keyword)
4647 U_CHAR *buf, *limit;
4649 struct directive *keyword;
4654 /* If this is a precompiler run (with -pcp) pass thru #define commands. */
4655 if (pcp_outfile && op)
4656 pass_thru_directive (buf, limit, op, keyword);
4658 mdef = create_definition (buf, limit, op);
4662 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
4666 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
4668 /* Redefining a precompiled key is ok. */
4669 if (hp->type == T_PCSTRING)
4671 /* Redefining a macro is ok if the definitions are the same. */
4672 else if (hp->type == T_MACRO)
4673 ok = ! compare_defs (mdef.defn, hp->value.defn);
4674 /* Redefining a constant is ok with -D. */
4675 else if (hp->type == T_CONST)
4676 ok = ! done_initializing;
4677 /* Print the warning if it's not ok. */
4679 U_CHAR *msg; /* what pain... */
4681 /* If we are passing through #define and #undef directives, do
4682 that for this re-definition now. */
4683 if (debug_output && op)
4684 pass_thru_directive (buf, limit, op, keyword);
4686 msg = (U_CHAR *) alloca (mdef.symlen + 22);
4688 bcopy (mdef.symnam, msg + 1, mdef.symlen);
4689 strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
4691 if (hp->type == T_MACRO)
4692 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
4693 "this is the location of the previous definition");
4695 /* Replace the old definition. */
4697 hp->value.defn = mdef.defn;
4699 /* If we are passing through #define and #undef directives, do
4700 that for this new definition now. */
4701 if (debug_output && op)
4702 pass_thru_directive (buf, limit, op, keyword);
4703 install (mdef.symnam, mdef.symlen, T_MACRO, mdef.defn, hashcode);
4714 /* Check a purported macro name SYMNAME, and yield its length.
4715 USAGE is the kind of name this is intended for. */
4718 check_macro_name (symname, usage)
4725 for (p = symname; is_idchar[*p]; p++)
4727 sym_length = p - symname;
4728 if (sym_length == 0)
4729 error ("invalid %s name", usage);
4730 else if (!is_idstart[*symname]) {
4731 U_CHAR *msg; /* what pain... */
4732 msg = (U_CHAR *) alloca (sym_length + 1);
4733 bcopy (symname, msg, sym_length);
4734 msg[sym_length] = 0;
4735 error ("invalid %s name `%s'", usage, msg);
4737 if (! strncmp (symname, "defined", 7) && sym_length == 7)
4738 error ("invalid %s name `defined'", usage);
4744 * return zero if two DEFINITIONs are isomorphic
4747 compare_defs (d1, d2)
4748 DEFINITION *d1, *d2;
4750 register struct reflist *a1, *a2;
4751 register U_CHAR *p1 = d1->expansion;
4752 register U_CHAR *p2 = d2->expansion;
4755 if (d1->nargs != d2->nargs)
4757 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
4759 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
4760 a1 = a1->next, a2 = a2->next) {
4761 if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
4762 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
4763 || a1->argno != a2->argno
4764 || a1->stringify != a2->stringify
4765 || a1->raw_before != a2->raw_before
4766 || a1->raw_after != a2->raw_after)
4774 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
4775 p2, d2->length - (p2 - d2->expansion), 1))
4780 /* Return 1 if two parts of two macro definitions are effectively different.
4781 One of the parts starts at BEG1 and has LEN1 chars;
4782 the other has LEN2 chars at BEG2.
4783 Any sequence of whitespace matches any other sequence of whitespace.
4784 FIRST means these parts are the first of a macro definition;
4785 so ignore leading whitespace entirely.
4786 LAST means these parts are the last of a macro definition;
4787 so ignore trailing whitespace entirely. */
4790 comp_def_part (first, beg1, len1, beg2, len2, last)
4792 U_CHAR *beg1, *beg2;
4796 register U_CHAR *end1 = beg1 + len1;
4797 register U_CHAR *end2 = beg2 + len2;
4799 while (beg1 != end1 && is_space[*beg1]) beg1++;
4800 while (beg2 != end2 && is_space[*beg2]) beg2++;
4803 while (beg1 != end1 && is_space[end1[-1]]) end1--;
4804 while (beg2 != end2 && is_space[end2[-1]]) end2--;
4806 while (beg1 != end1 && beg2 != end2) {
4807 if (is_space[*beg1] && is_space[*beg2]) {
4808 while (beg1 != end1 && is_space[*beg1]) beg1++;
4809 while (beg2 != end2 && is_space[*beg2]) beg2++;
4810 } else if (*beg1 == *beg2) {
4814 return (beg1 != end1) || (beg2 != end2);
4817 /* Read a replacement list for a macro with parameters.
4818 Build the DEFINITION structure.
4819 Reads characters of text starting at BUF until END.
4820 ARGLIST specifies the formal parameters to look for
4821 in the text of the definition; NARGS is the number of args
4822 in that list, or -1 for a macro name that wants no argument list.
4823 MACRONAME is the macro name itself (so we can avoid recursive expansion)
4824 and NAMELEN is its length in characters.
4826 Note that comments and backslash-newlines have already been deleted
4827 from the argument. */
4829 /* Leading and trailing Space, Tab, etc. are converted to markers
4830 Newline Space, Newline Tab, etc.
4831 Newline Space makes a space in the final output
4832 but is discarded if stringified. (Newline Tab is similar but
4833 makes a Tab instead.)
4835 If there is no trailing whitespace, a Newline Space is added at the end
4836 to prevent concatenation that would be contrary to the standard. */
4839 collect_expansion (buf, end, nargs, arglist)
4842 struct arglist *arglist;
4845 register U_CHAR *p, *limit, *lastp, *exp_p;
4846 struct reflist *endpat = NULL;
4847 /* Pointer to first nonspace after last ## seen. */
4849 /* Pointer to first nonspace after last single-# seen. */
4850 U_CHAR *stringify = 0;
4852 int expected_delimiter = '\0';
4854 /* Scan thru the replacement list, ignoring comments and quoted
4855 strings, picking up on the macro calls. It does a linear search
4856 thru the arg list on every potential symbol. Profiling might say
4857 that something smarter should happen. */
4862 /* Find the beginning of the trailing whitespace. */
4863 /* Find end of leading whitespace. */
4866 while (p < limit && is_space[limit[-1]]) limit--;
4867 while (p < limit && is_space[*p]) p++;
4869 /* Allocate space for the text in the macro definition.
4870 Leading and trailing whitespace chars need 2 bytes each.
4871 Each other input char may or may not need 1 byte,
4872 so this is an upper bound.
4873 The extra 2 are for invented trailing newline-marker and final null. */
4874 maxsize = (sizeof (DEFINITION)
4875 + 2 * (end - limit) + 2 * (p - buf)
4877 defn = (DEFINITION *) xcalloc (1, maxsize);
4879 defn->nargs = nargs;
4880 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
4885 /* Convert leading whitespace to Newline-markers. */
4886 while (p < limit && is_space[*p]) {
4891 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
4892 error ("`##' at start of macro definition");
4896 /* Process the main body of the definition. */
4898 int skipped_arg = 0;
4899 register U_CHAR c = *p++;
4907 if (expected_delimiter != '\0') {
4908 if (c == expected_delimiter)
4909 expected_delimiter = '\0';
4911 expected_delimiter = c;
4914 /* Special hack: if a \# is written in the #define
4915 include a # in the definition. This is useless for C code
4916 but useful for preprocessing other things. */
4919 /* \# quotes a # even outside of strings. */
4920 if (p < limit && *p == '#' && !expected_delimiter) {
4923 } else if (p < limit && expected_delimiter) {
4924 /* In a string, backslash goes through
4925 and makes next char ordinary. */
4931 /* # is ordinary inside a string. */
4932 if (expected_delimiter)
4934 if (p < limit && *p == '#') {
4935 /* ##: concatenate preceding and following tokens. */
4936 /* Take out the first #, discard preceding whitespace. */
4938 while (exp_p > lastp && is_hor_space[exp_p[-1]])
4940 /* Skip the second #. */
4942 /* Discard following whitespace. */
4943 SKIP_WHITE_SPACE (p);
4946 error ("`##' at end of macro definition");
4948 /* Single #: stringify following argument ref.
4949 Don't leave the # in the expansion. */
4951 SKIP_WHITE_SPACE (p);
4952 if (p == limit || ! is_idstart[*p] || nargs <= 0)
4953 error ("`#' operator is not followed by a macro argument name");
4960 /* In -traditional mode, recognize arguments inside strings and
4961 and character constants, and ignore special properties of #.
4962 Arguments inside strings are considered "stringified", but no
4963 extra quote marks are supplied. */
4967 if (expected_delimiter != '\0') {
4968 if (c == expected_delimiter)
4969 expected_delimiter = '\0';
4971 expected_delimiter = c;
4975 /* Backslash quotes delimiters and itself, but not macro args. */
4976 if (expected_delimiter != 0 && p < limit
4977 && (*p == expected_delimiter || *p == '\\')) {
4984 if (expected_delimiter != '\0') /* No comments inside strings. */
4987 /* If we find a comment that wasn't removed by handle_directive,
4988 this must be -traditional. So replace the comment with
4992 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
4995 /* Mark this as a concatenation-point, as if it had been ##. */
5003 /* Handle the start of a symbol. */
5004 if (is_idchar[c] && nargs > 0) {
5005 U_CHAR *id_beg = p - 1;
5009 while (p != limit && is_idchar[*p]) p++;
5010 id_len = p - id_beg;
5012 if (is_idstart[c]) {
5013 register struct arglist *arg;
5015 for (arg = arglist; arg != NULL; arg = arg->next) {
5016 struct reflist *tpat;
5018 if (arg->name[0] == c
5019 && arg->length == id_len
5020 && strncmp (arg->name, id_beg, id_len) == 0) {
5021 if (expected_delimiter && warn_stringify) {
5023 warning ("macro argument `%.*s' is stringified.",
5026 warning ("macro arg `%.*s' would be stringified with -traditional.",
5030 /* If ANSI, don't actually substitute inside a string. */
5031 if (!traditional && expected_delimiter)
5033 /* make a pat node for this arg and append it to the end of
5035 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
5037 tpat->raw_before = concat == id_beg;
5038 tpat->raw_after = 0;
5039 tpat->stringify = (traditional ? expected_delimiter != '\0'
5040 : stringify == id_beg);
5043 defn->pattern = tpat;
5045 endpat->next = tpat;
5048 tpat->argno = arg->argno;
5049 tpat->nchars = exp_p - lastp;
5051 register U_CHAR *p1 = p;
5052 SKIP_WHITE_SPACE (p1);
5053 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
5054 tpat->raw_after = 1;
5056 lastp = exp_p; /* place to start copying from next time */
5063 /* If this was not a macro arg, copy it into the expansion. */
5064 if (! skipped_arg) {
5065 register U_CHAR *lim1 = p;
5069 if (stringify == id_beg)
5070 error ("`#' operator should be followed by a macro argument name");
5076 /* Convert trailing whitespace to Newline-markers. */
5077 while (limit < end && is_space[*limit]) {
5079 *exp_p++ = *limit++;
5081 } else if (!traditional) {
5082 /* There is no trailing whitespace, so invent some. */
5089 defn->length = exp_p - defn->expansion;
5091 /* Crash now if we overrun the allocated size. */
5092 if (defn->length + 1 > maxsize)
5096 /* This isn't worth the time it takes. */
5097 /* give back excess storage */
5098 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
5105 do_assert (buf, limit, op, keyword)
5106 U_CHAR *buf, *limit;
5108 struct directive *keyword;
5110 U_CHAR *bp; /* temp ptr into input buffer */
5111 U_CHAR *symname; /* remember where symbol name starts */
5112 int sym_length; /* and how long it is */
5113 struct arglist *tokens = NULL;
5115 if (pedantic && done_initializing && !instack[indepth].system_header_p)
5116 pedwarn ("ANSI C does not allow `#assert'");
5120 while (is_hor_space[*bp])
5123 symname = bp; /* remember where it starts */
5124 sym_length = check_macro_name (bp, "assertion");
5126 /* #define doesn't do this, but we should. */
5127 SKIP_WHITE_SPACE (bp);
5129 /* Lossage will occur if identifiers or control tokens are broken
5130 across lines using backslash. This is not the right place to take
5134 error ("missing token-sequence in `#assert'");
5141 bp++; /* skip '(' */
5142 SKIP_WHITE_SPACE (bp);
5144 tokens = read_token_list (&bp, limit, &error_flag);
5148 error ("empty token-sequence in `#assert'");
5152 ++bp; /* skip paren */
5153 SKIP_WHITE_SPACE (bp);
5156 /* If this name isn't already an assertion name, make it one.
5157 Error if it was already in use in some other way. */
5160 ASSERTION_HASHNODE *hp;
5161 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
5162 struct tokenlist_list *value
5163 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
5165 hp = assertion_lookup (symname, sym_length, hashcode);
5167 if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
5168 error ("`defined' redefined as assertion");
5169 hp = assertion_install (symname, sym_length, hashcode);
5172 /* Add the spec'd token-sequence to the list of such. */
5173 value->tokens = tokens;
5174 value->next = hp->value;
5182 do_unassert (buf, limit, op, keyword)
5183 U_CHAR *buf, *limit;
5185 struct directive *keyword;
5187 U_CHAR *bp; /* temp ptr into input buffer */
5188 U_CHAR *symname; /* remember where symbol name starts */
5189 int sym_length; /* and how long it is */
5191 struct arglist *tokens = NULL;
5192 int tokens_specified = 0;
5194 if (pedantic && done_initializing && !instack[indepth].system_header_p)
5195 pedwarn ("ANSI C does not allow `#unassert'");
5199 while (is_hor_space[*bp])
5202 symname = bp; /* remember where it starts */
5203 sym_length = check_macro_name (bp, "assertion");
5205 /* #define doesn't do this, but we should. */
5206 SKIP_WHITE_SPACE (bp);
5208 /* Lossage will occur if identifiers or control tokens are broken
5209 across lines using backslash. This is not the right place to take
5215 bp++; /* skip '(' */
5216 SKIP_WHITE_SPACE (bp);
5218 tokens = read_token_list (&bp, limit, &error_flag);
5222 error ("empty token list in `#unassert'");
5226 tokens_specified = 1;
5228 ++bp; /* skip paren */
5229 SKIP_WHITE_SPACE (bp);
5233 ASSERTION_HASHNODE *hp;
5234 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
5235 struct tokenlist_list *tail, *prev;
5237 hp = assertion_lookup (symname, sym_length, hashcode);
5241 /* If no token list was specified, then eliminate this assertion
5243 if (! tokens_specified) {
5244 struct tokenlist_list *next;
5245 for (tail = hp->value; tail; tail = next) {
5247 free_token_list (tail->tokens);
5250 delete_assertion (hp);
5252 /* If a list of tokens was given, then delete any matching list. */
5257 struct tokenlist_list *next = tail->next;
5258 if (compare_token_lists (tail->tokens, tokens)) {
5262 hp->value = tail->next;
5263 free_token_list (tail->tokens);
5276 /* Test whether there is an assertion named NAME
5277 and optionally whether it has an asserted token list TOKENS.
5278 NAME is not null terminated; its length is SYM_LENGTH.
5279 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
5282 check_assertion (name, sym_length, tokens_specified, tokens)
5285 int tokens_specified;
5286 struct arglist *tokens;
5288 ASSERTION_HASHNODE *hp;
5289 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
5291 if (pedantic && !instack[indepth].system_header_p)
5292 pedwarn ("ANSI C does not allow testing assertions");
5294 hp = assertion_lookup (name, sym_length, hashcode);
5296 /* It is not an assertion; just return false. */
5299 /* If no token list was specified, then value is 1. */
5300 if (! tokens_specified)
5304 struct tokenlist_list *tail;
5308 /* If a list of tokens was given,
5309 then succeed if the assertion records a matching list. */
5312 if (compare_token_lists (tail->tokens, tokens))
5317 /* Fail if the assertion has no matching list. */
5322 /* Compare two lists of tokens for equality including order of tokens. */
5325 compare_token_lists (l1, l2)
5326 struct arglist *l1, *l2;
5329 if (l1->length != l2->length)
5331 if (strncmp (l1->name, l2->name, l1->length))
5337 /* Succeed if both lists end at the same time. */
5341 /* Read a space-separated list of tokens ending in a close parenthesis.
5342 Return a list of strings, in the order they were written.
5343 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
5344 Parse the text starting at *BPP, and update *BPP.
5345 Don't parse beyond LIMIT. */
5347 static struct arglist *
5348 read_token_list (bpp, limit, error_flag)
5353 struct arglist *token_ptrs = 0;
5359 /* Loop over the assertion value tokens. */
5361 struct arglist *temp;
5365 /* Find the end of the token. */
5369 } else if (*bp == ')') {
5374 } else if (*bp == '"' || *bp == '\'')
5375 bp = skip_quoted_string (bp, limit, 0, 0, 0, &eofp);
5377 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
5378 && *bp != '"' && *bp != '\'' && bp != limit)
5381 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
5382 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
5383 bcopy (beg, temp->name, bp - beg);
5384 temp->name[bp - beg] = 0;
5385 temp->next = token_ptrs;
5387 temp->length = bp - beg;
5389 SKIP_WHITE_SPACE (bp);
5392 error ("unterminated token sequence in `#assert' or `#unassert'");
5399 /* We accumulated the names in reverse order.
5400 Now reverse them to get the proper order. */
5402 register struct arglist *prev = 0, *this, *next;
5403 for (this = token_ptrs; this; this = next) {
5413 free_token_list (tokens)
5414 struct arglist *tokens;
5417 struct arglist *next = tokens->next;
5418 free (tokens->name);
5425 * Install a name in the assertion hash table.
5427 * If LEN is >= 0, it is the length of the name.
5428 * Otherwise, compute the length by scanning the entire name.
5430 * If HASH is >= 0, it is the precomputed hash code.
5431 * Otherwise, compute the hash code.
5433 static ASSERTION_HASHNODE *
5434 assertion_install (name, len, hash)
5439 register ASSERTION_HASHNODE *hp;
5440 register int i, bucket;
5441 register U_CHAR *p, *q;
5443 i = sizeof (ASSERTION_HASHNODE) + len + 1;
5444 hp = (ASSERTION_HASHNODE *) xmalloc (i);
5446 hp->bucket_hdr = &assertion_hashtab[bucket];
5447 hp->next = assertion_hashtab[bucket];
5448 assertion_hashtab[bucket] = hp;
5450 if (hp->next != NULL)
5451 hp->next->prev = hp;
5454 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
5457 for (i = 0; i < len; i++)
5464 * find the most recent hash node for name name (ending with first
5465 * non-identifier char) installed by install
5467 * If LEN is >= 0, it is the length of the name.
5468 * Otherwise, compute the length by scanning the entire name.
5470 * If HASH is >= 0, it is the precomputed hash code.
5471 * Otherwise, compute the hash code.
5473 static ASSERTION_HASHNODE *
5474 assertion_lookup (name, len, hash)
5479 register U_CHAR *bp;
5480 register ASSERTION_HASHNODE *bucket;
5482 bucket = assertion_hashtab[hash];
5484 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
5486 bucket = bucket->next;
5492 delete_assertion (hp)
5493 ASSERTION_HASHNODE *hp;
5496 if (hp->prev != NULL)
5497 hp->prev->next = hp->next;
5498 if (hp->next != NULL)
5499 hp->next->prev = hp->prev;
5501 /* make sure that the bucket chain header that
5502 the deleted guy was on points to the right thing afterwards. */
5503 if (hp == *hp->bucket_hdr)
5504 *hp->bucket_hdr = hp->next;
5510 * interpret #line command. Remembers previously seen fnames
5511 * in its very own hash table.
5513 #define FNAME_HASHSIZE 37
5516 do_line (buf, limit, op, keyword)
5517 U_CHAR *buf, *limit;
5519 struct directive *keyword;
5521 register U_CHAR *bp;
5522 FILE_BUF *ip = &instack[indepth];
5525 enum file_change_code file_change = same_file;
5527 /* Expand any macros. */
5528 tem = expand_to_temp_buffer (buf, limit, 0, 0);
5530 /* Point to macroexpanded line, which is null-terminated now. */
5532 SKIP_WHITE_SPACE (bp);
5534 if (!isdigit (*bp)) {
5535 error ("invalid format `#line' command");
5539 /* The Newline at the end of this line remains to be processed.
5540 To put the next line at the specified line number,
5541 we must store a line number now that is one less. */
5542 new_lineno = atoi (bp) - 1;
5544 /* skip over the line number. */
5545 while (isdigit (*bp))
5548 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
5549 if (*bp && !is_space[*bp]) {
5550 error ("invalid format `#line' command");
5555 SKIP_WHITE_SPACE (bp);
5558 static HASHNODE *fname_table[FNAME_HASHSIZE];
5559 HASHNODE *hp, **hash_bucket;
5565 while (*bp && *bp != '\"')
5568 error ("invalid format `#line' command");
5572 fname_length = bp - fname;
5575 SKIP_WHITE_SPACE (bp);
5578 file_change = enter_file;
5579 else if (*bp == '2')
5580 file_change = leave_file;
5581 else if (*bp == '3')
5582 ip->system_header_p = 1;
5584 error ("invalid format `#line' command");
5589 SKIP_WHITE_SPACE (bp);
5591 ip->system_header_p = 1;
5593 SKIP_WHITE_SPACE (bp);
5596 error ("invalid format `#line' command");
5602 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
5603 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5604 if (hp->length == fname_length &&
5605 strncmp (hp->value.cpval, fname, fname_length) == 0) {
5606 ip->nominal_fname = hp->value.cpval;
5610 /* Didn't find it; cons up a new one. */
5611 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
5612 hp->next = *hash_bucket;
5615 hp->length = fname_length;
5616 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
5617 bcopy (fname, hp->value.cpval, fname_length);
5620 error ("invalid format `#line' command");
5624 ip->lineno = new_lineno;
5625 output_line_command (ip, op, 0, file_change);
5626 check_expand (op, ip->length - (ip->bufp - ip->buf));
5631 * remove the definition of a symbol from the symbol table.
5632 * according to un*x /lib/cpp, it is not an error to undef
5633 * something that has no definitions, so it isn't one here either.
5637 do_undef (buf, limit, op, keyword)
5638 U_CHAR *buf, *limit;
5640 struct directive *keyword;
5644 U_CHAR *orig_buf = buf;
5646 /* If this is a precompiler run (with -pcp) pass thru #undef commands. */
5647 if (pcp_outfile && op)
5648 pass_thru_directive (buf, limit, op, keyword);
5650 SKIP_WHITE_SPACE (buf);
5651 sym_length = check_macro_name (buf, "macro");
5653 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
5654 /* If we are generating additional info for debugging (with -g) we
5655 need to pass through all effective #undef commands. */
5656 if (debug_output && op)
5657 pass_thru_directive (orig_buf, limit, op, keyword);
5658 if (hp->type != T_MACRO)
5659 warning ("undefining `%s'", hp->name);
5665 SKIP_WHITE_SPACE (buf);
5667 pedwarn ("garbage after `#undef' directive");
5673 * Report a fatal error detected by the program we are processing.
5674 * Use the text of the line in the error message, then terminate.
5675 * (We use error() because it prints the filename & line#.)
5679 do_error (buf, limit, op, keyword)
5680 U_CHAR *buf, *limit;
5682 struct directive *keyword;
5684 int length = limit - buf;
5685 char *copy = (char *) xmalloc (length + 1);
5686 bcopy (buf, copy, length);
5688 SKIP_WHITE_SPACE (copy);
5689 error ("#error %s", copy);
5690 exit (FAILURE_EXIT_CODE);
5696 * Report a warning detected by the program we are processing.
5697 * Use the text of the line in the warning message, then continue.
5698 * (We use error() because it prints the filename & line#.)
5702 do_warning (buf, limit, op, keyword)
5703 U_CHAR *buf, *limit;
5705 struct directive *keyword;
5707 int length = limit - buf;
5708 char *copy = (char *) xmalloc (length + 1);
5709 bcopy (buf, copy, length);
5711 SKIP_WHITE_SPACE (copy);
5712 error ("#warning %s", copy);
5716 /* Remember the name of the current file being read from so that we can
5717 avoid ever including it again. */
5723 FILE_BUF *ip = NULL;
5725 for (i = indepth; i >= 0; i--)
5726 if (instack[i].fname != NULL) {
5732 struct file_name_list *new;
5734 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
5735 new->next = dont_repeat_files;
5736 dont_repeat_files = new;
5737 new->fname = savestring (ip->fname);
5738 new->control_macro = 0;
5743 /* #ident has already been copied to the output file, so just ignore it. */
5746 do_ident (buf, limit)
5747 U_CHAR *buf, *limit;
5749 /* Allow #ident in system headers, since that's not user's fault. */
5750 if (pedantic && !instack[indepth].system_header_p)
5751 pedwarn ("ANSI C does not allow `#ident'");
5755 /* #pragma and its argument line have already been copied to the output file.
5756 Here just check for recognized pragmas. */
5759 do_pragma (buf, limit)
5760 U_CHAR *buf, *limit;
5762 while (*buf == ' ' || *buf == '\t')
5764 if (!strncmp (buf, "once", 4)) {
5765 warning ("`#pragma once' is obsolete");
5772 /* This was a fun hack, but #pragma seems to start to be useful.
5773 By failing to recognize it, we pass it through unchanged to cc1. */
5776 * the behavior of the #pragma directive is implementation defined.
5777 * this implementation defines it as follows.
5784 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
5787 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
5789 execl ("/usr/games/hack", "#pragma", 0);
5790 execl ("/usr/games/rogue", "#pragma", 0);
5791 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
5792 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
5794 fatal ("You are in a maze of twisty compiler features, all different");
5798 /* Just ignore #sccs, on systems where we define it at all. */
5804 pedwarn ("ANSI C does not allow `#sccs'");
5809 * handle #if command by
5810 * 1) inserting special `defined' keyword into the hash table
5811 * that gets turned into 0 or 1 by special_symbol (thus,
5812 * if the luser has a symbol called `defined' already, it won't
5813 * work inside the #if command)
5814 * 2) rescan the input into a temporary output buffer
5815 * 3) pass the output buffer to the yacc parser and collect a value
5816 * 4) clean up the mess left from steps 1 and 2.
5817 * 5) call conditional_skip to skip til the next #endif (etc.),
5818 * or not, depending on the value from step 3.
5822 do_if (buf, limit, op, keyword)
5823 U_CHAR *buf, *limit;
5825 struct directive *keyword;
5828 FILE_BUF *ip = &instack[indepth];
5830 value = eval_if_expression (buf, limit - buf);
5831 conditional_skip (ip, value == 0, T_IF, 0);
5836 * handle a #elif directive by not changing if_stack either.
5837 * see the comment above do_else.
5841 do_elif (buf, limit, op, keyword)
5842 U_CHAR *buf, *limit;
5844 struct directive *keyword;
5847 FILE_BUF *ip = &instack[indepth];
5849 if (if_stack == instack[indepth].if_stack) {
5850 error ("`#elif' not within a conditional");
5853 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
5854 error ("`#elif' after `#else'");
5855 fprintf (stderr, " (matches line %d", if_stack->lineno);
5856 if (if_stack->fname != NULL && ip->fname != NULL &&
5857 strcmp (if_stack->fname, ip->nominal_fname) != 0)
5858 fprintf (stderr, ", file %s", if_stack->fname);
5859 fprintf (stderr, ")\n");
5861 if_stack->type = T_ELIF;
5864 if (if_stack->if_succeeded)
5865 skip_if_group (ip, 0);
5867 value = eval_if_expression (buf, limit - buf);
5869 skip_if_group (ip, 0);
5871 ++if_stack->if_succeeded; /* continue processing input */
5872 output_line_command (ip, op, 1, same_file);
5879 * evaluate a #if expression in BUF, of length LENGTH,
5880 * then parse the result as a C expression and return the value as an int.
5883 eval_if_expression (buf, length)
5888 HASHNODE *save_defined;
5891 save_defined = install ("defined", -1, T_SPEC_DEFINED, 0, -1);
5893 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
5895 delete_macro (save_defined); /* clean up special symbol */
5897 value = parse_c_expression (temp_obuf.buf);
5899 free (temp_obuf.buf);
5905 * routine to handle ifdef/ifndef. Try to look up the symbol,
5906 * then do or don't skip to the #endif/#else/#elif depending
5907 * on what directive is actually being processed.
5911 do_xifdef (buf, limit, op, keyword)
5912 U_CHAR *buf, *limit;
5914 struct directive *keyword;
5917 FILE_BUF *ip = &instack[indepth];
5919 int start_of_file = 0;
5920 U_CHAR *control_macro = 0;
5922 /* Detect a #ifndef at start of file (not counting comments). */
5923 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
5924 U_CHAR *p = ip->buf;
5925 while (p != directive_start) {
5933 if (p != ip->bufp && *p == '*') {
5934 /* Skip this comment. */
5936 U_CHAR *save_bufp = ip->bufp;
5938 p = skip_to_end_of_comment (ip, &junk, 1);
5939 ip->bufp = save_bufp;
5946 /* If we get here, this conditional is the beginning of the file. */
5951 /* Discard leading and trailing whitespace. */
5952 SKIP_WHITE_SPACE (buf);
5953 while (limit != buf && is_hor_space[limit[-1]]) limit--;
5955 /* Find the end of the identifier at the beginning. */
5956 for (end = buf; is_idchar[*end]; end++);
5959 skip = (keyword->type == T_IFDEF);
5961 pedwarn (end == limit ? "`#%s' with no argument"
5962 : "`#%s' argument starts with punctuation",
5967 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
5968 pedwarn ("`#%s' argument starts with a digit", keyword->name);
5969 else if (end != limit && !traditional)
5970 pedwarn ("garbage at end of `#%s' argument", keyword->name);
5972 hp = lookup (buf, end-buf, -1);
5975 /* Output a precondition for this macro. */
5976 if (hp && hp->value.defn->predefined)
5977 fprintf(pcp_outfile, "#define %s\n", hp->name);
5980 fprintf(pcp_outfile, "#undef ");
5981 while (is_idchar[*cp]) /* Ick! */
5982 fputc (*cp++, pcp_outfile);
5983 putc ('\n', pcp_outfile);
5987 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
5988 if (start_of_file && !skip) {
5989 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
5990 bcopy (buf, control_macro, end - buf);
5991 control_macro[end - buf] = 0;
5995 conditional_skip (ip, skip, T_IF, control_macro);
5999 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
6000 If this is a #ifndef starting at the beginning of a file,
6001 CONTROL_MACRO is the macro name tested by the #ifndef.
6002 Otherwise, CONTROL_MACRO is 0. */
6005 conditional_skip (ip, skip, type, control_macro)
6008 enum node_type type;
6009 U_CHAR *control_macro;
6011 IF_STACK_FRAME *temp;
6013 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
6014 temp->fname = ip->nominal_fname;
6015 temp->lineno = ip->lineno;
6016 temp->next = if_stack;
6017 temp->control_macro = control_macro;
6020 if_stack->type = type;
6023 skip_if_group (ip, 0);
6026 ++if_stack->if_succeeded;
6027 output_line_command (ip, &outbuf, 1, same_file);
6032 * skip to #endif, #else, or #elif. adjust line numbers, etc.
6033 * leaves input ptr at the sharp sign found.
6034 * If ANY is nonzero, return at next directive of any sort.
6037 skip_if_group (ip, any)
6041 register U_CHAR *bp = ip->bufp, *cp;
6042 register U_CHAR *endb = ip->buf + ip->length;
6043 struct directive *kt;
6044 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
6045 U_CHAR *beg_of_line = bp;
6046 register int ident_length;
6047 U_CHAR *ident, *after_ident;
6051 case '/': /* possible comment */
6052 if (*bp == '\\' && bp[1] == '\n')
6055 || ((cplusplus || objc) && *bp == '/')) {
6057 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
6062 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno, 0, 0);
6065 /* Char after backslash loses its special meaning. */
6068 ++ip->lineno; /* But do update the line-count. */
6079 /* # keyword: a # must be first nonblank char on the line */
6080 if (beg_of_line == 0)
6082 /* Scan from start of line, skipping whitespace, comments
6083 and backslash-newlines, and see if we reach this #.
6084 If not, this # is not special. */
6087 if (is_hor_space[*bp])
6089 else if (*bp == '\\' && bp[1] == '\n')
6091 else if (*bp == '/' && bp[1] == '*') {
6093 while (!(*bp == '*' && bp[1] == '/'))
6096 } else if ((cplusplus || objc) && *bp == '/' && bp[1] == '/') {
6098 while (*bp++ != '\n') ;
6102 if (bp != ip->bufp) {
6103 bp = ip->bufp + 1; /* Reset bp to after the #. */
6107 bp = ip->bufp + 1; /* Point after the '#' */
6109 /* Skip whitespace and \-newline. */
6111 if (is_hor_space[*bp])
6113 else if (*bp == '\\' && bp[1] == '\n')
6115 else if (*bp == '/' && bp[1] == '*') {
6117 while (!(*bp == '*' && bp[1] == '/')) {
6123 } else if ((cplusplus || objc) && *bp == '/' && bp[1] == '/') {
6125 while (*bp++ != '\n') ;
6132 /* Now find end of directive name.
6133 If we encounter a backslash-newline, exchange it with any following
6134 symbol-constituents so that we end up with a contiguous name. */
6140 if (*bp == '\\' && bp[1] == '\n')
6141 name_newline_fix (bp);
6147 ident_length = bp - cp;
6151 /* A line of just `#' becomes blank. */
6153 if (ident_length == 0 && *after_ident == '\n') {
6157 if (ident_length == 0 || !is_idstart[*ident]) {
6159 while (is_idchar[*p]) {
6160 if (*p < '0' || *p > '9')
6164 /* Handle # followed by a line number. */
6165 if (p != ident && !is_idchar[*p]) {
6167 pedwarn ("`#' followed by integer");
6171 /* Avoid error for `###' and similar cases unless -pedantic. */
6173 while (*p == '#' || is_hor_space[*p]) p++;
6175 if (pedantic && !lang_asm)
6176 pedwarn ("invalid preprocessor directive");
6181 if (!lang_asm && pedantic)
6182 pedwarn ("invalid preprocessor directive name");
6186 for (kt = directive_table; kt->length >= 0; kt++) {
6187 IF_STACK_FRAME *temp;
6188 if (ident_length == kt->length
6189 && strncmp (cp, kt->name, kt->length) == 0) {
6190 /* If we are asked to return on next directive, do so now. */
6198 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
6199 temp->next = if_stack;
6201 temp->lineno = ip->lineno;
6202 temp->fname = ip->nominal_fname;
6203 temp->type = kt->type;
6207 if (pedantic && if_stack != save_if_stack)
6210 if (if_stack == instack[indepth].if_stack) {
6211 error ("`#%s' not within a conditional", kt->name);
6214 else if (if_stack == save_if_stack)
6215 return; /* found what we came for */
6217 if (kt->type != T_ENDIF) {
6218 if (if_stack->type == T_ELSE)
6219 error ("`#else' or `#elif' after `#else'");
6220 if_stack->type = kt->type;
6225 if_stack = if_stack->next;
6232 /* Don't let erroneous code go by. */
6233 if (kt->length < 0 && !lang_asm && pedantic)
6234 pedwarn ("invalid preprocessor directive name");
6238 /* after this returns, rescan will exit because ip->bufp
6239 now points to the end of the buffer.
6240 rescan is responsible for the error message also. */
6244 * handle a #else directive. Do this by just continuing processing
6245 * without changing if_stack ; this is so that the error message
6246 * for missing #endif's etc. will point to the original #if. It
6247 * is possible that something different would be better.
6251 do_else (buf, limit, op, keyword)
6252 U_CHAR *buf, *limit;
6254 struct directive *keyword;
6256 FILE_BUF *ip = &instack[indepth];
6259 SKIP_WHITE_SPACE (buf);
6261 pedwarn ("text following `#else' violates ANSI standard");
6264 if (if_stack == instack[indepth].if_stack) {
6265 error ("`#else' not within a conditional");
6268 /* #ifndef can't have its special treatment for containing the whole file
6269 if it has a #else clause. */
6270 if_stack->control_macro = 0;
6272 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6273 error ("`#else' after `#else'");
6274 fprintf (stderr, " (matches line %d", if_stack->lineno);
6275 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
6276 fprintf (stderr, ", file %s", if_stack->fname);
6277 fprintf (stderr, ")\n");
6279 if_stack->type = T_ELSE;
6282 if (if_stack->if_succeeded)
6283 skip_if_group (ip, 0);
6285 ++if_stack->if_succeeded; /* continue processing input */
6286 output_line_command (ip, op, 1, same_file);
6292 * unstack after #endif command
6296 do_endif (buf, limit, op, keyword)
6297 U_CHAR *buf, *limit;
6299 struct directive *keyword;
6302 SKIP_WHITE_SPACE (buf);
6304 pedwarn ("text following `#endif' violates ANSI standard");
6307 if (if_stack == instack[indepth].if_stack)
6308 error ("unbalanced `#endif'");
6310 IF_STACK_FRAME *temp = if_stack;
6311 if_stack = if_stack->next;
6312 if (temp->control_macro != 0) {
6313 /* This #endif matched a #ifndef at the start of the file.
6314 See if it is at the end of the file. */
6315 FILE_BUF *ip = &instack[indepth];
6316 U_CHAR *p = ip->bufp;
6317 U_CHAR *ep = ip->buf + ip->length;
6327 if (p != ep && *p == '*') {
6328 /* Skip this comment. */
6330 U_CHAR *save_bufp = ip->bufp;
6332 p = skip_to_end_of_comment (ip, &junk, 1);
6333 ip->bufp = save_bufp;
6340 /* If we get here, this #endif ends a #ifndef
6341 that contains all of the file (aside from whitespace).
6342 Arrange not to include the file again
6343 if the macro that was tested is defined. */
6345 record_control_macro (ip->fname, temp->control_macro);
6349 output_line_command (&instack[indepth], op, 1, same_file);
6354 /* When an #else or #endif is found while skipping failed conditional,
6355 if -pedantic was specified, this is called to warn about text after
6356 the command name. P points to the first char after the command name. */
6362 /* Advance P over whitespace and comments. */
6364 if (*p == '\\' && p[1] == '\n')
6366 if (is_hor_space[*p])
6368 else if (*p == '/') {
6369 if (p[1] == '\\' && p[2] == '\n')
6370 newline_fix (p + 1);
6373 /* Don't bother warning about unterminated comments
6374 since that will happen later. Just be sure to exit. */
6376 if (p[1] == '\\' && p[2] == '\n')
6377 newline_fix (p + 1);
6378 if (*p == '*' && p[1] == '/') {
6385 else if ((cplusplus || objc) && p[1] == '/') {
6387 while (*p && *p++ != '\n') ;
6391 if (*p && *p != '\n')
6392 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
6395 /* Skip a comment, assuming the input ptr immediately follows the
6396 initial slash-star. Bump *LINE_COUNTER for each newline.
6397 (The canonical line counter is &ip->lineno.)
6398 Don't use this routine (or the next one) if bumping the line
6399 counter is not sufficient to deal with newlines in the string.
6401 If NOWARN is nonzero, don't warn about slash-star inside a comment.
6402 This feature is useful when processing a comment that is going to be
6403 processed or was processed at another point in the preprocessor,
6404 to avoid a duplicate warning. */
6406 skip_to_end_of_comment (ip, line_counter, nowarn)
6407 register FILE_BUF *ip;
6408 int *line_counter; /* place to remember newlines, or NULL */
6411 register U_CHAR *limit = ip->buf + ip->length;
6412 register U_CHAR *bp = ip->bufp;
6413 FILE_BUF *op = &outbuf; /* JF */
6414 int output = put_out_comments && !line_counter;
6416 /* JF this line_counter stuff is a crock to make sure the
6417 comment is only put out once, no matter how many times
6418 the comment is skipped. It almost works */
6423 if ((cplusplus || objc) && bp[-1] == '/') {
6426 if ((*op->bufp++ = *bp++) == '\n') {
6434 while (bp < limit) {
6435 if (*bp++ == '\n') {
6444 while (bp < limit) {
6449 if (warn_comments && !nowarn && bp < limit && *bp == '*')
6450 warning ("`/*' within comment");
6453 if (line_counter != NULL)
6459 if (*bp == '\\' && bp[1] == '\n')
6475 * Skip over a quoted string. BP points to the opening quote.
6476 * Returns a pointer after the closing quote. Don't go past LIMIT.
6477 * START_LINE is the line number of the starting point (but it need
6478 * not be valid if the starting point is inside a macro expansion).
6480 * The input stack state is not changed.
6482 * If COUNT_NEWLINES is nonzero, it points to an int to increment
6483 * for each newline passed.
6485 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
6486 * if we pass a backslash-newline.
6488 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
6491 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
6492 register U_CHAR *bp;
6493 register U_CHAR *limit;
6495 int *count_newlines;
6496 int *backslash_newlines_p;
6499 register U_CHAR c, match;
6504 error_with_line (line_for_error (start_line),
6505 "unterminated string or character constant");
6512 while (*bp == '\\' && bp[1] == '\n') {
6513 if (backslash_newlines_p)
6514 *backslash_newlines_p = 1;
6519 if (*bp == '\n' && count_newlines) {
6520 if (backslash_newlines_p)
6521 *backslash_newlines_p = 1;
6525 } else if (c == '\n') {
6527 /* Unterminated strings and character constants are 'legal'. */
6528 bp--; /* Don't consume the newline. */
6533 if (match == '\'') {
6534 error_with_line (line_for_error (start_line),
6535 "unterminated character constant");
6541 if (traditional) { /* Unterminated strings are 'legal'. */
6546 /* If not traditional, then allow newlines inside strings. */
6549 } else if (c == match)
6555 /* Skip across a group of balanced parens, starting from IP->bufp.
6556 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
6558 This does not handle newlines, because it's used for the arg of #if,
6559 where there aren't any newlines. Also, backslash-newline can't appear. */
6562 skip_paren_group (ip)
6563 register FILE_BUF *ip;
6565 U_CHAR *limit = ip->buf + ip->length;
6566 U_CHAR *p = ip->bufp;
6568 int lines_dummy = 0;
6570 while (p != limit) {
6580 return ip->bufp = p;
6586 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
6594 p = skip_quoted_string (p - 1, limit, 0, 0, 0, &eofp);
6596 return ip->bufp = p;
6607 * write out a #line command, for instance, after an #include file.
6608 * If CONDITIONAL is nonzero, we can omit the #line if it would
6609 * appear to be a no-op, and we can output a few newlines instead
6610 * if we want to increase the line number by a small amount.
6611 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
6615 output_line_command (ip, op, conditional, file_change)
6618 enum file_change_code file_change;
6621 char line_cmd_buf[500];
6623 if (no_line_commands
6624 || ip->fname == NULL
6626 op->lineno = ip->lineno;
6631 if (ip->lineno == op->lineno)
6634 /* If the inherited line number is a little too small,
6635 output some newlines instead of a #line command. */
6636 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
6637 check_expand (op, 10);
6638 while (ip->lineno > op->lineno) {
6646 /* Don't output a line number of 0 if we can help it. */
6647 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
6648 && *ip->bufp == '\n') {
6653 #ifdef OUTPUT_LINE_COMMANDS
6654 sprintf (line_cmd_buf, "#line %d \"%s\"", ip->lineno, ip->nominal_fname);
6656 sprintf (line_cmd_buf, "# %d \"%s\"", ip->lineno, ip->nominal_fname);
6658 if (file_change != same_file)
6659 strcat (line_cmd_buf, file_change == enter_file ? " 1" : " 2");
6660 /* Tell cc1 if following text comes from a system header file. */
6661 if (ip->system_header_p)
6662 strcat (line_cmd_buf, " 3");
6663 len = strlen (line_cmd_buf);
6664 line_cmd_buf[len++] = '\n';
6665 check_expand (op, len + 1);
6666 if (op->bufp > op->buf && op->bufp[-1] != '\n')
6668 bcopy (line_cmd_buf, op->bufp, len);
6670 op->lineno = ip->lineno;
6673 /* This structure represents one parsed argument in a macro call.
6674 `raw' points to the argument text as written (`raw_length' is its length).
6675 `expanded' points to the argument's macro-expansion
6676 (its length is `expand_length').
6677 `stringified_length' is the length the argument would have
6679 `use_count' is the number of times this macro arg is substituted
6680 into the macro. If the actual use count exceeds 10,
6681 the value stored is 10.
6682 `free1' and `free2', if nonzero, point to blocks to be freed
6683 when the macro argument data is no longer needed. */
6686 U_CHAR *raw, *expanded;
6687 int raw_length, expand_length;
6688 int stringified_length;
6689 U_CHAR *free1, *free2;
6695 /* Expand a macro call.
6696 HP points to the symbol that is the macro being called.
6697 Put the result of expansion onto the input stack
6698 so that subsequent input by our caller will use it.
6700 If macro wants arguments, caller has already verified that
6701 an argument list follows; arguments come from the input stack. */
6704 macroexpand (hp, op)
6709 DEFINITION *defn = hp->value.defn;
6710 register U_CHAR *xbuf;
6712 int start_line = instack[indepth].lineno;
6714 CHECK_DEPTH (return;);
6716 /* it might not actually be a macro. */
6717 if (hp->type != T_MACRO) {
6718 special_symbol (hp, op);
6722 /* This macro is being used inside a #if, which means it must be */
6723 /* recorded as a precondition. */
6724 if (pcp_inside_if && pcp_outfile && defn->predefined)
6725 dump_single_macro (hp, pcp_outfile);
6727 nargs = defn->nargs;
6731 struct argdata *args;
6732 char *parse_error = 0;
6734 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
6736 for (i = 0; i < nargs; i++) {
6737 args[i].raw = args[i].expanded = (U_CHAR *) "";
6738 args[i].raw_length = args[i].expand_length
6739 = args[i].stringified_length = 0;
6740 args[i].free1 = args[i].free2 = 0;
6741 args[i].use_count = 0;
6744 /* Parse all the macro args that are supplied. I counts them.
6745 The first NARGS args are stored in ARGS.
6746 The rest are discarded. */
6749 /* Discard the open-parenthesis or comma before the next arg. */
6750 ++instack[indepth].bufp;
6752 = macarg ((i < nargs || (nargs == 0 && i == 0)) ? &args[i] : 0);
6754 error_with_line (line_for_error (start_line), parse_error);
6758 } while (*instack[indepth].bufp != ')');
6760 /* If we got one arg but it was just whitespace, call that 0 args. */
6762 register U_CHAR *bp = args[0].raw;
6763 register U_CHAR *lim = bp + args[0].raw_length;
6764 while (bp != lim && is_space[*bp]) bp++;
6769 if (nargs == 0 && i > 0)
6770 error ("arguments given to macro `%s'", hp->name);
6771 else if (i < nargs) {
6772 /* traditional C allows foo() if foo wants one argument. */
6773 if (nargs == 1 && i == 0 && traditional)
6776 error ("macro `%s' used without args", hp->name);
6778 error ("macro `%s' used with just one arg", hp->name);
6780 error ("macro `%s' used with only %d args", hp->name, i);
6781 } else if (i > nargs)
6782 error ("macro `%s' used with too many (%d) args", hp->name, i);
6784 /* Swallow the closeparen. */
6785 ++instack[indepth].bufp;
6787 /* If macro wants zero args, we parsed the arglist for checking only.
6788 Read directly from the macro definition. */
6790 xbuf = defn->expansion;
6791 xbuf_len = defn->length;
6793 register U_CHAR *exp = defn->expansion;
6794 register int offset; /* offset in expansion,
6795 copied a piece at a time */
6796 register int totlen; /* total amount of exp buffer filled so far */
6798 register struct reflist *ap;
6800 /* Macro really takes args. Compute the expansion of this call. */
6802 /* Compute length in characters of the macro's expansion.
6803 Also count number of times each arg is used. */
6804 xbuf_len = defn->length;
6805 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
6807 xbuf_len += args[ap->argno].stringified_length;
6808 else if (ap->raw_before || ap->raw_after || traditional)
6809 xbuf_len += args[ap->argno].raw_length;
6811 xbuf_len += args[ap->argno].expand_length;
6813 if (args[ap->argno].use_count < 10)
6814 args[ap->argno].use_count++;
6817 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
6819 /* Generate in XBUF the complete expansion
6820 with arguments substituted in.
6821 TOTLEN is the total size generated so far.
6822 OFFSET is the index in the definition
6823 of where we are copying from. */
6824 offset = totlen = 0;
6825 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
6826 register struct argdata *arg = &args[ap->argno];
6828 for (i = 0; i < ap->nchars; i++)
6829 xbuf[totlen++] = exp[offset++];
6831 if (ap->stringify != 0) {
6832 int arglen = arg->raw_length;
6838 && (c = arg->raw[i], is_space[c]))
6841 && (c = arg->raw[arglen - 1], is_space[c]))
6844 xbuf[totlen++] = '\"'; /* insert beginning quote */
6845 for (; i < arglen; i++) {
6848 /* Special markers Newline Space
6849 generate nothing for a stringified argument. */
6850 if (c == '\n' && arg->raw[i+1] != '\n') {
6855 /* Internal sequences of whitespace are replaced by one space
6856 except within an string or char token. */
6858 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
6860 /* Note that Newline Space does occur within whitespace
6861 sequences; consider it part of the sequence. */
6862 if (c == '\n' && is_space[arg->raw[i+1]])
6864 else if (c != '\n' && is_space[c])
6881 } else if (c == '\"' || c == '\'')
6885 /* Escape these chars */
6886 if (c == '\"' || (in_string && c == '\\'))
6887 xbuf[totlen++] = '\\';
6891 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
6896 xbuf[totlen++] = '\"'; /* insert ending quote */
6897 } else if (ap->raw_before || ap->raw_after || traditional) {
6898 U_CHAR *p1 = arg->raw;
6899 U_CHAR *l1 = p1 + arg->raw_length;
6900 if (ap->raw_before) {
6901 while (p1 != l1 && is_space[*p1]) p1++;
6902 while (p1 != l1 && is_idchar[*p1])
6903 xbuf[totlen++] = *p1++;
6904 /* Delete any no-reexpansion marker that follows
6905 an identifier at the beginning of the argument
6906 if the argument is concatenated with what precedes it. */
6907 if (p1[0] == '\n' && p1[1] == '-')
6910 if (ap->raw_after) {
6911 /* Arg is concatenated after: delete trailing whitespace,
6912 whitespace markers, and no-reexpansion markers. */
6914 if (is_space[l1[-1]]) l1--;
6915 else if (l1[-1] == '-') {
6916 U_CHAR *p2 = l1 - 1;
6917 /* If a `-' is preceded by an odd number of newlines then it
6918 and the last newline are a no-reexpansion marker. */
6919 while (p2 != p1 && p2[-1] == '\n') p2--;
6920 if ((l1 - 1 - p2) & 1) {
6928 bcopy (p1, xbuf + totlen, l1 - p1);
6931 bcopy (arg->expanded, xbuf + totlen, arg->expand_length);
6932 totlen += arg->expand_length;
6933 /* If a macro argument with newlines is used multiple times,
6934 then only expand the newlines once. This avoids creating output
6935 lines which don't correspond to any input line, which confuses
6937 if (arg->use_count > 1 && arg->newlines > 0) {
6938 /* Don't bother doing delete_newlines for subsequent
6942 = delete_newlines (arg->expanded, arg->expand_length);
6946 if (totlen > xbuf_len)
6950 /* if there is anything left of the definition
6951 after handling the arg list, copy that in too. */
6953 for (i = offset; i < defn->length; i++)
6954 xbuf[totlen++] = exp[i];
6959 for (i = 0; i < nargs; i++) {
6960 if (args[i].free1 != 0)
6961 free (args[i].free1);
6962 if (args[i].free2 != 0)
6963 free (args[i].free2);
6967 xbuf = defn->expansion;
6968 xbuf_len = defn->length;
6971 /* Now put the expansion on the input stack
6972 so our caller will commence reading from it. */
6974 register FILE_BUF *ip2;
6976 ip2 = &instack[++indepth];
6979 ip2->nominal_fname = 0;
6982 ip2->length = xbuf_len;
6984 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
6986 ip2->if_stack = if_stack;
6987 ip2->system_header_p = 0;
6989 /* Recursive macro use sometimes works traditionally.
6990 #define foo(x,y) bar(x(y,0), y)
6994 hp->type = T_DISABLED;
6999 * Parse a macro argument and store the info on it into *ARGPTR.
7000 * Return nonzero to indicate a syntax error.
7005 register struct argdata *argptr;
7007 FILE_BUF *ip = &instack[indepth];
7012 /* Try to parse as much of the argument as exists at this
7013 input stack level. */
7014 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
7015 &paren, &newlines, &comments);
7017 /* If we find the end of the argument at this level,
7018 set up *ARGPTR to point at it in the input stack. */
7019 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
7020 && bp != ip->buf + ip->length) {
7022 argptr->raw = ip->bufp;
7023 argptr->raw_length = bp - ip->bufp;
7024 argptr->newlines = newlines;
7028 /* This input stack level ends before the macro argument does.
7029 We must pop levels and keep parsing.
7030 Therefore, we must allocate a temporary buffer and copy
7031 the macro argument into it. */
7032 int bufsize = bp - ip->bufp;
7033 int extra = newlines;
7034 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
7035 int final_start = 0;
7037 bcopy (ip->bufp, buffer, bufsize);
7039 ip->lineno += newlines;
7041 while (bp == ip->buf + ip->length) {
7042 if (instack[indepth].macro == 0) {
7044 return "unterminated macro call";
7046 ip->macro->type = T_MACRO;
7048 free (ip->free_ptr);
7049 ip = &instack[--indepth];
7052 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
7053 &newlines, &comments);
7054 final_start = bufsize;
7055 bufsize += bp - ip->bufp;
7057 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
7058 bcopy (ip->bufp, buffer + bufsize - (bp - ip->bufp), bp - ip->bufp);
7060 ip->lineno += newlines;
7063 /* Now, if arg is actually wanted, record its raw form,
7064 discarding comments and duplicating newlines in whatever
7065 part of it did not come from a macro expansion.
7066 EXTRA space has been preallocated for duplicating the newlines.
7067 FINAL_START is the index of the start of that part. */
7069 argptr->raw = buffer;
7070 argptr->raw_length = bufsize;
7071 argptr->free1 = buffer;
7072 argptr->newlines = newlines;
7073 argptr->comments = comments;
7074 if ((newlines || comments) && ip->fname != 0)
7077 discard_comments (argptr->raw + final_start,
7078 argptr->raw_length - final_start,
7080 argptr->raw[argptr->raw_length] = 0;
7081 if (argptr->raw_length > bufsize + extra)
7086 /* If we are not discarding this argument,
7087 macroexpand it and compute its length as stringified.
7088 All this info goes into *ARGPTR. */
7092 register U_CHAR *buf, *lim;
7093 register int totlen;
7095 obuf = expand_to_temp_buffer (argptr->raw,
7096 argptr->raw + argptr->raw_length,
7099 argptr->expanded = obuf.buf;
7100 argptr->expand_length = obuf.length;
7101 argptr->free2 = obuf.buf;
7104 lim = buf + argptr->raw_length;
7106 while (buf != lim && is_space[*buf])
7108 while (buf != lim && is_space[lim[-1]])
7110 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
7111 while (buf != lim) {
7112 register U_CHAR c = *buf++;
7114 /* Internal sequences of whitespace are replaced by one space
7115 in most cases, but not always. So count all the whitespace
7116 in case we need to keep it all. */
7119 SKIP_ALL_WHITE_SPACE (buf);
7122 if (c == '\"' || c == '\\') /* escape these chars */
7124 else if (!isprint (c))
7127 argptr->stringified_length = totlen;
7132 /* Scan text from START (inclusive) up to LIMIT (exclusive),
7133 counting parens in *DEPTHPTR,
7134 and return if reach LIMIT
7135 or before a `)' that would make *DEPTHPTR negative
7136 or before a comma when *DEPTHPTR is zero.
7137 Single and double quotes are matched and termination
7138 is inhibited within them. Comments also inhibit it.
7139 Value returned is pointer to stopping place.
7141 Increment *NEWLINES each time a newline is passed.
7142 Set *COMMENTS to 1 if a comment is seen. */
7145 macarg1 (start, limit, depthptr, newlines, comments)
7147 register U_CHAR *limit;
7148 int *depthptr, *newlines, *comments;
7150 register U_CHAR *bp = start;
7152 while (bp < limit) {
7158 if (--(*depthptr) < 0)
7162 /* Traditionally, backslash makes following char not special. */
7163 if (bp + 1 < limit && traditional)
7166 /* But count source lines anyway. */
7175 if (bp[1] == '\\' && bp[2] == '\n')
7176 newline_fix (bp + 1);
7177 if ((cplusplus || objc) && bp[1] == '/') {
7180 while (bp < limit && *bp++ != '\n') ;
7184 if (bp[1] != '*' || bp + 1 >= limit)
7188 while (bp + 1 < limit) {
7190 && bp[1] == '\\' && bp[2] == '\n')
7191 newline_fix (bp + 1);
7192 if (bp[0] == '*' && bp[1] == '/')
7194 if (*bp == '\n') ++*newlines;
7202 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
7207 while (*bp == '\\' && bp[1] == '\n') {
7210 } else if (*bp == '\n') {
7219 if ((*depthptr) == 0)
7229 /* Discard comments and duplicate newlines
7230 in the string of length LENGTH at START,
7231 except inside of string constants.
7232 The string is copied into itself with its beginning staying fixed.
7234 NEWLINES is the number of newlines that must be duplicated.
7235 We assume that that much extra space is available past the end
7239 discard_comments (start, length, newlines)
7244 register U_CHAR *ibp;
7245 register U_CHAR *obp;
7246 register U_CHAR *limit;
7249 /* If we have newlines to duplicate, copy everything
7250 that many characters up. Then, in the second part,
7251 we will have room to insert the newlines
7253 NEWLINES may actually be too large, because it counts
7254 newlines in string constants, and we don't duplicate those.
7255 But that does no harm. */
7257 ibp = start + length;
7258 obp = ibp + newlines;
7260 while (limit != ibp)
7264 ibp = start + newlines;
7265 limit = start + length + newlines;
7268 while (ibp < limit) {
7269 *obp++ = c = *ibp++;
7272 /* Duplicate the newline. */
7284 if (*ibp == '\\' && ibp[1] == '\n')
7286 /* Delete any comment. */
7287 if ((cplusplus || objc) && ibp[0] == '/') {
7290 while (ibp < limit && *ibp++ != '\n') ;
7293 if (ibp[0] != '*' || ibp + 1 >= limit)
7297 while (ibp + 1 < limit) {
7299 && ibp[1] == '\\' && ibp[2] == '\n')
7300 newline_fix (ibp + 1);
7301 if (ibp[0] == '*' && ibp[1] == '/')
7310 /* Notice and skip strings, so that we don't
7311 think that comments start inside them,
7312 and so we don't duplicate newlines in them. */
7315 while (ibp < limit) {
7316 *obp++ = c = *ibp++;
7319 if (c == '\n' && quotec == '\'')
7321 if (c == '\\' && ibp < limit) {
7322 while (*ibp == '\\' && ibp[1] == '\n')
7335 /* Delete newlines in the string of length LENGTH at START, except inside
7336 of string constants. The string is copied into itself with its beginning
7340 delete_newlines (start, length)
7344 register U_CHAR *ibp;
7345 register U_CHAR *obp;
7346 register U_CHAR *limit;
7350 limit = start + length;
7353 while (ibp < limit) {
7354 *obp++ = c = *ibp++;
7357 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
7358 output. Skip past the newline and its duplicate. */
7368 /* Notice and skip strings, so that we don't delete newlines in them. */
7371 while (ibp < limit) {
7372 *obp++ = c = *ibp++;
7375 if (c == '\n' && quotec == '\'')
7387 * error - print error message and increment count of errors.
7391 error (msg, arg1, arg2, arg3)
7395 FILE_BUF *ip = NULL;
7397 print_containing_files ();
7399 for (i = indepth; i >= 0; i--)
7400 if (instack[i].fname != NULL) {
7406 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
7407 fprintf (stderr, msg, arg1, arg2, arg3);
7408 fprintf (stderr, "\n");
7412 /* Error including a message from `errno'. */
7415 error_from_errno (name)
7419 FILE_BUF *ip = NULL;
7421 print_containing_files ();
7423 for (i = indepth; i >= 0; i--)
7424 if (instack[i].fname != NULL) {
7430 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
7432 if (errno < sys_nerr)
7433 fprintf (stderr, "%s: %s\n", name, sys_errlist[errno]);
7435 fprintf (stderr, "%s: undocumented I/O error\n", name);
7440 /* Print error message but don't count it. */
7443 warning (msg, arg1, arg2, arg3)
7447 FILE_BUF *ip = NULL;
7449 if (inhibit_warnings)
7452 if (warnings_are_errors)
7455 print_containing_files ();
7457 for (i = indepth; i >= 0; i--)
7458 if (instack[i].fname != NULL) {
7464 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
7465 fprintf (stderr, "warning: ");
7466 fprintf (stderr, msg, arg1, arg2, arg3);
7467 fprintf (stderr, "\n");
7471 error_with_line (line, msg, arg1, arg2, arg3)
7476 FILE_BUF *ip = NULL;
7478 print_containing_files ();
7480 for (i = indepth; i >= 0; i--)
7481 if (instack[i].fname != NULL) {
7487 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
7488 fprintf (stderr, msg, arg1, arg2, arg3);
7489 fprintf (stderr, "\n");
7493 /* print an error message and maybe count it. */
7496 pedwarn (msg, arg1, arg2, arg3)
7499 if (pedantic_errors)
7500 error (msg, arg1, arg2, arg3);
7502 warning (msg, arg1, arg2, arg3);
7505 /* Report a warning (or an error if pedantic_errors)
7506 giving specified file name and line number, not current. */
7509 pedwarn_with_file_and_line (file, line, msg, arg1, arg2, arg3)
7515 if (!pedantic_errors && inhibit_warnings)
7518 fprintf (stderr, "%s:%d: ", file, line);
7519 if (pedantic_errors || warnings_are_errors)
7521 if (!pedantic_errors)
7522 fprintf (stderr, "warning: ");
7523 fprintf (stderr, msg, arg1, arg2, arg3);
7524 fprintf (stderr, "\n");
7527 /* Print the file names and line numbers of the #include
7528 commands which led to the current file. */
7531 print_containing_files ()
7533 FILE_BUF *ip = NULL;
7537 /* If stack of files hasn't changed since we last printed
7538 this info, don't repeat it. */
7539 if (last_error_tick == input_file_stack_tick)
7542 for (i = indepth; i >= 0; i--)
7543 if (instack[i].fname != NULL) {
7548 /* Give up if we don't find a source file. */
7552 /* Find the other, outer source files. */
7553 for (i--; i >= 0; i--)
7554 if (instack[i].fname != NULL) {
7558 fprintf (stderr, "In file included");
7560 fprintf (stderr, ",");
7563 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
7566 fprintf (stderr, ":\n");
7568 /* Record we have printed the status as of this time. */
7569 last_error_tick = input_file_stack_tick;
7572 /* Return the line at which an error occurred.
7573 The error is not necessarily associated with the current spot
7574 in the input stack, so LINE says where. LINE will have been
7575 copied from ip->lineno for the current input level.
7576 If the current level is for a file, we return LINE.
7577 But if the current level is not for a file, LINE is meaningless.
7578 In that case, we return the lineno of the innermost file. */
7581 line_for_error (line)
7587 for (i = indepth; i >= 0; ) {
7588 if (instack[i].fname != 0)
7593 line1 = instack[i].lineno;
7601 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
7603 * As things stand, nothing is ever placed in the output buffer to be
7604 * removed again except when it's KNOWN to be part of an identifier,
7605 * so flushing and moving down everything left, instead of expanding,
7609 /* You might think void was cleaner for the return type,
7610 but that would get type mismatch in check_expand in strict ANSI. */
7612 grow_outbuf (obuf, needed)
7613 register FILE_BUF *obuf;
7614 register int needed;
7619 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
7622 /* Make it at least twice as big as it is now. */
7624 /* Make it have at least 150% of the free space we will need. */
7625 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
7626 if (minsize > obuf->length)
7627 obuf->length = minsize;
7629 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
7632 obuf->bufp = p + (obuf->bufp - obuf->buf);
7638 /* Symbol table for macro names and special symbols */
7641 * install a name in the main hash table, even if it is already there.
7642 * name stops with first non alphanumeric, except leading '#'.
7643 * caller must check against redefinition if that is desired.
7644 * delete_macro () removes things installed by install () in fifo order.
7645 * this is important because of the `defined' special symbol used
7646 * in #if, and also if pushdef/popdef directives are ever implemented.
7648 * If LEN is >= 0, it is the length of the name.
7649 * Otherwise, compute the length by scanning the entire name.
7651 * If HASH is >= 0, it is the precomputed hash code.
7652 * Otherwise, compute the hash code.
7655 install (name, len, type, value, hash)
7658 enum node_type type;
7661 /* watch out here if sizeof (U_CHAR *) != sizeof (int) */
7663 register HASHNODE *hp;
7664 register int i, bucket;
7665 register U_CHAR *p, *q;
7669 while (is_idchar[*p])
7675 hash = hashf (name, len, HASHSIZE);
7677 i = sizeof (HASHNODE) + len + 1;
7678 hp = (HASHNODE *) xmalloc (i);
7680 hp->bucket_hdr = &hashtab[bucket];
7681 hp->next = hashtab[bucket];
7682 hashtab[bucket] = hp;
7684 if (hp->next != NULL)
7685 hp->next->prev = hp;
7688 hp->value.ival = value;
7689 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
7692 for (i = 0; i < len; i++)
7699 * find the most recent hash node for name name (ending with first
7700 * non-identifier char) installed by install
7702 * If LEN is >= 0, it is the length of the name.
7703 * Otherwise, compute the length by scanning the entire name.
7705 * If HASH is >= 0, it is the precomputed hash code.
7706 * Otherwise, compute the hash code.
7709 lookup (name, len, hash)
7714 register U_CHAR *bp;
7715 register HASHNODE *bucket;
7718 for (bp = name; is_idchar[*bp]; bp++) ;
7723 hash = hashf (name, len, HASHSIZE);
7725 bucket = hashtab[hash];
7727 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
7729 bucket = bucket->next;
7735 * Delete a hash node. Some weirdness to free junk from macros.
7736 * More such weirdness will have to be added if you define more hash
7737 * types that need it.
7740 /* Note that the DEFINITION of a macro is removed from the hash table
7741 but its storage is not freed. This would be a storage leak
7742 except that it is not reasonable to keep undefining and redefining
7743 large numbers of macros many times.
7744 In any case, this is necessary, because a macro can be #undef'd
7745 in the middle of reading the arguments to a call to it.
7746 If #undef freed the DEFINITION, that would crash. */
7753 if (hp->prev != NULL)
7754 hp->prev->next = hp->next;
7755 if (hp->next != NULL)
7756 hp->next->prev = hp->prev;
7758 /* make sure that the bucket chain header that
7759 the deleted guy was on points to the right thing afterwards. */
7760 if (hp == *hp->bucket_hdr)
7761 *hp->bucket_hdr = hp->next;
7764 if (hp->type == T_MACRO) {
7765 DEFINITION *d = hp->value.defn;
7766 struct reflist *ap, *nextap;
7768 for (ap = d->pattern; ap != NULL; ap = nextap) {
7779 * return hash function on name. must be compatible with the one
7780 * computed a step at a time, elsewhere
7783 hashf (name, len, hashsize)
7784 register U_CHAR *name;
7791 r = HASHSTEP (r, *name++);
7793 return MAKE_POS (r) % hashsize;
7797 /* Dump the definition of a single macro HP to OF. */
7799 dump_single_macro (hp, of)
7800 register HASHNODE *hp;
7803 register DEFINITION *defn = hp->value.defn;
7809 /* Print the definition of the macro HP. */
7811 fprintf (of, "#define %s", hp->name);
7813 if (defn->nargs >= 0) {
7817 for (i = 0; i < defn->nargs; i++) {
7818 dump_arg_n (defn, i, of);
7819 if (i + 1 < defn->nargs)
7829 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
7830 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
7831 if (ap->nchars != 0)
7833 offset += ap->nchars;
7836 if (ap->raw_before && !concat)
7837 fprintf (of, " ## ");
7839 dump_arg_n (defn, ap->argno, of);
7840 if (ap->raw_after) {
7841 fprintf (of, " ## ");
7845 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
7849 /* Dump all macro definitions as #defines to stdout. */
7856 for (bucket = 0; bucket < HASHSIZE; bucket++) {
7857 register HASHNODE *hp;
7859 for (hp = hashtab[bucket]; hp; hp= hp->next) {
7860 if (hp->type == T_MACRO)
7861 dump_single_macro (hp, stdout);
7866 /* Output to OF a substring of a macro definition.
7867 BASE is the beginning of the definition.
7868 Output characters START thru LENGTH.
7869 Discard newlines outside of strings, thus
7870 converting funny-space markers to ordinary spaces. */
7873 dump_defn_1 (base, start, length, of)
7879 U_CHAR *p = base + start;
7880 U_CHAR *limit = base + start + length;
7885 else if (*p == '\"' || *p =='\'') {
7886 U_CHAR *p1 = skip_quoted_string (p, limit, 0, 0, 0, 0);
7887 fwrite (p, p1 - p, 1, of);
7894 /* Print the name of argument number ARGNUM of macro definition DEFN
7896 Recall that DEFN->args.argnames contains all the arg names
7897 concatenated in reverse order with comma-space in between. */
7900 dump_arg_n (defn, argnum, of)
7905 register U_CHAR *p = defn->args.argnames;
7906 while (argnum + 1 < defn->nargs) {
7907 p = (U_CHAR *) index (p, ' ') + 1;
7911 while (*p && *p != ',') {
7917 /* Initialize syntactic classifications of characters. */
7920 initialize_char_syntax ()
7925 * Set up is_idchar and is_idstart tables. These should be
7926 * faster than saying (is_alpha (c) || c == '_'), etc.
7927 * Set up these things before calling any routines tthat
7930 for (i = 'a'; i <= 'z'; i++) {
7931 is_idchar[i - 'a' + 'A'] = 1;
7933 is_idstart[i - 'a' + 'A'] = 1;
7936 for (i = '0'; i <= '9'; i++)
7939 is_idstart['_'] = 1;
7940 is_idchar['$'] = dollars_in_ident;
7941 is_idstart['$'] = dollars_in_ident;
7943 /* horizontal space table */
7944 is_hor_space[' '] = 1;
7945 is_hor_space['\t'] = 1;
7946 is_hor_space['\v'] = 1;
7947 is_hor_space['\f'] = 1;
7948 is_hor_space['\r'] = 1;
7958 /* Initialize the built-in macros. */
7961 initialize_builtins (inp, outp)
7968 timebuf = localtime (&t);
7970 install ("__LINE__", -1, T_SPECLINE, 0, -1);
7971 install ("__DATE__", -1, T_DATE, 0, -1);
7972 install ("__FILE__", -1, T_FILE, 0, -1);
7973 install ("__BASE_FILE__", -1, T_BASE_FILE, 0, -1);
7974 install ("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, -1);
7975 install ("__VERSION__", -1, T_VERSION, 0, -1);
7976 install ("__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, -1);
7977 install ("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, -1);
7978 install ("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, -1);
7979 install ("__TIME__", -1, T_TIME, 0, -1);
7981 install ("__STDC__", -1, T_CONST, STDC_VALUE, -1);
7983 install ("__OBJC__", -1, T_CONST, 1, -1);
7984 /* This is supplied using a -D by the compiler driver
7985 so that it is present only when truly compiling with GNU C. */
7986 /* install ("__GNUC__", -1, T_CONST, 2, -1); */
7990 char directive[2048];
7991 register struct directive *dp = &directive_table[0];
7993 sprintf (directive, " __BASE_FILE__ \"%s\"",
7994 instack[0].nominal_fname);
7995 output_line_command (inp, outp, 0, same_file);
7996 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
7998 sprintf (directive, " __VERSION__ \"%s\"", version_string);
7999 output_line_command (inp, outp, 0, same_file);
8000 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8002 sprintf (directive, " __SIZE_TYPE__ %s", SIZE_TYPE);
8003 output_line_command (inp, outp, 0, same_file);
8004 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8006 sprintf (directive, " __PTRDIFF_TYPE__ %s", PTRDIFF_TYPE);
8007 output_line_command (inp, outp, 0, same_file);
8008 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8010 sprintf (directive, " __WCHAR_TYPE__ %s", WCHAR_TYPE);
8011 output_line_command (inp, outp, 0, same_file);
8012 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8014 sprintf (directive, " __WCHAR_TYPE__ %s", WCHAR_TYPE);
8015 output_line_command (inp, outp, 0, same_file);
8016 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8018 sprintf (directive, " __DATE__ \"%s %2d %4d\"",
8019 monthnames[timebuf->tm_mon],
8020 timebuf->tm_mday, timebuf->tm_year + 1900);
8021 output_line_command (inp, outp, 0, same_file);
8022 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8024 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"",
8025 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
8026 output_line_command (inp, outp, 0, same_file);
8027 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8031 sprintf (directive, " __STDC__ 1");
8032 output_line_command (inp, outp, 0, same_file);
8033 pass_thru_directive (directive, &directive[strlen (directive)],
8038 sprintf (directive, " __OBJC__ 1");
8039 output_line_command (inp, outp, 0, same_file);
8040 pass_thru_directive (directive, &directive[strlen (directive)],
8047 * process a given definition string, for initialization
8048 * If STR is just an identifier, define it with value 1.
8049 * If STR has anything after the identifier, then it should
8050 * be identifier=definition.
8054 make_definition (str, op)
8059 struct directive *kt;
8064 if (!is_idstart[*p]) {
8065 error ("malformed option `-D %s'", str);
8068 while (is_idchar[*++p])
8071 buf = (U_CHAR *) alloca (p - buf + 4);
8072 strcpy ((char *)buf, str);
8073 strcat ((char *)buf, " 1");
8074 } else if (*p != '=') {
8075 error ("malformed option `-D %s'", str);
8079 /* Copy the entire option so we can modify it. */
8080 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
8081 strncpy (buf, str, p - str);
8082 /* Change the = to a space. */
8084 /* Scan for any backslash-newline and remove it. */
8088 if (*p == '\\' && p[1] == '\n')
8090 /* Change newline chars into newline-markers. */
8091 else if (*p == '\n')
8103 ip = &instack[++indepth];
8104 ip->nominal_fname = ip->fname = "*Initialization*";
8106 ip->buf = ip->bufp = buf;
8107 ip->length = strlen (buf);
8111 ip->if_stack = if_stack;
8112 ip->system_header_p = 0;
8114 for (kt = directive_table; kt->type != T_DEFINE; kt++)
8117 do_define (buf, buf + strlen (buf) , op, kt);
8121 /* JF, this does the work for the -U option */
8124 make_undef (str, op)
8129 struct directive *kt;
8131 ip = &instack[++indepth];
8132 ip->nominal_fname = ip->fname = "*undef*";
8134 ip->buf = ip->bufp = str;
8135 ip->length = strlen (str);
8139 ip->if_stack = if_stack;
8140 ip->system_header_p = 0;
8142 for (kt = directive_table; kt->type != T_UNDEF; kt++)
8145 do_undef (str, str + strlen (str), op, kt);
8149 /* Process the string STR as if it appeared as the body of a #assert.
8150 OPTION is the option name for which STR was the argument. */
8153 make_assertion (option, str)
8158 struct directive *kt;
8159 U_CHAR *buf, *p, *q;
8161 /* Copy the entire option so we can modify it. */
8162 buf = (U_CHAR *) alloca (strlen (str) + 1);
8163 strcpy ((char *) buf, str);
8164 /* Scan for any backslash-newline and remove it. */
8167 if (*p == '\\' && p[1] == '\n')
8175 if (!is_idstart[*p]) {
8176 error ("malformed option `%s %s'", option, str);
8179 while (is_idchar[*++p])
8181 while (*p == ' ' || *p == '\t') p++;
8182 if (! (*p == 0 || *p == '(')) {
8183 error ("malformed option `%s %s'", option, str);
8187 ip = &instack[++indepth];
8188 ip->nominal_fname = ip->fname = "*Initialization*";
8190 ip->buf = ip->bufp = buf;
8191 ip->length = strlen (buf);
8195 ip->if_stack = if_stack;
8196 ip->system_header_p = 0;
8198 for (kt = directive_table; kt->type != T_ASSERT; kt++)
8201 /* pass NULL as output ptr to do_define since we KNOW it never
8202 does any output.... */
8203 do_assert (buf, buf + strlen (buf) , NULL, kt);
8207 /* Add output to `deps_buffer' for the -M switch.
8208 STRING points to the text to be output.
8209 SIZE is the number of bytes, or 0 meaning output until a null.
8210 Outputting the empty string breaks the line if it is long enough. */
8213 deps_output (string, size)
8218 size = strlen (string);
8220 #ifndef MAX_OUTPUT_COLUMNS
8221 #define MAX_OUTPUT_COLUMNS 75
8223 if (size == 0 && deps_column != 0
8224 && size + deps_column > MAX_OUTPUT_COLUMNS) {
8225 deps_output ("\\\n ", 0);
8229 if (deps_size + size + 1 > deps_allocated_size) {
8230 deps_allocated_size = deps_size + size + 50;
8231 deps_allocated_size *= 2;
8232 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
8234 bcopy (string, &deps_buffer[deps_size], size);
8236 deps_column += size;
8237 deps_buffer[deps_size] = 0;
8240 #if defined(USG) || defined(VMS)
8246 register unsigned length;
8250 long max_str = 65535;
8252 while (length > max_str) {
8253 (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b);
8257 (void) LIB$MOVC5 (&zero, &zero, &zero, &length, b);
8259 while (length-- > 0)
8261 #endif /* not VMS */
8265 bcopy (b1, b2, length)
8268 register unsigned length;
8271 long max_str = 65535;
8273 while (length > max_str) {
8274 (void) LIB$MOVC3 (&max_str, b1, b2);
8279 (void) LIB$MOVC3 (&length, b1, b2);
8281 while (length-- > 0)
8283 #endif /* not VMS */
8287 bcmp (b1, b2, length) /* This could be a macro! */
8290 register unsigned length;
8293 struct dsc$descriptor_s src1 = {length, DSC$K_DTYPE_T, DSC$K_CLASS_S, b1};
8294 struct dsc$descriptor_s src2 = {length, DSC$K_DTYPE_T, DSC$K_CLASS_S, b2};
8296 return STR$COMPARE (&src1, &src2);
8298 while (length-- > 0)
8303 #endif /* not VMS */
8305 #endif /* not BSTRING */
8306 #endif /* USG or VMS */
8315 fprintf (stderr, "%s: ", progname);
8316 fprintf (stderr, str, arg);
8317 fprintf (stderr, "\n");
8318 exit (FAILURE_EXIT_CODE);
8321 /* More 'friendly' abort that prints the line and file.
8322 config.h can #define abort fancy_abort if you like that sort of thing. */
8327 fatal ("Internal gcc abort.");
8331 perror_with_name (name)
8334 fprintf (stderr, "%s: ", progname);
8335 if (errno < sys_nerr)
8336 fprintf (stderr, "%s: %s\n", name, sys_errlist[errno]);
8338 fprintf (stderr, "%s: undocumented I/O error\n", name);
8343 pfatal_with_name (name)
8346 perror_with_name (name);
8350 exit (FAILURE_EXIT_CODE);
8358 fatal ("Memory exhausted.");
8366 register char *ptr = (char *) malloc (size);
8367 if (ptr != 0) return (ptr);
8374 xrealloc (old, size)
8378 register char *ptr = (char *) realloc (old, size);
8379 if (ptr != 0) return (ptr);
8386 xcalloc (number, size)
8387 unsigned number, size;
8389 register unsigned total = number * size;
8390 register char *ptr = (char *) malloc (total);
8395 /* It's not too long, so loop, zeroing by longs.
8396 It must be safe because malloc values are always well aligned. */
8397 register long *zp = (long *) ptr;
8398 register long *zl = (long *) (ptr + total - 4);
8399 register int i = total - 4;
8418 unsigned size = strlen (input);
8419 char *output = xmalloc (size + 1);
8420 strcpy (output, input);
8424 /* Get the file-mode and data size of the file open on FD
8425 and store them in *MODE_POINTER and *SIZE_POINTER. */
8428 file_size_and_mode (fd, mode_pointer, size_pointer)
8431 long int *size_pointer;
8435 if (fstat (fd, &sbuf) < 0) return (-1);
8436 if (mode_pointer) *mode_pointer = sbuf.st_mode;
8437 if (size_pointer) *size_pointer = sbuf.st_size;
8443 /* Under VMS we need to fix up the "include" specification
8444 filename so that everything following the 1st slash is
8445 changed into its correct VMS file specification. */
8448 hack_vms_include_specification (fname)
8451 register char *cp, *cp1, *cp2;
8452 int f, check_filename_before_returning, no_prefix_seen;
8455 check_filename_before_returning = 0;
8458 /* Ignore leading "./"s */
8459 while (fname[0] == '.' && fname[1] == '/') {
8460 strcpy (fname, fname+2);
8461 no_prefix_seen = 1; /* mark this for later */
8463 /* Look for the boundary between the VMS and UNIX filespecs */
8464 cp = rindex (fname, ']'); /* Look for end of dirspec. */
8465 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
8466 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
8470 cp = index (fname, '/'); /* Look for the "/" */
8473 cp2 = Local; /* initialize */
8475 /* We are trying to do a number of things here. First of all, we are
8476 trying to hammer the filenames into a standard format, such that later
8477 processing can handle them.
8479 If the file name contains something like [dir.], then it recognizes this
8480 as a root, and strips the ".]". Later processing will add whatever is
8481 needed to get things working properly.
8483 If no device is specified, then the first directory name is taken to be
8484 a device name (or a rooted logical). */
8486 /* See if we found that 1st slash */
8487 if (cp == 0) return; /* Nothing to do!!! */
8488 if (*cp != '/') return; /* Nothing to do!!! */
8489 /* Point to the UNIX filename part (which needs to be fixed!) */
8491 /* If the directory spec is not rooted, we can just copy
8492 the UNIX filename part and we are done */
8493 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
8494 if (cp[-2] != '.') {
8496 * The VMS part ends in a `]', and the preceding character is not a `.'.
8497 * We strip the `]', and then splice the two parts of the name in the
8498 * usual way. Given the default locations for include files in cccp.c,
8499 * we will only use this code if the user specifies alternate locations
8500 * with the /include (-I) switch on the command line. */
8501 cp -= 1; /* Strip "]" */
8502 cp1--; /* backspace */
8505 * The VMS part has a ".]" at the end, and this will not do. Later
8506 * processing will add a second directory spec, and this would be a syntax
8507 * error. Thus we strip the ".]", and thus merge the directory specs.
8508 * We also backspace cp1, so that it points to a '/'. This inhibits the
8509 * generation of the 000000 root directory spec (which does not belong here
8512 cp -= 2; /* Strip ".]" */
8513 cp1--; }; /* backspace */
8516 /* We drop in here if there is no VMS style directory specification yet.
8517 * If there is no device specification either, we make the first dir a
8518 * device and try that. If we do not do this, then we will be essentially
8519 * searching the users default directory (as if they did a #include "asdf.h").
8521 * Then all we need to do is to push a '[' into the output string. Later
8522 * processing will fill this in, and close the bracket.
8524 if(cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
8525 *cp2++ = '['; /* Open the directory specification */
8528 /* at this point we assume that we have the device spec, and (at least
8529 the opening "[" for a directory specification. We may have directories
8530 specified already */
8532 /* If there are no other slashes then the filename will be
8533 in the "root" directory. Otherwise, we need to add
8534 directory specifications. */
8535 if (index (cp1, '/') == 0) {
8536 /* Just add "000000]" as the directory string */
8537 strcpy (cp2, "000000]");
8538 cp2 += strlen (cp2);
8539 check_filename_before_returning = 1; /* we might need to fool with this later */
8541 /* As long as there are still subdirectories to add, do them. */
8542 while (index (cp1, '/') != 0) {
8543 /* If this token is "." we can ignore it */
8544 if ((cp1[0] == '.') && (cp1[1] == '/')) {
8548 /* Add a subdirectory spec. Do not duplicate "." */
8549 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
8551 /* If this is ".." then the spec becomes "-" */
8552 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
8553 /* Add "-" and skip the ".." */
8558 /* Copy the subdirectory */
8559 while (*cp1 != '/') *cp2++= *cp1++;
8560 cp1++; /* Skip the "/" */
8562 /* Close the directory specification */
8563 if(cp2[-1] == '.') /* no trailing periods */
8567 /* Now add the filename */
8568 while (*cp1) *cp2++ = *cp1++;
8570 /* Now append it to the original VMS spec. */
8573 /* If we put a [000000] in the filename, try to open it first. If this fails,
8574 remove the [000000], and return that name. This provides flexibility
8575 to the user in that they can use both rooted and non-rooted logical names
8576 to point to the location of the file. */
8578 if (check_filename_before_returning && no_prefix_seen) {
8579 f = open (fname, O_RDONLY, 0666);
8581 /* The file name is OK as it is, so return it as is. */
8585 /* The filename did not work. Try to remove the [000000] from the name,
8587 cp = index (fname, '[');
8588 cp2 = index (fname, ']') + 1;
8589 strcpy (cp, cp2); /* this gets rid of it */
8597 /* These are the read/write replacement routines for
8598 VAX-11 "C". They make read/write behave enough
8599 like their UNIX counterparts that CCCP will work */
8602 read (fd, buf, size)
8607 #undef read /* Get back the REAL read routine */
8609 register int total = 0;
8611 /* Read until the buffer is exhausted */
8613 /* Limit each read to 32KB */
8614 i = (size > (32*1024)) ? (32*1024) : size;
8615 i = read (fd, buf, i);
8617 if (i == 0) return (total);
8620 /* Account for this read */
8629 write (fd, buf, size)
8634 #undef write /* Get back the REAL write routine */
8638 /* Limit individual writes to 32Kb */
8641 j = (i > (32*1024)) ? (32*1024) : i;
8642 if (write (fd, buf, j) < 0) return (-1);
8643 /* Account for the data written */
8650 /* The following wrapper functions supply additional arguments to the VMS
8651 I/O routines to optimize performance with file handling. The arguments
8653 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
8654 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
8655 "fop=tef"- Truncate unused portions of file when closing file.
8656 "shr=nil"- Disallow file sharing while file is open.
8660 freopen (fname, type, oldfile)
8665 #undef freopen /* Get back the REAL fopen routine */
8666 if (strcmp (type, "w") == 0)
8667 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
8668 return freopen (fname, type, oldfile, "mbc=16");
8676 #undef fopen /* Get back the REAL fopen routine */
8677 if (strcmp (type, "w") == 0)
8678 return fopen (fname, type, "mbc=16", "deq=64", "fop=tef", "shr=nil");
8679 return fopen (fname, type, "mbc=16");
8683 open (fname, flags, prot)
8688 #undef open /* Get back the REAL open routine */
8689 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");