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"
50 #if 0 /* We can't get ptrdiff_t, so I arranged not to need PTR_INT_TYPE. */
52 #define PTR_INT_TYPE ptrdiff_t
54 #define PTR_INT_TYPE long
64 /* By default, colon separates directories in a path. */
65 #ifndef PATH_SEPARATOR
66 #define PATH_SEPARATOR ':'
69 /* In case config.h defines these. */
74 #include <sys/types.h>
82 #include <sys/time.h> /* for __DATE__ and __TIME__ */
83 #include <sys/resource.h>
90 /* This defines "errno" properly for VMS, and gives us EACCES. */
93 /* VMS-specific definitions */
96 #include <perror.h> /* This defines sys_errlist/sys_nerr properly */
98 #define O_RDONLY 0 /* Open arg for Read/Only */
99 #define O_WRONLY 1 /* Open arg for Write/Only */
100 #define read(fd,buf,size) VMS_read (fd,buf,size)
101 #define write(fd,buf,size) VMS_write (fd,buf,size)
102 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
103 #define fopen(fname,mode) VMS_fopen (fname,mode)
104 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
105 #define strncat(dst,src,cnt) VMS_strncat (dst,src,cnt)
106 static char * VMS_strncat ();
107 static int VMS_read ();
108 static int VMS_write ();
109 static int VMS_open ();
110 static FILE * VMS_fopen ();
111 static FILE * VMS_freopen ();
112 static void hack_vms_include_specification ();
113 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
114 #define ino_t vms_ino_t
115 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
117 #define BSTRING /* VMS/GCC supplies the bstring routines */
118 #endif /* __GNUC__ */
121 extern char *index ();
122 extern char *rindex ();
130 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
131 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
133 /* Find the largest host integer type and set its size and type. */
135 #ifndef HOST_BITS_PER_WIDE_INT
137 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
138 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
139 #define HOST_WIDE_INT long
141 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
142 #define HOST_WIDE_INT int
148 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
152 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
155 /* Define a generic NULL if one hasn't already been defined. */
162 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
163 #define GENERIC_PTR void *
165 #define GENERIC_PTR char *
170 #define NULL_PTR ((GENERIC_PTR)0)
173 #ifndef INCLUDE_LEN_FUDGE
174 #define INCLUDE_LEN_FUDGE 0
177 /* Forward declarations. */
183 /* External declarations. */
185 extern char *getenv ();
186 extern FILE *fdopen ();
187 extern char *version_string;
188 extern struct tm *localtime ();
190 extern char *sys_errlist[];
196 /* Forward declarations. */
203 #if defined(USG) || defined(VMS)
211 /* These functions are declared to return int instead of void since they
212 are going to be placed in a table and some old compilers have trouble with
213 pointers to functions returning void. */
215 static int do_define ();
216 static int do_line ();
217 static int do_include ();
218 static int do_undef ();
219 static int do_error ();
220 static int do_pragma ();
221 static int do_ident ();
223 static int do_xifdef ();
224 static int do_else ();
225 static int do_elif ();
226 static int do_endif ();
227 static int do_sccs ();
228 static int do_once ();
229 static int do_assert ();
230 static int do_unassert ();
231 static int do_warning ();
233 static void add_import ();
234 static void append_include_chain ();
235 static void deps_output ();
236 static void make_undef ();
237 static void make_definition ();
238 static void make_assertion ();
239 static void path_include ();
240 static void initialize_builtins ();
241 static void initialize_char_syntax ();
242 static void dump_arg_n ();
243 static void dump_defn_1 ();
244 static void delete_macro ();
245 static void trigraph_pcp ();
246 static void rescan ();
247 static void finclude ();
248 static void validate_else ();
249 static int comp_def_part ();
250 static void error_from_errno ();
251 static void error_with_line ();
253 void pedwarn_with_line ();
254 static void pedwarn_with_file_and_line ();
255 static void fatal ();
257 static void pfatal_with_name ();
258 static void perror_with_name ();
259 static void pipe_closed ();
260 static void print_containing_files ();
261 static int lookup_import ();
262 static int redundant_include_p ();
263 static is_system_include ();
264 static int check_preconditions ();
265 static void pcfinclude ();
266 static void pcstring_used ();
267 static void write_output ();
268 static int check_macro_name ();
269 static int compare_defs ();
270 static int compare_token_lists ();
271 static int eval_if_expression ();
272 static int discard_comments ();
273 static int change_newlines ();
274 static int line_for_error ();
276 static int file_size_and_mode ();
278 static struct arglist *read_token_list ();
279 static void free_token_list ();
281 static struct hashnode *install ();
282 struct hashnode *lookup ();
284 static struct assertion_hashnode *assertion_install ();
285 static struct assertion_hashnode *assertion_lookup ();
287 static char *xrealloc ();
288 static char *xcalloc ();
289 static char *savestring ();
291 static void delete_assertion ();
292 static void macroexpand ();
293 static void dump_all_macros ();
294 static void conditional_skip ();
295 static void skip_if_group ();
296 static void output_line_command ();
298 /* Last arg to output_line_command. */
299 enum file_change_code {same_file, enter_file, leave_file};
301 static int grow_outbuf ();
302 static int handle_directive ();
303 static void memory_full ();
305 static U_CHAR *macarg1 ();
306 static char *macarg ();
308 static U_CHAR *skip_to_end_of_comment ();
309 static U_CHAR *skip_quoted_string ();
310 static U_CHAR *skip_paren_group ();
312 static char *check_precompiled ();
313 /* static struct macrodef create_definition (); [moved below] */
314 static void dump_single_macro ();
316 #ifndef FAILURE_EXIT_CODE
317 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
320 #ifndef SUCCESS_EXIT_CODE
321 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
324 /* Name under which this program was invoked. */
326 static char *progname;
328 /* Nonzero means use extra default include directories for C++. */
330 static int cplusplus;
332 /* Nonzero means handle cplusplus style comments */
334 static int cplusplus_comments;
336 /* Nonzero means handle #import, for objective C. */
340 /* Nonzero means this is an assembly file, and allow
341 unknown directives, which could be comments. */
345 /* Current maximum length of directory names in the search path
346 for include files. (Altered as we get more of them.) */
348 static int max_include_len;
350 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
354 /* Nonzero means copy comments into the output file. */
356 static int put_out_comments = 0;
358 /* Nonzero means don't process the ANSI trigraph sequences. */
360 static int no_trigraphs = 0;
362 /* Nonzero means print the names of included files rather than
363 the preprocessed output. 1 means just the #include "...",
364 2 means #include <...> as well. */
366 static int print_deps = 0;
368 /* Nonzero means print names of header files (-H). */
370 static int print_include_names = 0;
372 /* Nonzero means don't output line number information. */
374 static int no_line_commands;
376 /* dump_only means inhibit output of the preprocessed text
377 and instead output the definitions of all user-defined
378 macros in a form suitable for use as input to cccp.
379 dump_names means pass #define and the macro name through to output.
380 dump_definitions means pass the whole definition (plus #define) through
383 static enum {dump_none, dump_only, dump_names, dump_definitions}
384 dump_macros = dump_none;
386 /* Nonzero means pass all #define and #undef directives which we actually
387 process through to the output stream. This feature is used primarily
388 to allow cc1 to record the #defines and #undefs for the sake of
389 debuggers which understand about preprocessor macros, but it may
390 also be useful with -E to figure out how symbols are defined, and
391 where they are defined. */
392 static int debug_output = 0;
394 /* Nonzero indicates special processing used by the pcp program. The
395 special effects of this mode are:
397 Inhibit all macro expansion, except those inside #if directives.
399 Process #define directives normally, and output their contents
402 Output preconditions to pcp_outfile indicating all the relevant
403 preconditions for use of this file in a later cpp run.
405 static FILE *pcp_outfile;
407 /* Nonzero means we are inside an IF during a -pcp run. In this mode
408 macro expansion is done, and preconditions are output for all macro
409 uses requiring them. */
410 static int pcp_inside_if;
412 /* Nonzero means never to include precompiled files.
413 This is 1 since there's no way now to make precompiled files,
414 so it's not worth testing for them. */
415 static int no_precomp = 1;
417 /* Nonzero means give all the error messages the ANSI standard requires. */
421 /* Nonzero means try to make failure to fit ANSI C an error. */
423 static int pedantic_errors;
425 /* Nonzero means don't print warning messages. -w. */
427 static int inhibit_warnings = 0;
429 /* Nonzero means warn if slash-star appears in a comment. */
431 static int warn_comments;
433 /* Nonzero means warn if a macro argument is (or would be)
434 stringified with -traditional. */
436 static int warn_stringify;
438 /* Nonzero means warn if there are any trigraphs. */
440 static int warn_trigraphs;
442 /* Nonzero means warn if #import is used. */
444 static int warn_import = 1;
446 /* Nonzero means turn warnings into errors. */
448 static int warnings_are_errors;
450 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
454 /* Nonzero causes output not to be done,
455 but directives such as #define that have side effects
458 static int no_output;
460 /* Nonzero means that we have finished processing the command line options.
461 This flag is used to decide whether or not to issue certain errors
464 static int done_initializing = 0;
466 /* Line where a newline was first seen in a string constant. */
468 static int multiline_string_line = 0;
470 /* I/O buffer structure.
471 The `fname' field is nonzero for source files and #include files
472 and for the dummy text used for -D and -U.
473 It is zero for rescanning results of macro expansion
474 and for expanding macro arguments. */
475 #define INPUT_STACK_MAX 200
476 static struct file_buf {
478 /* Filename specified with #line command. */
480 /* Record where in the search path this file was found.
481 For #include_next. */
482 struct file_name_list *dir;
487 /* Macro that this level is the expansion of.
488 Included so that we can reenable the macro
489 at the end of this level. */
490 struct hashnode *macro;
491 /* Value of if_stack at start of this file.
492 Used to prohibit unmatched #endif (etc) in an include file. */
493 struct if_stack *if_stack;
494 /* Object to be freed at end of input at this level. */
496 /* True if this is a header file included using <FILENAME>. */
497 char system_header_p;
498 } instack[INPUT_STACK_MAX];
500 static int last_error_tick; /* Incremented each time we print it. */
501 static int input_file_stack_tick; /* Incremented when the status changes. */
503 /* Current nesting level of input sources.
504 `instack[indepth]' is the level currently being read. */
505 static int indepth = -1;
506 #define CHECK_DEPTH(code) \
507 if (indepth >= (INPUT_STACK_MAX - 1)) \
509 error_with_line (line_for_error (instack[indepth].lineno), \
510 "macro or `#include' recursion too deep"); \
514 /* Current depth in #include directives that use <...>. */
515 static int system_include_depth = 0;
517 typedef struct file_buf FILE_BUF;
519 /* The output buffer. Its LENGTH field is the amount of room allocated
520 for the buffer, not the number of chars actually present. To get
521 that, subtract outbuf.buf from outbuf.bufp. */
523 #define OUTBUF_SIZE 10 /* initial size of output buffer */
524 static FILE_BUF outbuf;
526 /* Grow output buffer OBUF points at
527 so it can hold at least NEEDED more chars. */
529 #define check_expand(OBUF, NEEDED) \
530 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
531 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
533 struct file_name_list
535 struct file_name_list *next;
537 /* If the following is nonzero, it is a macro name.
538 Don't include the file again if that macro is defined. */
539 U_CHAR *control_macro;
542 /* #include "file" looks in source file dir, then stack. */
543 /* #include <file> just looks in the stack. */
544 /* -I directories are added to the end, then the defaults are added. */
545 static struct default_include { char *fname; int cplusplus; } include_defaults_array[]
546 #ifdef INCLUDE_DEFAULTS
550 /* Pick up GNU C++ specific include files. */
551 { GPLUSPLUS_INCLUDE_DIR, 1},
553 /* This is the dir for fixincludes. Put it just before
554 the files that we fix. */
555 { GCC_INCLUDE_DIR, 0},
556 /* For cross-compilation, this dir name is generated
557 automatically in Makefile.in. */
558 { CROSS_INCLUDE_DIR, 0 },
559 /* This is another place that the target system's headers might be. */
560 { TOOL_INCLUDE_DIR, 0},
561 #else /* not CROSS_COMPILE */
562 /* This should be /use/local/include and should come before
563 the fixincludes-fixed header files. */
564 { LOCAL_INCLUDE_DIR, 0},
565 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
566 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
567 { TOOL_INCLUDE_DIR, 0},
568 /* This is the dir for fixincludes. Put it just before
569 the files that we fix. */
570 { GCC_INCLUDE_DIR, 0},
571 /* Some systems have an extra dir of include files. */
572 #ifdef SYSTEM_INCLUDE_DIR
573 { SYSTEM_INCLUDE_DIR, 0},
575 { STANDARD_INCLUDE_DIR, 0},
576 #endif /* not CROSS_COMPILE */
579 #endif /* no INCLUDE_DEFAULTS */
581 /* The code looks at the defaults through this pointer, rather than through
582 the constant structure above. This pointer gets changed if an environment
583 variable specifies other defaults. */
584 static struct default_include *include_defaults = include_defaults_array;
586 static struct file_name_list *include = 0; /* First dir to search */
587 /* First dir to search for <file> */
588 /* This is the first element to use for #include <...>.
589 If it is 0, use the entire chain for such includes. */
590 static struct file_name_list *first_bracket_include = 0;
591 /* This is the first element in the chain that corresponds to
592 a directory of system header files. */
593 static struct file_name_list *first_system_include = 0;
594 static struct file_name_list *last_include = 0; /* Last in chain */
596 /* Chain of include directories to put at the end of the other chain. */
597 static struct file_name_list *after_include = 0;
598 static struct file_name_list *last_after_include = 0; /* Last in chain */
600 /* List of included files that contained #pragma once. */
601 static struct file_name_list *dont_repeat_files = 0;
603 /* List of other included files.
604 If ->control_macro if nonzero, the file had a #ifndef
605 around the entire contents, and ->control_macro gives the macro name. */
606 static struct file_name_list *all_include_files = 0;
608 /* Directory prefix that should replace `/usr' in the standard
609 include file directories. */
610 static char *include_prefix;
612 /* Global list of strings read in from precompiled files. This list
613 is kept in the order the strings are read in, with new strings being
614 added at the end through stringlist_tailp. We use this list to output
615 the strings at the end of the run.
617 static STRINGDEF *stringlist;
618 static STRINGDEF **stringlist_tailp = &stringlist;
621 /* Structure returned by create_definition */
622 typedef struct macrodef MACRODEF;
625 struct definition *defn;
630 static struct macrodef create_definition ();
633 /* Structure allocated for every #define. For a simple replacement
636 nargs = -1, the `pattern' list is null, and the expansion is just
637 the replacement text. Nargs = 0 means a functionlike macro with no args,
639 #define getchar() getc (stdin) .
640 When there are args, the expansion is the replacement text with the
641 args squashed out, and the reflist is a list describing how to
642 build the output from the input: e.g., "3 chars, then the 1st arg,
643 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
644 The chars here come from the expansion. Whatever is left of the
645 expansion after the last arg-occurrence is copied after that arg.
646 Note that the reflist can be arbitrarily long---
647 its length depends on the number of times the arguments appear in
648 the replacement text, not how many args there are. Example:
649 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
651 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
652 where (x, y) means (nchars, argno). */
654 typedef struct definition DEFINITION;
657 int length; /* length of expansion string */
658 int predefined; /* True if the macro was builtin or */
659 /* came from the command line */
661 int line; /* Line number of definition */
662 char *file; /* File of definition */
663 char rest_args; /* Nonzero if last arg. absorbs the rest */
665 struct reflist *next;
666 char stringify; /* nonzero if this arg was preceded by a
668 char raw_before; /* Nonzero if a ## operator before arg. */
669 char raw_after; /* Nonzero if a ## operator after arg. */
670 char rest_args; /* Nonzero if this arg. absorbs the rest */
671 int nchars; /* Number of literal chars to copy before
672 this arg occurrence. */
673 int argno; /* Number of arg to substitute (origin-0) */
676 /* Names of macro args, concatenated in reverse order
677 with comma-space between them.
678 The only use of this is that we warn on redefinition
679 if this differs between the old and new definitions. */
684 /* different kinds of things that can appear in the value field
685 of a hash node. Actually, this may be useless now. */
694 * special extension string that can be added to the last macro argument to
695 * allow it to absorb the "rest" of the arguments when expanded. Ex:
696 * #define wow(a, b...) process (b, a, b)
697 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
698 * { wow (one, two); } -> { process (two, one, two); }
699 * if this "rest_arg" is used with the concat token '##' and if it is not
700 * supplied then the token attached to with ## will not be outputted. Ex:
701 * #define wow (a, b...) process (b ## , a, ## b)
702 * { wow (1, 2); } -> { process (2, 1, 2); }
703 * { wow (one); } -> { process (one); {
705 static char rest_extension[] = "...";
706 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
708 /* The structure of a node in the hash table. The hash table
709 has entries for all tokens defined by #define commands (type T_MACRO),
710 plus some special tokens like __LINE__ (these each have their own
711 type, and the appropriate code is run when that type of node is seen.
712 It does not contain control words like "#define", which are recognized
713 by a separate piece of code. */
715 /* different flavors of hash nodes --- also used in keyword table */
717 T_DEFINE = 1, /* the `#define' keyword */
718 T_INCLUDE, /* the `#include' keyword */
719 T_INCLUDE_NEXT, /* the `#include_next' keyword */
720 T_IMPORT, /* the `#import' keyword */
721 T_IFDEF, /* the `#ifdef' keyword */
722 T_IFNDEF, /* the `#ifndef' keyword */
723 T_IF, /* the `#if' keyword */
724 T_ELSE, /* `#else' */
725 T_PRAGMA, /* `#pragma' */
726 T_ELIF, /* `#elif' */
727 T_UNDEF, /* `#undef' */
728 T_LINE, /* `#line' */
729 T_ERROR, /* `#error' */
730 T_WARNING, /* `#warning' */
731 T_ENDIF, /* `#endif' */
732 T_SCCS, /* `#sccs', used on system V. */
733 T_IDENT, /* `#ident', used on system V. */
734 T_ASSERT, /* `#assert', taken from system V. */
735 T_UNASSERT, /* `#unassert', taken from system V. */
736 T_SPECLINE, /* special symbol `__LINE__' */
737 T_DATE, /* `__DATE__' */
738 T_FILE, /* `__FILE__' */
739 T_BASE_FILE, /* `__BASE_FILE__' */
740 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
741 T_VERSION, /* `__VERSION__' */
742 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
743 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
744 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
745 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
746 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
747 T_TIME, /* `__TIME__' */
748 T_CONST, /* Constant value, used by `__STDC__' */
749 T_MACRO, /* macro defined by `#define' */
750 T_DISABLED, /* macro temporarily turned off for rescan */
751 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
752 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
753 T_UNUSED /* Used for something not defined. */
757 struct hashnode *next; /* double links for easy deletion */
758 struct hashnode *prev;
759 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
760 chain is kept, in case the node is the head
761 of the chain and gets deleted. */
762 enum node_type type; /* type of special token */
763 int length; /* length of token, for quick comparison */
764 U_CHAR *name; /* the actual name */
765 union hashval value; /* pointer to expansion, or whatever */
768 typedef struct hashnode HASHNODE;
770 /* Some definitions for the hash table. The hash function MUST be
771 computed as shown in hashf () below. That is because the rescan
772 loop computes the hash value `on the fly' for most tokens,
773 in order to avoid the overhead of a lot of procedure calls to
774 the hashf () function. Hashf () only exists for the sake of
775 politeness, for use when speed isn't so important. */
777 #define HASHSIZE 1403
778 static HASHNODE *hashtab[HASHSIZE];
779 #define HASHSTEP(old, c) ((old << 2) + c)
780 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
782 /* Symbols to predefine. */
784 #ifdef CPP_PREDEFINES
785 static char *predefs = CPP_PREDEFINES;
787 static char *predefs = "";
790 /* We let tm.h override the types used here, to handle trivial differences
791 such as the choice of unsigned int or long unsigned int for size_t.
792 When machines start needing nontrivial differences in the size type,
793 it would be best to do something here to figure out automatically
794 from other information what type to use. */
796 /* The string value for __size_type__. */
799 #define SIZE_TYPE "long unsigned int"
802 /* The string value for __ptrdiff_type__. */
805 #define PTRDIFF_TYPE "long int"
808 /* The string value for __wchar_type__. */
811 #define WCHAR_TYPE "int"
814 /* The string value for __USER_LABEL_PREFIX__ */
816 #ifndef USER_LABEL_PREFIX
817 #define USER_LABEL_PREFIX ""
820 /* The string value for __REGISTER_PREFIX__ */
822 #ifndef REGISTER_PREFIX
823 #define REGISTER_PREFIX ""
826 /* In the definition of a #assert name, this structure forms
827 a list of the individual values asserted.
828 Each value is itself a list of "tokens".
829 These are strings that are compared by name. */
831 struct tokenlist_list {
832 struct tokenlist_list *next;
833 struct arglist *tokens;
836 struct assertion_hashnode {
837 struct assertion_hashnode *next; /* double links for easy deletion */
838 struct assertion_hashnode *prev;
839 /* also, a back pointer to this node's hash
840 chain is kept, in case the node is the head
841 of the chain and gets deleted. */
842 struct assertion_hashnode **bucket_hdr;
843 int length; /* length of token, for quick comparison */
844 U_CHAR *name; /* the actual name */
845 /* List of token-sequences. */
846 struct tokenlist_list *value;
849 typedef struct assertion_hashnode ASSERTION_HASHNODE;
851 /* Some definitions for the hash table. The hash function MUST be
852 computed as shown in hashf below. That is because the rescan
853 loop computes the hash value `on the fly' for most tokens,
854 in order to avoid the overhead of a lot of procedure calls to
855 the hashf function. hashf only exists for the sake of
856 politeness, for use when speed isn't so important. */
858 #define ASSERTION_HASHSIZE 37
859 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
861 /* Nonzero means inhibit macroexpansion of what seem to be
862 assertion tests, in rescan. For #if. */
863 static int assertions_flag;
865 /* `struct directive' defines one #-directive, including how to handle it. */
868 int length; /* Length of name */
869 int (*func)(); /* Function to handle directive */
870 char *name; /* Name of directive */
871 enum node_type type; /* Code which describes which directive. */
872 char angle_brackets; /* Nonzero => <...> is special. */
873 char traditional_comments; /* Nonzero: keep comments if -traditional. */
874 char pass_thru; /* Copy preprocessed directive to output file. */
877 /* Here is the actual list of #-directives, most-often-used first. */
879 static struct directive directive_table[] = {
880 { 6, do_define, "define", T_DEFINE, 0, 1},
881 { 2, do_if, "if", T_IF},
882 { 5, do_xifdef, "ifdef", T_IFDEF},
883 { 6, do_xifdef, "ifndef", T_IFNDEF},
884 { 5, do_endif, "endif", T_ENDIF},
885 { 4, do_else, "else", T_ELSE},
886 { 4, do_elif, "elif", T_ELIF},
887 { 4, do_line, "line", T_LINE},
888 { 7, do_include, "include", T_INCLUDE, 1},
889 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
890 { 6, do_include, "import", T_IMPORT, 1},
891 { 5, do_undef, "undef", T_UNDEF},
892 { 5, do_error, "error", T_ERROR},
893 { 7, do_warning, "warning", T_WARNING},
894 #ifdef SCCS_DIRECTIVE
895 { 4, do_sccs, "sccs", T_SCCS},
897 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
898 { 5, do_ident, "ident", T_IDENT, 0, 0, 1},
899 { 6, do_assert, "assert", T_ASSERT},
900 { 8, do_unassert, "unassert", T_UNASSERT},
901 { -1, 0, "", T_UNUSED},
904 /* When a directive handler is called,
905 this points to the # that started the directive. */
906 U_CHAR *directive_start;
908 /* table to tell if char can be part of a C identifier. */
909 U_CHAR is_idchar[256];
910 /* table to tell if char can be first char of a c identifier. */
911 U_CHAR is_idstart[256];
912 /* table to tell if c is horizontal space. */
913 U_CHAR is_hor_space[256];
914 /* table to tell if c is horizontal or vertical space. */
915 static U_CHAR is_space[256];
917 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
918 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
920 static int errors = 0; /* Error counter for exit code */
922 /* Name of output file, for error messages. */
923 static char *out_fname;
925 /* Zero means dollar signs are punctuation.
926 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
927 This must be 0 for correct processing of this ANSI C program:
929 #define lose(b) foo (b)
932 static int dollars_in_ident;
933 #ifndef DOLLARS_IN_IDENTIFIERS
934 #define DOLLARS_IN_IDENTIFIERS 1
937 static FILE_BUF expand_to_temp_buffer ();
939 static DEFINITION *collect_expansion ();
941 /* Stack of conditionals currently in progress
942 (including both successful and failing conditionals). */
945 struct if_stack *next; /* for chaining to the next stack frame */
946 char *fname; /* copied from input when frame is made */
947 int lineno; /* similarly */
948 int if_succeeded; /* true if a leg of this if-group
949 has been passed through rescan */
950 U_CHAR *control_macro; /* For #ifndef at start of file,
951 this is the macro name tested. */
952 enum node_type type; /* type of last directive seen in this group */
954 typedef struct if_stack IF_STACK_FRAME;
955 static IF_STACK_FRAME *if_stack = NULL;
957 /* Buffer of -M output. */
958 static char *deps_buffer;
960 /* Number of bytes allocated in above. */
961 static int deps_allocated_size;
963 /* Number of bytes used. */
964 static int deps_size;
966 /* Number of bytes since the last newline. */
967 static int deps_column;
969 /* Nonzero means -I- has been seen,
970 so don't look for #include "foo" the source-file directory. */
971 static int ignore_srcdir;
984 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
985 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
986 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
987 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
988 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
990 /* Record the option used with each element of pend_assertions.
991 This is preparation for supporting more than one option for making
993 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
994 int inhibit_predefs = 0;
995 int no_standard_includes = 0;
996 int no_standard_cplusplus_includes = 0;
997 int missing_newline = 0;
999 /* Non-0 means don't output the preprocessed program. */
1000 int inhibit_output = 0;
1002 /* File name which deps are being written to.
1003 This is 0 if deps are being written to stdout. */
1004 char *deps_file = 0;
1005 /* Fopen file mode to open deps_file with. */
1006 char *deps_mode = "a";
1007 /* Stream on which to print the dependency information. */
1008 FILE *deps_stream = 0;
1009 /* Target-name to write with the dependency information. */
1010 char *deps_target = 0;
1013 /* Get rid of any avoidable limit on stack size. */
1017 /* Set the stack limit huge so that alloca (particularly stringtab
1018 * in dbxread.c) does not fail. */
1019 getrlimit (RLIMIT_STACK, &rlim);
1020 rlim.rlim_cur = rlim.rlim_max;
1021 setrlimit (RLIMIT_STACK, &rlim);
1023 #endif /* RLIMIT_STACK defined */
1025 signal (SIGPIPE, pipe_closed);
1027 p = argv[0] + strlen (argv[0]);
1028 while (p != argv[0] && p[-1] != '/') --p;
1033 /* Remove directories from PROGNAME. */
1036 progname = savestring (argv[0]);
1038 if (!(s = rindex (progname, ']')))
1039 s = rindex (progname, ':');
1041 strcpy (progname, s+1);
1042 if (s = rindex (progname, '.'))
1050 /* Initialize is_idchar to allow $. */
1051 dollars_in_ident = 1;
1052 initialize_char_syntax ();
1053 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1055 no_line_commands = 0;
1057 dump_macros = dump_none;
1060 cplusplus_comments = 0;
1062 bzero (pend_files, argc * sizeof (char *));
1063 bzero (pend_defs, argc * sizeof (char *));
1064 bzero (pend_undefs, argc * sizeof (char *));
1065 bzero (pend_assertions, argc * sizeof (char *));
1066 bzero (pend_includes, argc * sizeof (char *));
1068 /* Process switches and find input file name. */
1070 for (i = 1; i < argc; i++) {
1071 if (argv[i][0] != '-') {
1072 if (out_fname != NULL)
1073 fatal ("Usage: %s [switches] input output", argv[0]);
1074 else if (in_fname != NULL)
1075 out_fname = argv[i];
1079 switch (argv[i][1]) {
1082 if (!strcmp (argv[i], "-include")) {
1084 fatal ("Filename missing after `-include' option");
1086 pend_includes[i] = argv[i+1], i++;
1088 if (!strcmp (argv[i], "-imacros")) {
1090 fatal ("Filename missing after `-imacros' option");
1092 pend_files[i] = argv[i+1], i++;
1094 if (!strcmp (argv[i], "-iprefix")) {
1096 fatal ("Filename missing after `-iprefix' option");
1098 include_prefix = argv[++i];
1100 /* Add directory to end of path for includes,
1101 with the default prefix at the front of its name. */
1102 if (!strcmp (argv[i], "-iwithprefix")) {
1103 struct file_name_list *dirtmp;
1106 if (include_prefix != 0)
1107 prefix = include_prefix;
1109 prefix = savestring (GCC_INCLUDE_DIR);
1110 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1111 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1112 prefix[strlen (prefix) - 7] = 0;
1115 dirtmp = (struct file_name_list *)
1116 xmalloc (sizeof (struct file_name_list));
1117 dirtmp->next = 0; /* New one goes on the end */
1118 dirtmp->control_macro = 0;
1120 fatal ("Directory name missing after `-iwithprefix' option");
1122 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1123 + strlen (prefix) + 1);
1124 strcpy (dirtmp->fname, prefix);
1125 strcat (dirtmp->fname, argv[++i]);
1127 if (after_include == 0)
1128 after_include = dirtmp;
1130 last_after_include->next = dirtmp;
1131 last_after_include = dirtmp; /* Tail follows the last one */
1133 /* Add directory to main path for includes,
1134 with the default prefix at the front of its name. */
1135 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1136 struct file_name_list *dirtmp;
1139 if (include_prefix != 0)
1140 prefix = include_prefix;
1142 prefix = savestring (GCC_INCLUDE_DIR);
1143 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1144 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1145 prefix[strlen (prefix) - 7] = 0;
1148 dirtmp = (struct file_name_list *)
1149 xmalloc (sizeof (struct file_name_list));
1150 dirtmp->next = 0; /* New one goes on the end */
1151 dirtmp->control_macro = 0;
1153 fatal ("Directory name missing after `-iwithprefixbefore' option");
1155 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1156 + strlen (prefix) + 1);
1157 strcpy (dirtmp->fname, prefix);
1158 strcat (dirtmp->fname, argv[++i]);
1160 append_include_chain (dirtmp, dirtmp);
1162 /* Add directory to end of path for includes. */
1163 if (!strcmp (argv[i], "-idirafter")) {
1164 struct file_name_list *dirtmp;
1166 dirtmp = (struct file_name_list *)
1167 xmalloc (sizeof (struct file_name_list));
1168 dirtmp->next = 0; /* New one goes on the end */
1169 dirtmp->control_macro = 0;
1171 fatal ("Directory name missing after `-idirafter' option");
1173 dirtmp->fname = argv[++i];
1175 if (after_include == 0)
1176 after_include = dirtmp;
1178 last_after_include->next = dirtmp;
1179 last_after_include = dirtmp; /* Tail follows the last one */
1184 if (out_fname != NULL)
1185 fatal ("Output filename specified twice");
1187 fatal ("Filename missing after -o option");
1188 out_fname = argv[++i];
1189 if (!strcmp (out_fname, "-"))
1194 if (!strcmp (argv[i], "-pedantic"))
1196 else if (!strcmp (argv[i], "-pedantic-errors")) {
1198 pedantic_errors = 1;
1199 } else if (!strcmp (argv[i], "-pcp")) {
1200 char *pcp_fname = argv[++i];
1202 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1203 ? fopen (pcp_fname, "w")
1204 : fdopen (dup (fileno (stdout)), "w"));
1205 if (pcp_outfile == 0)
1206 pfatal_with_name (pcp_fname);
1212 if (!strcmp (argv[i], "-traditional")) {
1214 if (dollars_in_ident > 0)
1215 dollars_in_ident = 1;
1216 } else if (!strcmp (argv[i], "-trigraphs")) {
1222 if (! strcmp (argv[i], "-lang-c"))
1223 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1224 if (! strcmp (argv[i], "-lang-c++"))
1225 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1226 if (! strcmp (argv[i], "-lang-objc"))
1227 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1228 if (! strcmp (argv[i], "-lang-objc++"))
1229 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1230 if (! strcmp (argv[i], "-lang-asm"))
1232 if (! strcmp (argv[i], "-lint"))
1237 cplusplus = 1, cplusplus_comments = 1;
1241 inhibit_warnings = 1;
1245 if (!strcmp (argv[i], "-Wtrigraphs"))
1247 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1249 else if (!strcmp (argv[i], "-Wcomment"))
1251 else if (!strcmp (argv[i], "-Wno-comment"))
1253 else if (!strcmp (argv[i], "-Wcomments"))
1255 else if (!strcmp (argv[i], "-Wno-comments"))
1257 else if (!strcmp (argv[i], "-Wtraditional"))
1259 else if (!strcmp (argv[i], "-Wno-traditional"))
1261 else if (!strcmp (argv[i], "-Wimport"))
1263 else if (!strcmp (argv[i], "-Wno-import"))
1265 else if (!strcmp (argv[i], "-Werror"))
1266 warnings_are_errors = 1;
1267 else if (!strcmp (argv[i], "-Wno-error"))
1268 warnings_are_errors = 0;
1269 else if (!strcmp (argv[i], "-Wall"))
1277 if (!strcmp (argv[i], "-M"))
1279 else if (!strcmp (argv[i], "-MM"))
1281 else if (!strcmp (argv[i], "-MD"))
1283 else if (!strcmp (argv[i], "-MMD"))
1285 /* For -MD and -MMD options, write deps on file named by next arg. */
1286 if (!strcmp (argv[i], "-MD")
1287 || !strcmp (argv[i], "-MMD")) {
1289 deps_file = argv[i];
1292 /* For -M and -MM, write deps on standard output
1293 and suppress the usual output. */
1294 deps_stream = stdout;
1301 char *p = argv[i] + 2;
1304 /* Arg to -d specifies what parts of macros to dump */
1307 dump_macros = dump_only;
1311 dump_macros = dump_names;
1314 dump_macros = dump_definitions;
1322 if (argv[i][2] == '3')
1327 fprintf (stderr, "GNU CPP version %s", version_string);
1328 #ifdef TARGET_VERSION
1331 fprintf (stderr, "\n");
1335 print_include_names = 1;
1342 if (argv[i][2] != 0)
1344 else if (i + 1 == argc)
1345 fatal ("Macro name missing after -D option");
1357 if (argv[i][2] != 0)
1359 else if (i + 1 == argc)
1360 fatal ("Assertion missing after -A option");
1364 if (!strcmp (p, "-")) {
1365 /* -A- eliminates all predefined macros and assertions.
1366 Let's include also any that were specified earlier
1367 on the command line. That way we can get rid of any
1368 that were passed automatically in from GCC. */
1370 inhibit_predefs = 1;
1371 for (j = 0; j < i; j++)
1372 pend_defs[j] = pend_assertions[j] = 0;
1374 pend_assertions[i] = p;
1375 pend_assertion_options[i] = "-A";
1380 case 'U': /* JF #undef something */
1381 if (argv[i][2] != 0)
1382 pend_undefs[i] = argv[i] + 2;
1383 else if (i + 1 == argc)
1384 fatal ("Macro name missing after -U option");
1386 pend_undefs[i] = argv[i+1], i++;
1390 put_out_comments = 1;
1393 case 'E': /* -E comes from cc -E; ignore it. */
1397 no_line_commands = 1;
1400 case '$': /* Don't include $ in identifiers. */
1401 dollars_in_ident = 0;
1404 case 'I': /* Add directory to path for includes. */
1406 struct file_name_list *dirtmp;
1408 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1410 /* Don't use any preceding -I directories for #include <...>. */
1411 first_bracket_include = 0;
1414 dirtmp = (struct file_name_list *)
1415 xmalloc (sizeof (struct file_name_list));
1416 dirtmp->next = 0; /* New one goes on the end */
1417 dirtmp->control_macro = 0;
1418 if (argv[i][2] != 0)
1419 dirtmp->fname = argv[i] + 2;
1420 else if (i + 1 == argc)
1421 fatal ("Directory name missing after -I option");
1423 dirtmp->fname = argv[++i];
1424 append_include_chain (dirtmp, dirtmp);
1430 if (!strcmp (argv[i], "-nostdinc"))
1431 /* -nostdinc causes no default include directories.
1432 You must specify all include-file directories with -I. */
1433 no_standard_includes = 1;
1434 else if (!strcmp (argv[i], "-nostdinc++"))
1435 /* -nostdinc++ causes no default C++-specific include directories. */
1436 no_standard_cplusplus_includes = 1;
1437 else if (!strcmp (argv[i], "-noprecomp"))
1442 /* Sun compiler passes undocumented switch "-undef".
1443 Let's assume it means to inhibit the predefined symbols. */
1444 inhibit_predefs = 1;
1447 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1448 if (in_fname == NULL) {
1451 } else if (out_fname == NULL) {
1454 } /* else fall through into error */
1457 fatal ("Invalid option `%s'", argv[i]);
1462 /* Add dirs from CPATH after dirs from -I. */
1463 /* There seems to be confusion about what CPATH should do,
1464 so for the moment it is not documented. */
1465 /* Some people say that CPATH should replace the standard include dirs,
1466 but that seems pointless: it comes before them, so it overrides them
1468 p = (char *) getenv ("CPATH");
1469 if (p != 0 && ! no_standard_includes)
1472 /* Now that dollars_in_ident is known, initialize is_idchar. */
1473 initialize_char_syntax ();
1475 /* Initialize output buffer */
1477 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1478 outbuf.bufp = outbuf.buf;
1479 outbuf.length = OUTBUF_SIZE;
1481 /* Do partial setup of input buffer for the sake of generating
1482 early #line directives (when -g is in effect). */
1484 fp = &instack[++indepth];
1485 if (in_fname == NULL)
1487 fp->nominal_fname = fp->fname = in_fname;
1490 /* Install __LINE__, etc. Must follow initialize_char_syntax
1491 and option processing. */
1492 initialize_builtins (fp, &outbuf);
1494 /* Do standard #defines and assertions
1495 that identify system and machine type. */
1497 if (!inhibit_predefs) {
1498 char *p = (char *) alloca (strlen (predefs) + 1);
1499 strcpy (p, predefs);
1502 while (*p == ' ' || *p == '\t')
1504 /* Handle -D options. */
1505 if (p[0] == '-' && p[1] == 'D') {
1507 while (*p && *p != ' ' && *p != '\t')
1512 output_line_command (fp, &outbuf, 0, same_file);
1513 make_definition (q, &outbuf);
1514 while (*p == ' ' || *p == '\t')
1516 } else if (p[0] == '-' && p[1] == 'A') {
1517 /* Handle -A options (assertions). */
1526 past_name = assertion;
1527 /* Locate end of name. */
1528 while (*past_name && *past_name != ' '
1529 && *past_name != '\t' && *past_name != '(')
1531 /* Locate `(' at start of value. */
1533 while (*value && (*value == ' ' || *value == '\t'))
1535 if (*value++ != '(')
1537 while (*value && (*value == ' ' || *value == '\t'))
1540 /* Locate end of value. */
1541 while (*past_value && *past_value != ' '
1542 && *past_value != '\t' && *past_value != ')')
1544 termination = past_value;
1545 while (*termination && (*termination == ' ' || *termination == '\t'))
1547 if (*termination++ != ')')
1549 if (*termination && *termination != ' ' && *termination != '\t')
1551 /* Temporarily null-terminate the value. */
1552 save_char = *termination;
1553 *termination = '\0';
1554 /* Install the assertion. */
1555 make_assertion ("-A", assertion);
1556 *termination = (char) save_char;
1558 while (*p == ' ' || *p == '\t')
1566 /* Now handle the command line options. */
1568 /* Do -U's, -D's and -A's in the order they were seen. */
1569 for (i = 1; i < argc; i++) {
1570 if (pend_undefs[i]) {
1572 output_line_command (fp, &outbuf, 0, same_file);
1573 make_undef (pend_undefs[i], &outbuf);
1577 output_line_command (fp, &outbuf, 0, same_file);
1578 make_definition (pend_defs[i], &outbuf);
1580 if (pend_assertions[i])
1581 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1584 done_initializing = 1;
1586 { /* read the appropriate environment variable and if it exists
1587 replace include_defaults with the listed path. */
1589 switch ((objc << 1) + cplusplus)
1592 epath = getenv ("C_INCLUDE_PATH");
1595 epath = getenv ("CPLUS_INCLUDE_PATH");
1598 epath = getenv ("OBJC_INCLUDE_PATH");
1601 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1604 /* If the environment var for this language is set,
1605 add to the default list of include directories. */
1607 char *nstore = (char *) alloca (strlen (epath) + 2);
1609 char *startp, *endp;
1611 for (num_dirs = 1, startp = epath; *startp; startp++)
1612 if (*startp == PATH_SEPARATOR)
1615 = (struct default_include *) xmalloc ((num_dirs
1616 * sizeof (struct default_include))
1617 + sizeof (include_defaults_array));
1618 startp = endp = epath;
1621 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1622 if ((*endp == PATH_SEPARATOR
1623 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
1625 && (endp-startp != 1 || !isalpha (*startp))
1630 strncpy (nstore, startp, endp-startp);
1632 strcpy (nstore, ".");
1634 nstore[endp-startp] = '\0';
1636 include_defaults[num_dirs].fname = savestring (nstore);
1637 include_defaults[num_dirs].cplusplus = cplusplus;
1641 endp = startp = endp + 1;
1645 /* Put the usual defaults back in at the end. */
1646 bcopy (include_defaults_array, &include_defaults[num_dirs],
1647 sizeof (include_defaults_array));
1651 first_system_include = 0;
1652 /* Unless -fnostdinc,
1653 tack on the standard include file dirs to the specified list */
1654 if (!no_standard_includes) {
1655 struct default_include *p = include_defaults;
1656 char *specd_prefix = include_prefix;
1657 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1658 int default_len = 0;
1659 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1660 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1661 default_len = strlen (default_prefix) - 7;
1662 default_prefix[default_len] = 0;
1664 /* Search "translated" versions of GNU directories.
1665 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1666 if (specd_prefix != 0 && default_len != 0)
1667 for (p = include_defaults; p->fname; p++) {
1668 /* Some standard dirs are only for C++. */
1669 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1670 /* Does this dir start with the prefix? */
1671 if (!strncmp (p->fname, default_prefix, default_len)) {
1672 /* Yes; change prefix and add to search list. */
1673 struct file_name_list *new
1674 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1675 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
1676 char *str = (char *) xmalloc (this_len + 1);
1677 strcpy (str, specd_prefix);
1678 strcat (str, p->fname + default_len);
1680 new->control_macro = 0;
1681 append_include_chain (new, new);
1682 if (first_system_include == 0)
1683 first_system_include = new;
1687 /* Search ordinary names for GNU include directories. */
1688 for (p = include_defaults; p->fname; p++) {
1689 /* Some standard dirs are only for C++. */
1690 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1691 struct file_name_list *new
1692 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1693 new->control_macro = 0;
1694 new->fname = p->fname;
1695 append_include_chain (new, new);
1696 if (first_system_include == 0)
1697 first_system_include = new;
1702 /* Tack the after_include chain at the end of the include chain. */
1703 append_include_chain (after_include, last_after_include);
1704 if (first_system_include == 0)
1705 first_system_include = after_include;
1707 /* Scan the -imacros files before the main input.
1708 Much like #including them, but with no_output set
1709 so that only their macro definitions matter. */
1712 for (i = 1; i < argc; i++)
1713 if (pend_files[i]) {
1714 int fd = open (pend_files[i], O_RDONLY, 0666);
1716 perror_with_name (pend_files[i]);
1717 return FAILURE_EXIT_CODE;
1719 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
1723 /* Copy the entire contents of the main input file into
1724 the stacked input buffer previously allocated for it. */
1726 /* JF check for stdin */
1727 if (in_fname == NULL || *in_fname == 0) {
1730 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
1733 /* Either of two environment variables can specify output of deps.
1734 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1735 where OUTPUT_FILE is the file to write deps info to
1736 and DEPS_TARGET is the target to mention in the deps. */
1739 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1740 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1741 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1746 spec = getenv ("SUNPRO_DEPENDENCIES");
1753 /* Find the space before the DEPS_TARGET, if there is one. */
1754 /* This should use index. (mrs) */
1755 while (*s != 0 && *s != ' ') s++;
1757 deps_target = s + 1;
1758 output_file = (char *) xmalloc (s - spec + 1);
1759 bcopy (spec, output_file, s - spec);
1760 output_file[s - spec] = 0;
1767 deps_file = output_file;
1771 /* For -M, print the expected object file name
1772 as the target of this Make-rule. */
1774 deps_allocated_size = 200;
1775 deps_buffer = (char *) xmalloc (deps_allocated_size);
1781 deps_output (deps_target, 0);
1782 deps_output (":", 0);
1783 } else if (*in_fname == 0)
1784 deps_output ("-: ", 0);
1789 /* Discard all directory prefixes from P. */
1795 /* Output P, but remove known suffixes. */
1797 if (p[len - 2] == '.' && p[len - 1] == 'c')
1798 deps_output (p, len - 2);
1799 else if (p[len - 2] == '.' && p[len - 1] == 'C')
1800 deps_output (p, len - 2);
1801 else if (p[len - 3] == '.'
1802 && p[len - 2] == 'c'
1803 && p[len - 1] == 'c')
1804 deps_output (p, len - 3);
1805 else if (p[len - 4] == '.'
1806 && p[len - 3] == 'c'
1807 && p[len - 2] == 'x'
1808 && p[len - 1] == 'x')
1809 deps_output (p, len - 4);
1810 else if (p[len - 2] == '.' && p[len - 1] == 's')
1811 deps_output (p, len - 2);
1812 else if (p[len - 2] == '.' && p[len - 1] == 'S')
1813 deps_output (p, len - 2);
1814 else if (p[len - 2] == '.' && p[len - 1] == 'm')
1815 deps_output (p, len - 2);
1818 /* Supply our own suffix. */
1820 deps_output (".o : ", 0);
1822 deps_output (".obj : ", 0);
1824 deps_output (in_fname, 0);
1825 deps_output (" ", 0);
1829 file_size_and_mode (f, &st_mode, &st_size);
1830 fp->nominal_fname = fp->fname = in_fname;
1832 fp->system_header_p = 0;
1833 /* JF all this is mine about reading pipes and ttys */
1834 if (! S_ISREG (st_mode)) {
1835 /* Read input from a file that is not a normal disk file.
1836 We cannot preallocate a buffer with the correct size,
1837 so we must read in the file a piece at the time and make it bigger. */
1845 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
1848 cnt = read (f, bufp, bsize - size);
1849 if (cnt < 0) goto perror; /* error! */
1850 if (cnt == 0) break; /* End of file */
1853 if (bsize == size) { /* Buffer is full! */
1855 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
1856 bufp = fp->buf + size; /* May have moved */
1861 /* Read a file whose size we can determine in advance.
1862 For the sake of VMS, st_size is just an upper bound. */
1865 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
1867 while (st_size > 0) {
1868 i = read (f, fp->buf + fp->length, st_size);
1878 fp->if_stack = if_stack;
1880 /* Make sure data ends with a newline. And put a null after it. */
1882 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
1883 /* Backslash-newline at end is not good enough. */
1884 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
1885 fp->buf[fp->length++] = '\n';
1886 missing_newline = 1;
1888 fp->buf[fp->length] = '\0';
1890 /* Unless inhibited, convert trigraphs in the input. */
1895 /* Now that we know the input file is valid, open the output. */
1897 if (!out_fname || !strcmp (out_fname, ""))
1898 out_fname = "stdout";
1899 else if (! freopen (out_fname, "w", stdout))
1900 pfatal_with_name (out_fname);
1902 output_line_command (fp, &outbuf, 0, same_file);
1904 /* Scan the -include files before the main input. */
1906 for (i = 1; i < argc; i++)
1907 if (pend_includes[i]) {
1908 int fd = open (pend_includes[i], O_RDONLY, 0666);
1910 perror_with_name (pend_includes[i]);
1911 return FAILURE_EXIT_CODE;
1913 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
1916 /* Scan the input, processing macros and directives. */
1918 rescan (&outbuf, 0);
1920 if (missing_newline)
1923 if (pedantic && missing_newline)
1924 pedwarn ("file does not end in newline");
1926 /* Now we have processed the entire input
1927 Write whichever kind of output has been requested. */
1929 if (dump_macros == dump_only)
1931 else if (! inhibit_output) {
1936 /* Don't actually write the deps file if compilation has failed. */
1938 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
1939 pfatal_with_name (deps_file);
1940 fputs (deps_buffer, deps_stream);
1941 putc ('\n', deps_stream);
1943 if (ferror (deps_stream) || fclose (deps_stream) != 0)
1944 fatal ("I/O error on output");
1949 if (pcp_outfile && pcp_outfile != stdout
1950 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
1951 fatal ("I/O error on `-pcp' output");
1953 if (ferror (stdout) || fclose (stdout) != 0)
1954 fatal ("I/O error on output");
1957 exit (FAILURE_EXIT_CODE);
1958 exit (SUCCESS_EXIT_CODE);
1961 pfatal_with_name (in_fname);
1965 /* Given a colon-separated list of file names PATH,
1966 add all the names to the search path for include files. */
1980 struct file_name_list *dirtmp;
1982 /* Find the end of this name. */
1983 while (*q != 0 && *q != PATH_SEPARATOR) q++;
1985 /* An empty name in the path stands for the current directory. */
1986 name = (char *) xmalloc (2);
1990 /* Otherwise use the directory that is named. */
1991 name = (char *) xmalloc (q - p + 1);
1992 bcopy (p, name, q - p);
1996 dirtmp = (struct file_name_list *)
1997 xmalloc (sizeof (struct file_name_list));
1998 dirtmp->next = 0; /* New one goes on the end */
1999 dirtmp->control_macro = 0;
2000 dirtmp->fname = name;
2001 append_include_chain (dirtmp, dirtmp);
2003 /* Advance past this name. */
2007 /* Skip the colon. */
2012 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2013 before main CCCP processing. Name `pcp' is also in honor of the
2014 drugs the trigraph designers must have been on.
2016 Using an extra pass through the buffer takes a little extra time,
2017 but is infinitely less hairy than trying to handle trigraphs inside
2018 strings, etc. everywhere, and also makes sure that trigraphs are
2019 only translated in the top level of processing. */
2025 register U_CHAR c, *fptr, *bptr, *sptr;
2028 fptr = bptr = sptr = buf->buf;
2029 while ((sptr = (U_CHAR *) index (sptr, '?')) != NULL) {
2066 len = sptr - fptr - 2;
2067 if (bptr != fptr && len > 0)
2068 bcopy (fptr, bptr, len); /* BSD doc says bcopy () works right
2069 for overlapping strings. In ANSI
2070 C, this will be memmove (). */
2075 len = buf->length - (fptr - buf->buf);
2076 if (bptr != fptr && len > 0)
2077 bcopy (fptr, bptr, len);
2078 buf->length -= fptr - bptr;
2079 buf->buf[buf->length] = '\0';
2080 if (warn_trigraphs && fptr != bptr)
2081 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
2084 /* Move all backslash-newline pairs out of embarrassing places.
2085 Exchange all such pairs following BP
2086 with any potentially-embarrassing characters that follow them.
2087 Potentially-embarrassing characters are / and *
2088 (because a backslash-newline inside a comment delimiter
2089 would cause it not to be recognized). */
2095 register U_CHAR *p = bp;
2096 register int count = 0;
2098 /* First count the backslash-newline pairs here. */
2104 else if (p[1] == '\r' && p[2] == '\n')
2112 /* What follows the backslash-newlines is not embarrassing. */
2114 if (count == 0 || (*p != '/' && *p != '*'))
2117 /* Copy all potentially embarrassing characters
2118 that follow the backslash-newline pairs
2119 down to where the pairs originally started. */
2121 while (*p == '*' || *p == '/')
2124 /* Now write the same number of pairs after the embarrassing chars. */
2125 while (count-- > 0) {
2131 /* Like newline_fix but for use within a directive-name.
2132 Move any backslash-newlines up past any following symbol constituents. */
2135 name_newline_fix (bp)
2138 register U_CHAR *p = bp;
2139 register int count = 0;
2141 /* First count the backslash-newline pairs here. */
2146 else if (p[1] == '\r' && p[2] == '\n')
2154 /* What follows the backslash-newlines is not embarrassing. */
2156 if (count == 0 || !is_idchar[*p])
2159 /* Copy all potentially embarrassing characters
2160 that follow the backslash-newline pairs
2161 down to where the pairs originally started. */
2163 while (is_idchar[*p])
2166 /* Now write the same number of pairs after the embarrassing chars. */
2167 while (count-- > 0) {
2173 /* Look for lint commands in comments.
2175 When we come in here, ibp points into a comment. Limit is as one expects.
2176 scan within the comment -- it should start, after lwsp, with a lint command.
2177 If so that command is returned as a (constant) string.
2179 Upon return, any arg will be pointed to with argstart and will be
2180 arglen long. Note that we don't parse that arg since it will just
2181 be printed out again.
2185 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2186 register U_CHAR *ibp;
2187 register U_CHAR *limit;
2188 U_CHAR **argstart; /* point to command arg */
2189 int *arglen, *cmdlen; /* how long they are */
2192 register U_CHAR *numptr; /* temp for arg parsing */
2196 SKIP_WHITE_SPACE (ibp);
2198 if (ibp >= limit) return NULL;
2200 linsize = limit - ibp;
2202 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2203 if ((linsize >= 10) && !strncmp (ibp, "NOTREACHED", 10)) {
2205 return "NOTREACHED";
2207 if ((linsize >= 8) && !strncmp (ibp, "ARGSUSED", 8)) {
2211 if ((linsize >= 11) && !strncmp (ibp, "LINTLIBRARY", 11)) {
2213 return "LINTLIBRARY";
2215 if ((linsize >= 7) && !strncmp (ibp, "VARARGS", 7)) {
2217 ibp += 7; linsize -= 7;
2218 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2220 /* OK, read a number */
2221 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2223 *arglen = numptr - *argstart;
2230 * The main loop of the program.
2232 * Read characters from the input stack, transferring them to the
2235 * Macros are expanded and push levels on the input stack.
2236 * At the end of such a level it is popped off and we keep reading.
2237 * At the end of any other kind of level, we return.
2238 * #-directives are handled, except within macros.
2240 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2241 * and insert them when appropriate. This is set while scanning macro
2242 * arguments before substitution. It is zero when scanning for final output.
2243 * There are three types of Newline markers:
2244 * * Newline - follows a macro name that was not expanded
2245 * because it appeared inside an expansion of the same macro.
2246 * This marker prevents future expansion of that identifier.
2247 * When the input is rescanned into the final output, these are deleted.
2248 * These are also deleted by ## concatenation.
2249 * * Newline Space (or Newline and any other whitespace character)
2250 * stands for a place that tokens must be separated or whitespace
2251 * is otherwise desirable, but where the ANSI standard specifies there
2252 * is no whitespace. This marker turns into a Space (or whichever other
2253 * whitespace char appears in the marker) in the final output,
2254 * but it turns into nothing in an argument that is stringified with #.
2255 * Such stringified arguments are the only place where the ANSI standard
2256 * specifies with precision that whitespace may not appear.
2258 * During this function, IP->bufp is kept cached in IBP for speed of access.
2259 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2260 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2261 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2262 * explicitly, and before RECACHE, since RECACHE uses OBP.
2266 rescan (op, output_marks)
2270 /* Character being scanned in main loop. */
2273 /* Length of pending accumulated identifier. */
2274 register int ident_length = 0;
2276 /* Hash code of pending accumulated identifier. */
2277 register int hash = 0;
2279 /* Current input level (&instack[indepth]). */
2282 /* Pointer for scanning input. */
2283 register U_CHAR *ibp;
2285 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2286 register U_CHAR *limit;
2288 /* Pointer for storing output. */
2289 register U_CHAR *obp;
2291 /* REDO_CHAR is nonzero if we are processing an identifier
2292 after backing up over the terminating character.
2293 Sometimes we process an identifier without backing up over
2294 the terminating character, if the terminating character
2295 is not special. Backing up is done so that the terminating character
2296 will be dispatched on again once the identifier is dealt with. */
2299 /* 1 if within an identifier inside of which a concatenation
2300 marker (Newline -) has been seen. */
2301 int concatenated = 0;
2303 /* While scanning a comment or a string constant,
2304 this records the line it started on, for error messages. */
2307 /* Record position of last `real' newline. */
2308 U_CHAR *beg_of_line;
2310 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2313 do { ip->macro->type = T_MACRO; \
2314 if (ip->free_ptr) free (ip->free_ptr); \
2315 --indepth; } while (0)
2317 /* Reload `rescan's local variables that describe the current
2318 level of the input stack. */
2321 do { ip = &instack[indepth]; \
2323 limit = ip->buf + ip->length; \
2325 check_expand (op, limit - ibp); \
2327 obp = op->bufp; } while (0)
2329 if (no_output && instack[indepth].fname != 0)
2330 skip_if_group (&instack[indepth], 1);
2337 /* Our caller must always put a null after the end of
2338 the input at each input stack level. */
2351 /* Always merge lines ending with backslash-newline,
2352 even in middle of identifier. */
2355 --obp; /* remove backslash from obuf */
2358 /* Otherwise, backslash suppresses specialness of following char,
2359 so copy it here to prevent the switch from seeing it.
2360 But first get any pending identifier processed. */
2361 if (ident_length > 0)
2367 if (assertions_flag) {
2368 /* Copy #foo (bar lose) without macro expansion. */
2369 SKIP_WHITE_SPACE (ibp);
2370 while (is_idchar[*ibp])
2372 SKIP_WHITE_SPACE (ibp);
2375 skip_paren_group (ip);
2376 bcopy (ibp, obp, ip->bufp - ibp);
2377 obp += ip->bufp - ibp;
2382 /* If this is expanding a macro definition, don't recognize
2383 preprocessor directives. */
2386 /* If this is expand_into_temp_buffer, recognize them
2387 only after an actual newline at this level,
2388 not at the beginning of the input level. */
2389 if (ip->fname == 0 && beg_of_line == ip->buf)
2395 /* # keyword: a # must be first nonblank char on the line */
2396 if (beg_of_line == 0)
2401 /* Scan from start of line, skipping whitespace, comments
2402 and backslash-newlines, and see if we reach this #.
2403 If not, this # is not special. */
2405 /* If -traditional, require # to be at beginning of line. */
2408 if (is_hor_space[*bp])
2410 else if (*bp == '\\' && bp[1] == '\n')
2412 else if (*bp == '/' && bp[1] == '*') {
2414 while (!(*bp == '*' && bp[1] == '/'))
2418 else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
2420 while (*bp++ != '\n') ;
2428 /* This # can start a directive. */
2430 --obp; /* Don't copy the '#' */
2434 if (! handle_directive (ip, op)) {
2438 /* Not a known directive: treat it as ordinary text.
2439 IP, OP, IBP, etc. have not been changed. */
2440 if (no_output && instack[indepth].fname) {
2441 /* If not generating expanded output,
2442 what we do with ordinary text is skip it.
2443 Discard everything until next # directive. */
2444 skip_if_group (&instack[indepth], 1);
2449 ++obp; /* Copy the '#' after all */
2455 /* A # directive has been successfully processed. */
2456 /* If not generating expanded output, ignore everything until
2457 next # directive. */
2458 if (no_output && instack[indepth].fname)
2459 skip_if_group (&instack[indepth], 1);
2465 case '\"': /* skip quoted string */
2467 /* A single quoted string is treated like a double -- some
2468 programs (e.g., troff) are perverse this way */
2473 start_line = ip->lineno;
2475 /* Skip ahead to a matching quote. */
2479 if (ip->macro != 0) {
2480 /* try harder: this string crosses a macro expansion boundary.
2481 This can happen naturally if -traditional.
2482 Otherwise, only -D can make a macro with an unmatched quote. */
2488 error_with_line (line_for_error (start_line),
2489 "unterminated string or character constant");
2490 error_with_line (multiline_string_line,
2491 "possible real start of unterminated constant");
2492 multiline_string_line = 0;
2501 /* Traditionally, end of line ends a string constant with no error.
2502 So exit the loop and record the new line. */
2508 error_with_line (line_for_error (start_line),
2509 "unterminated character constant");
2512 if (pedantic && multiline_string_line == 0) {
2513 pedwarn_with_line (line_for_error (start_line),
2514 "string constant runs past end of line");
2516 if (multiline_string_line == 0)
2517 multiline_string_line = ip->lineno - 1;
2524 /* Backslash newline is replaced by nothing at all,
2525 but keep the line counts correct. */
2530 /* ANSI stupidly requires that in \\ the second \
2531 is *not* prevented from combining with a newline. */
2532 while (*ibp == '\\' && ibp[1] == '\n') {
2551 if (*ibp == '\\' && ibp[1] == '\n')
2555 && !(cplusplus_comments && *ibp == '/'))
2563 /* C++ style comment... */
2564 start_line = ip->lineno;
2566 --ibp; /* Back over the slash */
2569 /* Comments are equivalent to spaces. */
2570 if (! put_out_comments)
2573 /* must fake up a comment here */
2578 U_CHAR *before_bp = ibp+2;
2580 while (ibp < limit) {
2581 if (*ibp++ == '\n') {
2583 if (put_out_comments) {
2584 bcopy (before_bp, obp, ibp - before_bp);
2585 obp += ibp - before_bp;
2594 /* Ordinary C comment. Skip it, optionally copying it to output. */
2596 start_line = ip->lineno;
2598 ++ibp; /* Skip the star. */
2600 /* If this cpp is for lint, we peek inside the comments: */
2604 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2606 if (lintcmd != NULL) {
2607 /* I believe it is always safe to emit this newline: */
2609 bcopy ("#pragma lint ", obp, 13);
2611 bcopy (lintcmd, obp, cmdlen);
2616 bcopy (argbp, obp, arglen);
2620 /* OK, now bring us back to the state we were in before we entered
2621 this branch. We need #line b/c the newline for the pragma
2622 could fuck things up. */
2623 output_line_command (ip, op, 0, same_file);
2624 *(obp++) = ' '; /* just in case, if comments are copied thru */
2629 /* Comments are equivalent to spaces.
2630 Note that we already output the slash; we might not want it.
2631 For -traditional, a comment is equivalent to nothing. */
2632 if (! put_out_comments) {
2642 U_CHAR *before_bp = ibp;
2644 while (ibp < limit) {
2647 if (warn_comments && ibp < limit && *ibp == '*')
2648 warning ("`/*' within comment");
2651 if (*ibp == '\\' && ibp[1] == '\n')
2653 if (ibp >= limit || *ibp == '/')
2658 /* Copy the newline into the output buffer, in order to
2659 avoid the pain of a #line every time a multiline comment
2661 if (!put_out_comments)
2669 error_with_line (line_for_error (start_line),
2670 "unterminated comment");
2673 if (put_out_comments) {
2674 bcopy (before_bp, obp, ibp - before_bp);
2675 obp += ibp - before_bp;
2682 if (!dollars_in_ident)
2686 case '0': case '1': case '2': case '3': case '4':
2687 case '5': case '6': case '7': case '8': case '9':
2688 /* If digit is not part of identifier, it starts a number,
2689 which means that following letters are not an identifier.
2690 "0x5" does not refer to an identifier "x5".
2691 So copy all alphanumerics that follow without accumulating
2692 as an identifier. Periods also, for sake of "3.e7". */
2694 if (ident_length == 0) {
2695 while (ibp < limit) {
2696 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
2701 /* ".." terminates a preprocessing number. This is useless for C
2702 code but useful for preprocessing other things. */
2703 if (!isalnum (c) && (c != '.' || *ibp == '.') && c != '_') {
2708 /* A sign can be part of a preprocessing number
2709 if it follows an e. */
2710 if (c == 'e' || c == 'E') {
2711 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
2715 if (ibp < limit && (*ibp == '+' || *ibp == '-')) {
2717 /* But traditional C does not let the token go past the sign. */
2728 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2729 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2730 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
2731 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2733 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2734 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
2735 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
2736 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2740 /* Compute step of hash function, to avoid a proc call on every token */
2741 hash = HASHSTEP (hash, c);
2745 if (ip->fname == 0 && *ibp == '-') {
2746 /* Newline - inhibits expansion of preceding token.
2747 If expanding a macro arg, we keep the newline -.
2748 In final output, it is deleted.
2749 We recognize Newline - in macro bodies and macro args. */
2750 if (! concatenated) {
2755 if (!output_marks) {
2758 /* If expanding a macro arg, keep the newline -. */
2764 /* If reprocessing a macro expansion, newline is a special marker. */
2765 else if (ip->macro != 0) {
2766 /* Newline White is a "funny space" to separate tokens that are
2767 supposed to be separate but without space between.
2768 Here White means any whitespace character.
2769 Newline - marks a recursive macro use that is not
2770 supposed to be expandable. */
2772 if (is_space[*ibp]) {
2773 /* Newline Space does not prevent expansion of preceding token
2774 so expand the preceding token and then come back. */
2775 if (ident_length > 0)
2778 /* If generating final output, newline space makes a space. */
2779 if (!output_marks) {
2781 /* And Newline Newline makes a newline, so count it. */
2782 if (obp[-1] == '\n')
2785 /* If expanding a macro arg, keep the newline space.
2786 If the arg gets stringified, newline space makes nothing. */
2789 } else abort (); /* Newline followed by something random? */
2793 /* If there is a pending identifier, handle it and come back here. */
2794 if (ident_length > 0)
2799 /* Update the line counts and output a #line if necessary. */
2802 if (ip->lineno != op->lineno) {
2804 output_line_command (ip, op, 1, same_file);
2805 check_expand (op, ip->length - (ip->bufp - ip->buf));
2810 /* Come here either after (1) a null character that is part of the input
2811 or (2) at the end of the input, because there is a null there. */
2814 /* Our input really contains a null character. */
2817 /* At end of a macro-expansion level, pop it and read next level. */
2818 if (ip->macro != 0) {
2821 /* If traditional, and we have an identifier that ends here,
2822 process it now, so we get the right error for recursion. */
2823 if (traditional && ident_length
2824 && ! is_idchar[*instack[indepth - 1].bufp]) {
2833 /* If we don't have a pending identifier,
2834 return at end of input. */
2835 if (ident_length == 0) {
2843 /* If we do have a pending identifier, just consider this null
2844 a special character and arrange to dispatch on it again.
2845 The second time, IDENT_LENGTH will be zero so we will return. */
2851 /* Handle the case of a character such as /, ', " or null
2852 seen following an identifier. Back over it so that
2853 after the identifier is processed the special char
2854 will be dispatched on again. */
2864 if (ident_length > 0) {
2865 register HASHNODE *hp;
2867 /* We have just seen an identifier end. If it's a macro, expand it.
2869 IDENT_LENGTH is the length of the identifier
2870 and HASH is its hash code.
2872 The identifier has already been copied to the output,
2873 so if it is a macro we must remove it.
2875 If REDO_CHAR is 0, the char that terminated the identifier
2876 has been skipped in the output and the input.
2877 OBP-IDENT_LENGTH-1 points to the identifier.
2878 If the identifier is a macro, we must back over the terminator.
2880 If REDO_CHAR is 1, the terminating char has already been
2881 backed over. OBP-IDENT_LENGTH points to the identifier. */
2883 if (!pcp_outfile || pcp_inside_if) {
2885 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
2888 if (hp->length == ident_length) {
2889 int obufp_before_macroname;
2890 int op_lineno_before_macroname;
2891 register int i = ident_length;
2892 register U_CHAR *p = hp->name;
2893 register U_CHAR *q = obp - i;
2899 do { /* All this to avoid a strncmp () */
2904 /* We found a use of a macro name.
2905 see if the context shows it is a macro call. */
2907 /* Back up over terminating character if not already done. */
2913 /* Save this as a displacement from the beginning of the output
2914 buffer. We can not save this as a position in the output
2915 buffer, because it may get realloc'ed by RECACHE. */
2916 obufp_before_macroname = (obp - op->buf) - ident_length;
2917 op_lineno_before_macroname = op->lineno;
2919 if (hp->type == T_PCSTRING) {
2920 pcstring_used (hp); /* Mark the definition of this key
2921 as needed, ensuring that it
2923 break; /* Exit loop, since the key cannot have a
2924 definition any longer. */
2927 /* Record whether the macro is disabled. */
2928 disabled = hp->type == T_DISABLED;
2930 /* This looks like a macro ref, but if the macro was disabled,
2931 just copy its name and put in a marker if requested. */
2935 /* This error check caught useful cases such as
2936 #define foo(x,y) bar (x (y,0), y)
2939 error ("recursive use of macro `%s'", hp->name);
2943 check_expand (op, limit - ibp + 2);
2950 /* If macro wants an arglist, verify that a '(' follows.
2951 first skip all whitespace, copying it to the output
2952 after the macro name. Then, if there is no '(',
2953 decide this is not a macro call and leave things that way. */
2954 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
2955 && hp->value.defn->nargs >= 0)
2957 U_CHAR *old_ibp = ibp;
2958 U_CHAR *old_obp = obp;
2959 int old_iln = ip->lineno;
2960 int old_oln = op->lineno;
2963 /* Scan forward over whitespace, copying it to the output. */
2964 if (ibp == limit && ip->macro != 0) {
2969 old_iln = ip->lineno;
2970 old_oln = op->lineno;
2972 /* A comment: copy it unchanged or discard it. */
2973 else if (*ibp == '/' && ibp+1 != limit && ibp[1] == '*') {
2974 if (put_out_comments) {
2977 } else if (! traditional) {
2981 while (ibp + 1 != limit
2982 && !(ibp[0] == '*' && ibp[1] == '/')) {
2983 /* We need not worry about newline-marks,
2984 since they are never found in comments. */
2986 /* Newline in a file. Count it. */
2990 if (put_out_comments)
2996 if (put_out_comments) {
3001 else if (is_space[*ibp]) {
3003 if (ibp[-1] == '\n') {
3004 if (ip->macro == 0) {
3005 /* Newline in a file. Count it. */
3008 } else if (!output_marks) {
3009 /* A newline mark, and we don't want marks
3010 in the output. If it is newline-hyphen,
3011 discard it entirely. Otherwise, it is
3012 newline-whitechar, so keep the whitechar. */
3022 /* A newline mark; copy both chars to the output. */
3030 /* It isn't a macro call.
3031 Put back the space that we just skipped. */
3034 ip->lineno = old_iln;
3035 op->lineno = old_oln;
3036 /* Exit the for loop. */
3041 /* This is now known to be a macro call.
3042 Discard the macro name from the output,
3043 along with any following whitespace just copied. */
3044 obp = op->buf + obufp_before_macroname;
3045 op->lineno = op_lineno_before_macroname;
3047 /* Prevent accidental token-pasting with a character
3048 before the macro call. */
3049 if (!traditional && obp != op->buf
3050 && (obp[-1] == '-' || obp[1] == '+' || obp[1] == '&'
3051 || obp[-1] == '|' || obp[1] == '<' || obp[1] == '>')) {
3052 /* If we are expanding a macro arg, make a newline marker
3053 to separate the tokens. If we are making real output,
3054 a plain space will do. */
3060 /* Expand the macro, reading arguments as needed,
3061 and push the expansion on the input stack. */
3064 macroexpand (hp, op);
3066 /* Reexamine input stack, since macroexpand has pushed
3067 a new level on it. */
3074 } /* End hash-table-search loop */
3076 ident_length = hash = 0; /* Stop collecting identifier */
3079 } /* End if (ident_length > 0) */
3081 } /* End per-char loop */
3083 /* Come here to return -- but first give an error message
3084 if there was an unterminated successful conditional. */
3086 if (if_stack != ip->if_stack) {
3088 switch (if_stack->type) {
3105 error_with_line (line_for_error (if_stack->lineno),
3106 "unterminated `#%s' conditional", str);
3108 if_stack = ip->if_stack;
3112 * Rescan a string into a temporary buffer and return the result
3113 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3115 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3116 * and insert such markers when appropriate. See `rescan' for details.
3117 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3118 * before substitution; it is 0 for other uses.
3121 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3122 U_CHAR *buf, *limit;
3123 int output_marks, assertions;
3125 register FILE_BUF *ip;
3127 int length = limit - buf;
3129 int odepth = indepth;
3130 int save_assertions_flag = assertions_flag;
3132 assertions_flag = assertions;
3137 /* Set up the input on the input stack. */
3139 buf1 = (U_CHAR *) alloca (length + 1);
3141 register U_CHAR *p1 = buf;
3142 register U_CHAR *p2 = buf1;
3149 /* Set up to receive the output. */
3151 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3152 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3157 CHECK_DEPTH ({return obuf;});
3161 ip = &instack[indepth];
3163 ip->nominal_fname = 0;
3164 ip->system_header_p = 0;
3167 ip->length = length;
3168 ip->buf = ip->bufp = buf1;
3169 ip->if_stack = if_stack;
3171 ip->lineno = obuf.lineno = 1;
3173 /* Scan the input, create the output. */
3174 rescan (&obuf, output_marks);
3176 /* Pop input stack to original state. */
3179 if (indepth != odepth)
3182 /* Record the output. */
3183 obuf.length = obuf.bufp - obuf.buf;
3185 assertions_flag = save_assertions_flag;
3190 * Process a # directive. Expects IP->bufp to point after the '#', as in
3191 * `#define foo bar'. Passes to the command handler
3192 * (do_define, do_include, etc.): the addresses of the 1st and
3193 * last chars of the command (starting immediately after the #
3194 * keyword), plus op and the keyword table pointer. If the command
3195 * contains comments it is copied into a temporary buffer sans comments
3196 * and the temporary buffer is passed to the command handler instead.
3197 * Likewise for backslash-newlines.
3199 * Returns nonzero if this was a known # directive.
3200 * Otherwise, returns zero, without advancing the input pointer.
3204 handle_directive (ip, op)
3207 register U_CHAR *bp, *cp;
3208 register struct directive *kt;
3209 register int ident_length;
3212 /* Nonzero means we must copy the entire command
3213 to get rid of comments or backslash-newlines. */
3214 int copy_command = 0;
3216 U_CHAR *ident, *after_ident;
3220 /* Record where the directive started. do_xifdef needs this. */
3221 directive_start = bp - 1;
3223 /* Skip whitespace and \-newline. */
3225 if (is_hor_space[*bp]) {
3226 if ((*bp == '\f' || *bp == '\v') && pedantic)
3227 pedwarn ("%s in preprocessing directive",
3228 *bp == '\f' ? "formfeed" : "vertical tab");
3230 } else if (*bp == '/' && bp[1] == '*') {
3232 skip_to_end_of_comment (ip, &ip->lineno, 0);
3234 } else if (*bp == '\\' && bp[1] == '\n') {
3235 bp += 2; ip->lineno++;
3239 /* Now find end of directive name.
3240 If we encounter a backslash-newline, exchange it with any following
3241 symbol-constituents so that we end up with a contiguous name. */
3248 if (*cp == '\\' && cp[1] == '\n')
3249 name_newline_fix (cp);
3255 ident_length = cp - bp;
3259 /* A line of just `#' becomes blank. */
3261 if (ident_length == 0 && *after_ident == '\n') {
3262 ip->bufp = after_ident;
3266 if (ident_length == 0 || !is_idstart[*ident]) {
3268 while (is_idchar[*p]) {
3269 if (*p < '0' || *p > '9')
3273 /* Handle # followed by a line number. */
3274 if (p != ident && !is_idchar[*p]) {
3275 static struct directive line_directive_table[] = {
3276 { 4, do_line, "line", T_LINE},
3279 pedwarn ("`#' followed by integer");
3280 after_ident = ident;
3281 kt = line_directive_table;
3285 /* Avoid error for `###' and similar cases unless -pedantic. */
3287 while (*p == '#' || is_hor_space[*p]) p++;
3289 if (pedantic && !lang_asm)
3290 warning ("invalid preprocessor directive");
3296 error ("invalid preprocessor directive name");
3302 * Decode the keyword and call the appropriate expansion
3303 * routine, after moving the input pointer up to the next line.
3305 for (kt = directive_table; kt->length > 0; kt++) {
3306 if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length)) {
3307 register U_CHAR *buf;
3308 register U_CHAR *limit;
3311 int *already_output;
3313 /* Nonzero means do not delete comments within the directive.
3314 #define needs this when -traditional. */
3319 limit = ip->buf + ip->length;
3322 keep_comments = traditional && kt->traditional_comments;
3323 /* #import is defined only in Objective C, or when on the NeXT. */
3324 if (kt->type == T_IMPORT && !(objc || lookup ("__NeXT__", -1, -1)))
3327 /* Find the end of this command (first newline not backslashed
3328 and not in a string or comment).
3329 Set COPY_COMMAND if the command must be copied
3330 (it contains a backslash-newline or a comment). */
3332 buf = bp = after_ident;
3333 while (bp < limit) {
3334 register U_CHAR c = *bp++;
3348 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_command, &unterminated);
3349 /* Don't bother calling the directive if we already got an error
3350 message due to unterminated string. Skip everything and pretend
3351 we called the directive. */
3354 /* Traditional preprocessing permits unterminated strings. */
3363 /* <...> is special for #include. */
3365 if (!kt->angle_brackets)
3367 while (*bp && *bp != '>') bp++;
3371 if (*bp == '\\' && bp[1] == '\n')
3374 || (cplusplus_comments && *bp == '/')) {
3375 U_CHAR *obp = bp - 1;
3377 skip_to_end_of_comment (ip, &ip->lineno, 0);
3379 /* No need to copy the command because of a comment at the end;
3380 just don't include the comment in the directive. */
3381 if (bp == limit || *bp == '\n') {
3385 /* Don't remove the comments if -traditional. */
3386 if (! keep_comments)
3394 pedwarn ("%s in preprocessing directive",
3395 c == '\f' ? "formfeed" : "vertical tab");
3399 --bp; /* Point to the newline */
3407 resume_p = ip->bufp;
3408 /* BP is the end of the directive.
3409 RESUME_P is the next interesting data after the directive.
3410 A comment may come between. */
3412 /* If a directive should be copied through, and -E was given,
3413 pass it through before removing comments. */
3414 if (!no_output && kt->pass_thru && put_out_comments) {
3417 /* Output directive name. */
3418 check_expand (op, kt->length + 2);
3419 /* Make sure # is at the start of a line */
3420 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3425 bcopy (kt->name, op->bufp, kt->length);
3426 op->bufp += kt->length;
3428 /* Output arguments. */
3430 check_expand (op, len);
3431 bcopy (buf, op->bufp, len);
3433 /* Take account of any (escaped) newlines just output. */
3435 if (buf[len] == '\n')
3438 already_output = &junk;
3439 } /* Don't we need a newline or #line? */
3442 register U_CHAR *xp = buf;
3443 /* Need to copy entire command into temp buffer before dispatching */
3445 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
3449 /* Copy to the new buffer, deleting comments
3450 and backslash-newlines (and whitespace surrounding the latter). */
3453 register U_CHAR c = *xp++;
3458 abort (); /* A bare newline should never part of the line. */
3461 /* <...> is special for #include. */
3463 if (!kt->angle_brackets)
3465 while (xp < bp && c != '>') {
3467 if (c == '\\' && xp < bp && *xp == '\n')
3478 if (cp != buf && is_space[cp[-1]]) {
3479 while (cp != buf && is_space[cp[-1]]) cp--;
3481 SKIP_WHITE_SPACE (xp);
3482 } else if (is_space[*xp]) {
3484 SKIP_WHITE_SPACE (xp);
3494 register U_CHAR *bp1
3495 = skip_quoted_string (xp - 1, bp, ip->lineno,
3496 NULL_PTR, NULL_PTR, NULL_PTR);
3510 || (cplusplus_comments && *xp == '/')) {
3512 /* If we already copied the command through,
3513 already_output != 0 prevents outputting comment now. */
3514 skip_to_end_of_comment (ip, already_output, 0);
3516 while (xp != ip->bufp)
3518 /* Delete or replace the slash. */
3519 else if (traditional)
3528 /* Null-terminate the copy. */
3534 ip->bufp = resume_p;
3536 /* Some directives should be written out for cc1 to process,
3537 just as if they were not defined. And sometimes we're copying
3538 definitions through. */
3540 if (!no_output && already_output == 0
3542 || (kt->type == T_DEFINE
3543 && (dump_macros == dump_names
3544 || dump_macros == dump_definitions)))) {
3547 /* Output directive name. */
3548 check_expand (op, kt->length + 1);
3550 bcopy (kt->name, op->bufp, kt->length);
3551 op->bufp += kt->length;
3553 if (kt->pass_thru || dump_macros == dump_definitions) {
3554 /* Output arguments. */
3556 check_expand (op, len);
3557 bcopy (buf, op->bufp, len);
3559 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
3562 SKIP_WHITE_SPACE (xp);
3564 while (is_idchar[*xp]) xp++;
3566 check_expand (op, len + 1);
3568 bcopy (yp, op->bufp, len);
3571 } /* Don't we need a newline or #line? */
3573 /* Call the appropriate command handler. buf now points to
3574 either the appropriate place in the input buffer, or to
3575 the temp buffer if it was necessary to make one. cp
3576 points to the first char after the contents of the (possibly
3577 copied) command, in either case. */
3578 (*kt->func) (buf, cp, op, kt);
3579 check_expand (op, ip->length - (ip->bufp - ip->buf));
3585 /* It is deliberate that we don't warn about undefined directives.
3586 That is the responsibility of cc1. */
3593 static struct tm *timebuf;
3595 time_t t = time (0);
3596 timebuf = localtime (&t);
3601 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3602 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3606 * expand things like __FILE__. Place the expansion into the output
3607 * buffer *without* rescanning.
3611 special_symbol (hp, op)
3618 FILE_BUF *ip = NULL;
3621 int paren = 0; /* For special `defined' keyword */
3623 if (pcp_outfile && pcp_inside_if
3624 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
3625 error ("Predefined macro `%s' used inside `#if' during precompilation",
3628 for (i = indepth; i >= 0; i--)
3629 if (instack[i].fname != NULL) {
3634 error ("cccp error: not in any file?!");
3635 return; /* the show must go on */
3643 if (hp->type == T_FILE)
3644 string = ip->nominal_fname;
3646 string = instack[0].nominal_fname;
3650 buf = (char *) alloca (3 + strlen (string));
3651 sprintf (buf, "\"%s\"", string);
3659 case T_INCLUDE_LEVEL:
3661 for (i = indepth; i >= 0; i--)
3662 if (instack[i].fname != NULL)
3665 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
3666 sprintf (buf, "%d", true_indepth - 1);
3670 buf = (char *) alloca (3 + strlen (version_string));
3671 sprintf (buf, "\"%s\"", version_string);
3675 buf = (char *) alloca (3 + strlen (SIZE_TYPE));
3676 sprintf (buf, "%s", SIZE_TYPE);
3679 case T_PTRDIFF_TYPE:
3680 buf = (char *) alloca (3 + strlen (PTRDIFF_TYPE));
3681 sprintf (buf, "%s", PTRDIFF_TYPE);
3685 buf = (char *) alloca (3 + strlen (WCHAR_TYPE));
3686 sprintf (buf, "%s", WCHAR_TYPE);
3689 case T_USER_LABEL_PREFIX_TYPE:
3690 buf = (char *) alloca (3 + strlen (USER_LABEL_PREFIX));
3691 sprintf (buf, "%s", USER_LABEL_PREFIX);
3694 case T_REGISTER_PREFIX_TYPE:
3695 buf = (char *) alloca (3 + strlen (REGISTER_PREFIX));
3696 sprintf (buf, "%s", REGISTER_PREFIX);
3700 buf = (char *) alloca (4 * sizeof (int));
3701 sprintf (buf, "%d", hp->value.ival);
3702 if (pcp_inside_if && pcp_outfile)
3703 /* Output a precondition for this macro use */
3704 fprintf (pcp_outfile, "#define %s %d\n", hp->name, hp->value.ival);
3708 buf = (char *) alloca (10);
3709 sprintf (buf, "%d", ip->lineno);
3714 buf = (char *) alloca (20);
3715 timebuf = timestamp ();
3716 if (hp->type == T_DATE)
3717 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3718 timebuf->tm_mday, timebuf->tm_year + 1900);
3720 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3724 case T_SPEC_DEFINED:
3725 buf = " 0 "; /* Assume symbol is not defined */
3726 ip = &instack[indepth];
3727 SKIP_WHITE_SPACE (ip->bufp);
3728 if (*ip->bufp == '(') {
3730 ip->bufp++; /* Skip over the paren */
3731 SKIP_WHITE_SPACE (ip->bufp);
3734 if (!is_idstart[*ip->bufp])
3736 if (hp = lookup (ip->bufp, -1, -1)) {
3737 if (pcp_outfile && pcp_inside_if
3738 && hp->value.defn->predefined)
3739 /* Output a precondition for this macro use. */
3740 fprintf (pcp_outfile, "#define %s\n", hp->name);
3744 if (pcp_outfile && pcp_inside_if) {
3745 /* Output a precondition for this macro use */
3746 U_CHAR *cp = ip->bufp;
3747 fprintf (pcp_outfile, "#undef ");
3748 while (is_idchar[*cp]) /* Ick! */
3749 fputc (*cp++, pcp_outfile);
3750 putc ('\n', pcp_outfile);
3752 while (is_idchar[*ip->bufp])
3754 SKIP_WHITE_SPACE (ip->bufp);
3756 if (*ip->bufp != ')')
3764 error ("`defined' without an identifier");
3768 error ("cccp error: invalid special hash type"); /* time for gdb */
3772 check_expand (op, len);
3773 bcopy (buf, op->bufp, len);
3780 /* Routines to handle #directives */
3782 /* Handle #include and #import.
3783 This function expects to see "fname" or <fname> on the input. */
3786 do_include (buf, limit, op, keyword)
3787 U_CHAR *buf, *limit;
3789 struct directive *keyword;
3791 int importing = (keyword->type == T_IMPORT);
3792 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3793 static int import_warning = 0;
3794 char *fname; /* Dynamically allocated fname buffer */
3797 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
3799 struct file_name_list *search_start = include; /* Chain of dirs to search */
3800 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3801 struct file_name_list *searchptr = 0;
3804 int f; /* file number */
3806 int retried = 0; /* Have already tried macro
3807 expanding the include line*/
3808 FILE_BUF trybuf; /* It got expanded into here */
3809 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
3814 f= -1; /* JF we iz paranoid! */
3816 if (importing && warn_import && !inhibit_warnings
3817 && !instack[indepth].system_header_p && !import_warning) {
3819 warning ("using `#import' is not recommended");
3820 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
3821 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
3822 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
3823 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
3824 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
3825 fprintf (stderr, " ... <real contents of file> ...\n");
3826 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
3827 fprintf (stderr, "Then users can use `#include' any number of times.\n");
3828 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
3829 fprintf (stderr, "when it is equipped with such a conditional.\n");
3835 SKIP_WHITE_SPACE (fbeg);
3836 /* Discard trailing whitespace so we can easily see
3837 if we have parsed all the significant chars we were given. */
3838 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
3844 /* Copy the operand text, concatenating the strings. */
3847 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
3849 while (fin != limit) {
3850 while (fin != limit && *fin != '\"')
3855 /* If not at the end, there had better be another string. */
3856 /* Skip just horiz space, and don't go past limit. */
3857 while (fin != limit && is_hor_space[*fin]) fin++;
3858 if (fin != limit && *fin == '\"')
3866 /* We have "filename". Figure out directory this source
3867 file is coming from and put it on the front of the list. */
3869 /* If -I- was specified, don't search current dir, only spec'd ones. */
3870 if (ignore_srcdir) break;
3872 for (fp = &instack[indepth]; fp >= instack; fp--)
3877 if ((nam = fp->nominal_fname) != NULL) {
3878 /* Found a named file. Figure out dir of the file,
3879 and put it in front of the search list. */
3880 dsp[0].next = search_start;
3883 ep = rindex (nam, '/');
3885 ep = rindex (nam, ']');
3886 if (ep == NULL) ep = rindex (nam, '>');
3887 if (ep == NULL) ep = rindex (nam, ':');
3888 if (ep != NULL) ep++;
3892 dsp[0].fname = (char *) alloca (n + 1);
3893 strncpy (dsp[0].fname, nam, n);
3894 dsp[0].fname[n] = '\0';
3895 if (n + INCLUDE_LEN_FUDGE > max_include_len)
3896 max_include_len = n + INCLUDE_LEN_FUDGE;
3898 dsp[0].fname = 0; /* Current directory */
3908 while (fend != limit && *fend != '>') fend++;
3909 if (*fend == '>' && fend + 1 == limit) {
3911 /* If -I-, start with the first -I dir after the -I-. */
3912 if (first_bracket_include)
3913 search_start = first_bracket_include;
3921 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
3924 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
3925 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
3926 bcopy (trybuf.buf, buf, trybuf.bufp - trybuf.buf);
3927 limit = buf + (trybuf.bufp - trybuf.buf);
3934 /* For #include_next, skip in the search path
3935 past the dir in which the containing file was found. */
3938 for (fp = &instack[indepth]; fp >= instack; fp--)
3939 if (fp->fname != NULL) {
3940 /* fp->dir is null if the containing file was specified
3941 with an absolute file name. In that case, don't skip anything. */
3943 search_start = fp->dir->next;
3952 error ("empty file name in `#%s'", keyword->name);
3956 /* Allocate this permanently, because it gets stored in the definitions
3958 fname = (char *) xmalloc (max_include_len + flen + 2);
3959 /* + 2 above for slash and terminating null. */
3961 /* If specified file name is absolute, just open it. */
3964 strncpy (fname, fbeg, flen);
3966 if (redundant_include_p (fname))
3969 f = lookup_import (fname);
3971 f = open (fname, O_RDONLY, 0666);
3973 return 0; /* Already included this file */
3975 /* Search directory path, trying to open the file.
3976 Copy each filename tried into FNAME. */
3978 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
3979 if (searchptr->fname) {
3980 /* The empty string in a search path is ignored.
3981 This makes it possible to turn off entirely
3982 a standard piece of the list. */
3983 if (searchptr->fname[0] == 0)
3985 strcpy (fname, searchptr->fname);
3986 strcat (fname, "/");
3987 fname[strlen (fname) + flen] = 0;
3991 strncat (fname, fbeg, flen);
3993 /* Change this 1/2 Unix 1/2 VMS file specification into a
3994 full VMS file specification */
3995 if (searchptr->fname && (searchptr->fname[0] != 0)) {
3996 /* Fix up the filename */
3997 hack_vms_include_specification (fname);
3999 /* This is a normal VMS filespec, so use it unchanged. */
4000 strncpy (fname, fbeg, flen);
4005 f = lookup_import (fname);
4007 f = open (fname, O_RDONLY, 0666);
4009 return 0; /* Already included this file */
4011 else if (f == -1 && errno == EACCES)
4012 warning ("Header file %s exists, but is not readable", fname);
4014 if (redundant_include_p (fname)) {
4024 /* A file that was not found. */
4026 strncpy (fname, fbeg, flen);
4028 /* If -M was specified, and this header file won't be added to the
4029 dependency list, then don't count this as an error, because we can
4030 still produce correct output. Otherwise, we can't produce correct
4031 output, because there may be dependencies we need inside the missing
4032 file, and we don't know what directory this missing file exists in. */
4034 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4035 warning ("No include path in which to find %s", fname);
4036 else if (search_start)
4037 error_from_errno (fname);
4039 error ("No include path in which to find %s", fname);
4043 /* Check to see if this include file is a once-only include file.
4046 struct file_name_list* ptr;
4048 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4049 if (!strcmp (ptr->fname, fname)) {
4051 return 0; /* This file was once'd. */
4055 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4056 if (!strcmp (ptr->fname, fname))
4057 break; /* This file was included before. */
4061 /* This is the first time for this file. */
4062 /* Add it to list of files included. */
4064 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4065 ptr->control_macro = 0;
4066 ptr->next = all_include_files;
4067 all_include_files = ptr;
4068 ptr->fname = savestring (fname);
4070 /* For -M, add this file to the dependencies. */
4071 if (print_deps > (angle_brackets || (system_include_depth > 0))) {
4072 deps_output ("", 0);
4073 deps_output (fname, 0);
4074 deps_output (" ", 0);
4078 /* Handle -H option. */
4079 if (print_include_names)
4080 fprintf (stderr, "%s\n", fname);
4083 system_include_depth++;
4085 /* Actually process the file. */
4086 add_import (f, fname); /* Record file on "seen" list for #import. */
4088 pcftry = (char *) alloca (strlen (fname) + 30);
4096 sprintf (pcftry, "%s%d", fname, pcfnum++);
4098 pcf = open (pcftry, O_RDONLY, 0666);
4104 if (bcmp (&stat_f.st_ino, &s.st_ino, sizeof (s.st_ino))
4105 || stat_f.st_dev != s.st_dev)
4107 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4108 /* Don't need it any more. */
4113 /* Don't need it at all. */
4118 } while (pcf != -1 && !pcfbuf);
4120 /* Actually process the file */
4122 pcfname = xmalloc (strlen (pcftry) + 1);
4123 strcpy (pcfname, pcftry);
4124 pcfinclude (pcfbuf, pcfbuflimit, fname, op);
4127 finclude (f, fname, op, is_system_include (fname), searchptr);
4130 system_include_depth--;
4135 /* Return nonzero if there is no need to include file NAME
4136 because it has already been included and it contains a conditional
4137 to make a repeated include do nothing. */
4140 redundant_include_p (name)
4143 struct file_name_list *l = all_include_files;
4144 for (; l; l = l->next)
4145 if (! strcmp (name, l->fname)
4147 && lookup (l->control_macro, -1, -1))
4152 /* Return nonzero if the given FILENAME is an absolute pathname which
4153 designates a file within one of the known "system" include file
4154 directories. We assume here that if the given FILENAME looks like
4155 it is the name of a file which resides either directly in a "system"
4156 include file directory, or within any subdirectory thereof, then the
4157 given file must be a "system" include file. This function tells us
4158 if we should suppress pedantic errors/warnings for the given FILENAME. */
4161 is_system_include (filename)
4162 register char *filename;
4164 struct file_name_list *searchptr;
4166 for (searchptr = first_system_include; searchptr;
4167 searchptr = searchptr->next)
4168 if (searchptr->fname) {
4169 register char *sys_dir = searchptr->fname;
4170 register unsigned length = strlen (sys_dir);
4172 if (! strncmp (sys_dir, filename, length) && filename[length] == '/')
4178 /* Process the contents of include file FNAME, already open on descriptor F,
4180 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4181 "system" include directories (as decided by the `is_system_include'
4183 DIRPTR is the link in the dir path through which this file was found,
4184 or 0 if the file name was absolute. */
4187 finclude (f, fname, op, system_header_p, dirptr)
4191 int system_header_p;
4192 struct file_name_list *dirptr;
4197 FILE_BUF *fp; /* For input stack frame */
4198 int missing_newline = 0;
4200 CHECK_DEPTH (return;);
4202 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
4204 perror_with_name (fname);
4209 fp = &instack[indepth + 1];
4210 bzero (fp, sizeof (FILE_BUF));
4211 fp->nominal_fname = fp->fname = fname;
4214 fp->if_stack = if_stack;
4215 fp->system_header_p = system_header_p;
4218 if (S_ISREG (st_mode)) {
4219 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
4222 /* Read the file contents, knowing that st_size is an upper bound
4223 on the number of bytes we can read. */
4224 while (st_size > 0) {
4225 i = read (f, fp->buf + fp->length, st_size);
4234 else if (S_ISDIR (st_mode)) {
4235 error ("directory `%s' specified in #include", fname);
4239 /* Cannot count its file size before reading.
4240 First read the entire file into heap and
4241 copy them into buffer on stack. */
4248 basep = (U_CHAR *) xmalloc (bsize + 2);
4249 fp->buf = basep; /* So it will get freed, on error. */
4253 i = read (f, bufp, bsize - st_size);
4255 goto nope; /* error! */
4257 break; /* End of file */
4260 if (bsize == st_size) { /* Buffer is full! */
4262 basep = (U_CHAR *) xrealloc (basep, bsize + 2);
4264 bufp = basep + st_size; /* May have moved */
4268 fp->length = st_size;
4271 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
4272 /* Backslash-newline at end is not good enough. */
4273 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
4274 fp->buf[fp->length++] = '\n';
4275 missing_newline = 1;
4277 fp->buf[fp->length] = '\0';
4279 /* Close descriptor now, so nesting does not use lots of descriptors. */
4282 /* Must do this before calling trigraph_pcp, so that the correct file name
4283 will be printed in warning messages. */
4286 input_file_stack_tick++;
4291 output_line_command (fp, op, 0, enter_file);
4294 if (missing_newline)
4297 if (pedantic && missing_newline)
4298 pedwarn ("file does not end in newline");
4301 input_file_stack_tick++;
4302 output_line_command (&instack[indepth], op, 0, leave_file);
4308 perror_with_name (fname);
4313 /* Record that inclusion of the file named FILE
4314 should be controlled by the macro named MACRO_NAME.
4315 This means that trying to include the file again
4316 will do something if that macro is defined. */
4319 record_control_macro (file, macro_name)
4323 struct file_name_list *new;
4325 for (new = all_include_files; new; new = new->next) {
4326 if (!strcmp (new->fname, file)) {
4327 new->control_macro = macro_name;
4332 /* If the file is not in all_include_files, something's wrong. */
4336 /* Maintain and search list of included files, for #import. */
4338 #define IMPORT_HASH_SIZE 31
4340 struct import_file {
4344 struct import_file *next;
4347 /* Hash table of files already included with #include or #import. */
4349 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
4351 /* Hash a file name for import_hash_table. */
4359 while (*f) val += *f++;
4360 return (val%IMPORT_HASH_SIZE);
4363 /* Search for file FILENAME in import_hash_table.
4364 Return -2 if found, either a matching name or a matching inode.
4365 Otherwise, open the file and return a file descriptor if successful
4366 or -1 if unsuccessful. */
4369 lookup_import (filename)
4372 struct import_file *i;
4378 hashval = import_hash (filename);
4380 /* Attempt to find file in list of already included files */
4381 i = import_hash_table[hashval];
4384 if (!strcmp (filename, i->name))
4385 return -2; /* return found */
4388 /* Open it and try a match on inode/dev */
4389 fd = open (filename, O_RDONLY, 0666);
4393 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
4394 i = import_hash_table[h];
4396 /* Compare the inode and the device.
4397 Supposedly on some systems the inode is not a scalar. */
4398 if (!bcmp (&i->inode, &sb.st_ino, sizeof (sb.st_ino))
4399 && i->dev == sb.st_dev) {
4401 return -2; /* return found */
4406 return fd; /* Not found, return open file */
4409 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
4412 add_import (fd, fname)
4416 struct import_file *i;
4420 hashval = import_hash (fname);
4422 i = (struct import_file *)xmalloc (sizeof (struct import_file));
4423 i->name = (char *)xmalloc (strlen (fname)+1);
4424 strcpy (i->name, fname);
4425 bcopy (&sb.st_ino, &i->inode, sizeof (sb.st_ino));
4427 i->next = import_hash_table[hashval];
4428 import_hash_table[hashval] = i;
4431 /* Load the specified precompiled header into core, and verify its
4432 preconditions. PCF indicates the file descriptor to read, which must
4433 be a regular file. FNAME indicates the file name of the original
4434 header. *LIMIT will be set to an address one past the end of the file.
4435 If the preconditions of the file are not satisfied, the buffer is
4436 freed and we return 0. If the preconditions are satisfied, return
4437 the address of the buffer following the preconditions. The buffer, in
4438 this case, should never be freed because various pieces of it will
4439 be referred to until all precompiled strings are output at the end of
4443 check_precompiled (pcf, fname, limit)
4459 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
4462 if (S_ISREG (st_mode))
4464 buf = xmalloc (st_size + 2);
4467 i = read (pcf, buf + length, st_size);
4479 if (length > 0 && buf[length-1] != '\n')
4480 buf[length++] = '\n';
4483 *limit = buf + length;
4485 /* File is in core. Check the preconditions. */
4486 if (!check_preconditions (buf))
4488 for (cp = buf; *cp; cp++)
4491 fprintf (stderr, "Using preinclude %s\n", fname);
4497 fprintf (stderr, "Cannot use preinclude %s\n", fname);
4503 /* PREC (null terminated) points to the preconditions of a
4504 precompiled header. These are a series of #define and #undef
4505 lines which must match the current contents of the hash
4508 check_preconditions (prec)
4515 lineend = (char *) index (prec, '\n');
4517 if (*prec++ != '#') {
4518 error ("Bad format encountered while reading precompiled file");
4521 if (!strncmp (prec, "define", 6)) {
4525 mdef = create_definition (prec, lineend, NULL_PTR);
4530 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
4531 || (hp->type != T_MACRO && hp->type != T_CONST)
4532 || (hp->type == T_MACRO
4533 && !compare_defs (mdef.defn, hp->value.defn)
4534 && (mdef.defn->length != 2
4535 || mdef.defn->expansion[0] != '\n'
4536 || mdef.defn->expansion[1] != ' ')))
4538 } else if (!strncmp (prec, "undef", 5)) {
4543 while (is_hor_space[(U_CHAR) *prec])
4546 while (is_idchar[(U_CHAR) *prec])
4550 if (lookup (name, len, -1))
4553 error ("Bad format encountered while reading precompiled file");
4558 /* They all passed successfully */
4562 /* Process the main body of a precompiled file. BUF points to the
4563 string section of the file, following the preconditions. LIMIT is one
4564 character past the end. NAME is the name of the file being read
4565 in. OP is the main output buffer */
4567 pcfinclude (buf, limit, name, op)
4568 U_CHAR *buf, *limit, *name;
4575 /* First in the file comes 4 bytes indicating the number of strings, */
4576 /* in network byte order. (MSB first). */
4578 nstrings = (nstrings << 8) | *cp++;
4579 nstrings = (nstrings << 8) | *cp++;
4580 nstrings = (nstrings << 8) | *cp++;
4582 /* Looping over each string... */
4583 while (nstrings--) {
4584 U_CHAR *string_start;
4585 U_CHAR *endofthiskey;
4589 /* Each string starts with a STRINGDEF structure (str), followed */
4590 /* by the text of the string (string_start) */
4592 /* First skip to a longword boundary */
4593 /* ??? Why a 4-byte boundary? On all machines? */
4594 /* NOTE: This works correctly even if HOST_WIDE_INT
4595 is narrower than a pointer.
4596 Do not try risky measures here to get another type to use!
4597 Do not include gstddef.h or stddef.h--either one will fail! */
4598 if ((HOST_WIDE_INT) cp & 3)
4599 cp += 4 - ((HOST_WIDE_INT) cp & 3);
4601 /* Now get the string. */
4602 str = (STRINGDEF *) cp;
4603 string_start = cp += sizeof (STRINGDEF);
4605 for (; *cp; cp++) /* skip the string */
4608 /* We need to macro expand the string here to ensure that the
4609 proper definition environment is in place. If it were only
4610 expanded when we find out it is needed, macros necessary for
4611 its proper expansion might have had their definitions changed. */
4612 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
4613 /* Lineno is already set in the precompiled file */
4614 str->contents = tmpbuf.buf;
4615 str->len = tmpbuf.length;
4617 str->filename = name;
4618 str->output_mark = outbuf.bufp - outbuf.buf;
4621 *stringlist_tailp = str;
4622 stringlist_tailp = &str->chain;
4624 /* Next comes a fourbyte number indicating the number of keys */
4625 /* for this string. */
4627 nkeys = (nkeys << 8) | *cp++;
4628 nkeys = (nkeys << 8) | *cp++;
4629 nkeys = (nkeys << 8) | *cp++;
4631 /* If this number is -1, then the string is mandatory. */
4635 /* Otherwise, for each key, */
4636 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
4637 KEYDEF *kp = (KEYDEF *) cp;
4640 /* It starts with a KEYDEF structure */
4641 cp += sizeof (KEYDEF);
4643 /* Find the end of the key. At the end of this for loop we
4644 advance CP to the start of the next key using this variable. */
4645 endofthiskey = cp + strlen (cp);
4648 /* Expand the key, and enter it into the hash table. */
4649 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
4650 tmpbuf.bufp = tmpbuf.buf;
4652 while (is_hor_space[*tmpbuf.bufp])
4654 if (!is_idstart[*tmpbuf.bufp]
4655 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
4660 hp = lookup (tmpbuf.bufp, -1, -1);
4663 install (tmpbuf.bufp, -1, T_PCSTRING, 0, (char *) kp, -1);
4665 else if (hp->type == T_PCSTRING) {
4666 kp->chain = hp->value.keydef;
4667 hp->value.keydef = kp;
4673 /* This output_line_command serves to switch us back to the current
4674 input file in case some of these strings get output (which will
4675 result in line commands for the header file being output). */
4676 output_line_command (&instack[indepth], op, 0, enter_file);
4679 /* Called from rescan when it hits a key for strings. Mark them all */
4680 /* used and clean up. */
4687 for (kp = hp->value.keydef; kp; kp = kp->chain)
4688 kp->str->writeflag = 1;
4692 /* Write the output, interspersing precompiled strings in their */
4693 /* appropriate places. */
4697 STRINGDEF *next_string;
4698 U_CHAR *cur_buf_loc;
4699 int line_command_len = 80;
4700 char *line_command = xmalloc (line_command_len);
4703 /* In each run through the loop, either cur_buf_loc == */
4704 /* next_string_loc, in which case we print a series of strings, or */
4705 /* it is less than next_string_loc, in which case we write some of */
4707 cur_buf_loc = outbuf.buf;
4708 next_string = stringlist;
4710 while (cur_buf_loc < outbuf.bufp || next_string) {
4712 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
4713 if (next_string->writeflag) {
4714 len = strlen (next_string->filename);
4715 if (len > line_command_len)
4716 line_command = xrealloc (line_command,
4717 line_command_len *= 2);
4718 sprintf (line_command, "\n# %d \"%s\"\n",
4719 next_string->lineno, next_string->filename);
4720 if (write (fileno (stdout), line_command, strlen (line_command)) < 0)
4721 pfatal_with_name (out_fname);
4722 if (write (fileno (stdout), next_string->contents, next_string->len) < 0)
4723 pfatal_with_name (out_fname);
4725 next_string = next_string->chain;
4729 ? (next_string->output_mark
4730 - (cur_buf_loc - outbuf.buf))
4731 : outbuf.bufp - cur_buf_loc);
4733 if (write (fileno (stdout), cur_buf_loc, len) < len)
4734 pfatal_with_name (out_fname);
4738 free (line_command);
4741 /* Pass a directive through to the output file.
4742 BUF points to the contents of the directive, as a contiguous string.
4743 LIMIT points to the first character past the end of the directive.
4744 KEYWORD is the keyword-table entry for the directive. */
4747 pass_thru_directive (buf, limit, op, keyword)
4748 U_CHAR *buf, *limit;
4750 struct directive *keyword;
4752 register unsigned keyword_length = keyword->length;
4754 check_expand (op, 1 + keyword_length + (limit - buf));
4756 bcopy (keyword->name, op->bufp, keyword_length);
4757 op->bufp += keyword_length;
4758 if (limit != buf && buf[0] != ' ')
4760 bcopy (buf, op->bufp, limit - buf);
4761 op->bufp += (limit - buf);
4764 /* Count the line we have just made in the output,
4765 to get in sync properly. */
4770 /* The arglist structure is built by do_define to tell
4771 collect_definition where the argument names begin. That
4772 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
4773 would contain pointers to the strings x, y, and z.
4774 Collect_definition would then build a DEFINITION node,
4775 with reflist nodes pointing to the places x, y, and z had
4776 appeared. So the arglist is just convenience data passed
4777 between these two routines. It is not kept around after
4778 the current #define has been processed and entered into the
4782 struct arglist *next;
4789 /* Create a DEFINITION node from a #define directive. Arguments are
4790 as for do_define. */
4792 create_definition (buf, limit, op)
4793 U_CHAR *buf, *limit;
4796 U_CHAR *bp; /* temp ptr into input buffer */
4797 U_CHAR *symname; /* remember where symbol name starts */
4798 int sym_length; /* and how long it is */
4799 int line = instack[indepth].lineno;
4800 char *file = instack[indepth].nominal_fname;
4804 int arglengths = 0; /* Accumulate lengths of arg names
4805 plus number of args. */
4810 while (is_hor_space[*bp])
4813 symname = bp; /* remember where it starts */
4814 sym_length = check_macro_name (bp, "macro");
4817 /* Lossage will occur if identifiers or control keywords are broken
4818 across lines using backslash. This is not the right place to take
4822 struct arglist *arg_ptrs = NULL;
4825 bp++; /* skip '(' */
4826 SKIP_WHITE_SPACE (bp);
4828 /* Loop over macro argument names. */
4829 while (*bp != ')') {
4830 struct arglist *temp;
4832 temp = (struct arglist *) alloca (sizeof (struct arglist));
4834 temp->next = arg_ptrs;
4835 temp->argno = argno++;
4836 temp->rest_args = 0;
4840 pedwarn ("another parameter follows `%s'",
4843 if (!is_idstart[*bp])
4844 pedwarn ("invalid character in macro parameter name");
4846 /* Find the end of the arg name. */
4847 while (is_idchar[*bp]) {
4849 /* do we have a "special" rest-args extension here? */
4850 if (limit - bp > REST_EXTENSION_LENGTH &&
4851 strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
4853 temp->rest_args = 1;
4857 temp->length = bp - temp->name;
4859 bp += REST_EXTENSION_LENGTH;
4860 arglengths += temp->length + 2;
4861 SKIP_WHITE_SPACE (bp);
4862 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
4863 error ("badly punctuated parameter list in `#define'");
4868 SKIP_WHITE_SPACE (bp);
4871 error ("unterminated parameter list in `#define'");
4875 struct arglist *otemp;
4877 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
4878 if (temp->length == otemp->length &&
4879 strncmp (temp->name, otemp->name, temp->length) == 0) {
4882 name = (U_CHAR *) alloca (temp->length + 1);
4883 (void) strncpy (name, temp->name, temp->length);
4884 name[temp->length] = '\0';
4885 error ("duplicate argument name `%s' in `#define'", name);
4891 ++bp; /* skip paren */
4892 /* Skip exactly one space or tab if any. */
4893 if (bp < limit && (*bp == ' ' || *bp == '\t')) ++bp;
4894 /* now everything from bp before limit is the definition. */
4895 defn = collect_expansion (bp, limit, argno, arg_ptrs);
4896 defn->rest_args = rest_args;
4898 /* Now set defn->args.argnames to the result of concatenating
4899 the argument names in reverse order
4900 with comma-space between them. */
4901 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
4903 struct arglist *temp;
4905 for (temp = arg_ptrs; temp; temp = temp->next) {
4906 bcopy (temp->name, &defn->args.argnames[i], temp->length);
4908 if (temp->next != 0) {
4909 defn->args.argnames[i++] = ',';
4910 defn->args.argnames[i++] = ' ';
4913 defn->args.argnames[i] = 0;
4916 /* simple expansion or empty definition; gobble it */
4917 if (is_hor_space[*bp])
4918 ++bp; /* skip exactly one blank/tab char */
4919 /* now everything from bp before limit is the definition. */
4920 defn = collect_expansion (bp, limit, -1, NULL_PTR);
4921 defn->args.argnames = (U_CHAR *) "";
4927 /* OP is null if this is a predefinition */
4928 defn->predefined = !op;
4930 mdef.symnam = symname;
4931 mdef.symlen = sym_length;
4940 /* Process a #define command.
4941 BUF points to the contents of the #define command, as a contiguous string.
4942 LIMIT points to the first character past the end of the definition.
4943 KEYWORD is the keyword-table entry for #define. */
4946 do_define (buf, limit, op, keyword)
4947 U_CHAR *buf, *limit;
4949 struct directive *keyword;
4954 /* If this is a precompiler run (with -pcp) pass thru #define commands. */
4955 if (pcp_outfile && op)
4956 pass_thru_directive (buf, limit, op, keyword);
4958 mdef = create_definition (buf, limit, op);
4962 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
4966 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
4968 /* Redefining a precompiled key is ok. */
4969 if (hp->type == T_PCSTRING)
4971 /* Redefining a macro is ok if the definitions are the same. */
4972 else if (hp->type == T_MACRO)
4973 ok = ! compare_defs (mdef.defn, hp->value.defn);
4974 /* Redefining a constant is ok with -D. */
4975 else if (hp->type == T_CONST)
4976 ok = ! done_initializing;
4977 /* Print the warning if it's not ok. */
4979 U_CHAR *msg; /* what pain... */
4981 /* If we are passing through #define and #undef directives, do
4982 that for this re-definition now. */
4983 if (debug_output && op)
4984 pass_thru_directive (buf, limit, op, keyword);
4986 msg = (U_CHAR *) alloca (mdef.symlen + 22);
4988 bcopy (mdef.symnam, msg + 1, mdef.symlen);
4989 strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
4991 if (hp->type == T_MACRO)
4992 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
4993 "this is the location of the previous definition");
4995 /* Replace the old definition. */
4997 hp->value.defn = mdef.defn;
4999 /* If we are passing through #define and #undef directives, do
5000 that for this new definition now. */
5001 if (debug_output && op)
5002 pass_thru_directive (buf, limit, op, keyword);
5003 install (mdef.symnam, mdef.symlen, T_MACRO, 0,
5004 (char *) mdef.defn, hashcode);
5015 /* Check a purported macro name SYMNAME, and yield its length.
5016 USAGE is the kind of name this is intended for. */
5019 check_macro_name (symname, usage)
5026 for (p = symname; is_idchar[*p]; p++)
5028 sym_length = p - symname;
5029 if (sym_length == 0)
5030 error ("invalid %s name", usage);
5031 else if (!is_idstart[*symname]) {
5032 U_CHAR *msg; /* what pain... */
5033 msg = (U_CHAR *) alloca (sym_length + 1);
5034 bcopy (symname, msg, sym_length);
5035 msg[sym_length] = 0;
5036 error ("invalid %s name `%s'", usage, msg);
5038 if (! strncmp (symname, "defined", 7) && sym_length == 7)
5039 error ("invalid %s name `defined'", usage);
5045 * return zero if two DEFINITIONs are isomorphic
5048 compare_defs (d1, d2)
5049 DEFINITION *d1, *d2;
5051 register struct reflist *a1, *a2;
5052 register U_CHAR *p1 = d1->expansion;
5053 register U_CHAR *p2 = d2->expansion;
5056 if (d1->nargs != d2->nargs)
5058 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5060 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5061 a1 = a1->next, a2 = a2->next) {
5062 if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
5063 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5064 || a1->argno != a2->argno
5065 || a1->stringify != a2->stringify
5066 || a1->raw_before != a2->raw_before
5067 || a1->raw_after != a2->raw_after)
5075 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5076 p2, d2->length - (p2 - d2->expansion), 1))
5081 /* Return 1 if two parts of two macro definitions are effectively different.
5082 One of the parts starts at BEG1 and has LEN1 chars;
5083 the other has LEN2 chars at BEG2.
5084 Any sequence of whitespace matches any other sequence of whitespace.
5085 FIRST means these parts are the first of a macro definition;
5086 so ignore leading whitespace entirely.
5087 LAST means these parts are the last of a macro definition;
5088 so ignore trailing whitespace entirely. */
5091 comp_def_part (first, beg1, len1, beg2, len2, last)
5093 U_CHAR *beg1, *beg2;
5097 register U_CHAR *end1 = beg1 + len1;
5098 register U_CHAR *end2 = beg2 + len2;
5100 while (beg1 != end1 && is_space[*beg1]) beg1++;
5101 while (beg2 != end2 && is_space[*beg2]) beg2++;
5104 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5105 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5107 while (beg1 != end1 && beg2 != end2) {
5108 if (is_space[*beg1] && is_space[*beg2]) {
5109 while (beg1 != end1 && is_space[*beg1]) beg1++;
5110 while (beg2 != end2 && is_space[*beg2]) beg2++;
5111 } else if (*beg1 == *beg2) {
5115 return (beg1 != end1) || (beg2 != end2);
5118 /* Read a replacement list for a macro with parameters.
5119 Build the DEFINITION structure.
5120 Reads characters of text starting at BUF until END.
5121 ARGLIST specifies the formal parameters to look for
5122 in the text of the definition; NARGS is the number of args
5123 in that list, or -1 for a macro name that wants no argument list.
5124 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5125 and NAMELEN is its length in characters.
5127 Note that comments and backslash-newlines have already been deleted
5128 from the argument. */
5130 /* Leading and trailing Space, Tab, etc. are converted to markers
5131 Newline Space, Newline Tab, etc.
5132 Newline Space makes a space in the final output
5133 but is discarded if stringified. (Newline Tab is similar but
5134 makes a Tab instead.)
5136 If there is no trailing whitespace, a Newline Space is added at the end
5137 to prevent concatenation that would be contrary to the standard. */
5140 collect_expansion (buf, end, nargs, arglist)
5143 struct arglist *arglist;
5146 register U_CHAR *p, *limit, *lastp, *exp_p;
5147 struct reflist *endpat = NULL;
5148 /* Pointer to first nonspace after last ## seen. */
5150 /* Pointer to first nonspace after last single-# seen. */
5151 U_CHAR *stringify = 0;
5153 int expected_delimiter = '\0';
5155 /* Scan thru the replacement list, ignoring comments and quoted
5156 strings, picking up on the macro calls. It does a linear search
5157 thru the arg list on every potential symbol. Profiling might say
5158 that something smarter should happen. */
5163 /* Find the beginning of the trailing whitespace. */
5164 /* Find end of leading whitespace. */
5167 while (p < limit && is_space[limit[-1]]) limit--;
5168 while (p < limit && is_space[*p]) p++;
5170 /* Allocate space for the text in the macro definition.
5171 Leading and trailing whitespace chars need 2 bytes each.
5172 Each other input char may or may not need 1 byte,
5173 so this is an upper bound.
5174 The extra 2 are for invented trailing newline-marker and final null. */
5175 maxsize = (sizeof (DEFINITION)
5176 + 2 * (end - limit) + 2 * (p - buf)
5178 defn = (DEFINITION *) xcalloc (1, maxsize);
5180 defn->nargs = nargs;
5181 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5186 /* Convert leading whitespace to Newline-markers. */
5187 while (p < limit && is_space[*p]) {
5192 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
5193 error ("`##' at start of macro definition");
5197 /* Process the main body of the definition. */
5199 int skipped_arg = 0;
5200 register U_CHAR c = *p++;
5208 if (expected_delimiter != '\0') {
5209 if (c == expected_delimiter)
5210 expected_delimiter = '\0';
5212 expected_delimiter = c;
5215 /* Special hack: if a \# is written in the #define
5216 include a # in the definition. This is useless for C code
5217 but useful for preprocessing other things. */
5220 /* \# quotes a # even outside of strings. */
5221 if (p < limit && *p == '#' && !expected_delimiter) {
5224 } else if (p < limit && expected_delimiter) {
5225 /* In a string, backslash goes through
5226 and makes next char ordinary. */
5232 /* # is ordinary inside a string. */
5233 if (expected_delimiter)
5235 if (p < limit && *p == '#') {
5236 /* ##: concatenate preceding and following tokens. */
5237 /* Take out the first #, discard preceding whitespace. */
5239 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5241 /* Skip the second #. */
5243 /* Discard following whitespace. */
5244 SKIP_WHITE_SPACE (p);
5247 error ("`##' at end of macro definition");
5248 } else if (nargs >= 0) {
5249 /* Single #: stringify following argument ref.
5250 Don't leave the # in the expansion. */
5252 SKIP_WHITE_SPACE (p);
5253 if (p == limit || ! is_idstart[*p])
5254 error ("`#' operator is not followed by a macro argument name");
5261 /* In -traditional mode, recognize arguments inside strings and
5262 and character constants, and ignore special properties of #.
5263 Arguments inside strings are considered "stringified", but no
5264 extra quote marks are supplied. */
5268 if (expected_delimiter != '\0') {
5269 if (c == expected_delimiter)
5270 expected_delimiter = '\0';
5272 expected_delimiter = c;
5276 /* Backslash quotes delimiters and itself, but not macro args. */
5277 if (expected_delimiter != 0 && p < limit
5278 && (*p == expected_delimiter || *p == '\\')) {
5285 if (expected_delimiter != '\0') /* No comments inside strings. */
5288 /* If we find a comment that wasn't removed by handle_directive,
5289 this must be -traditional. So replace the comment with
5293 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
5296 /* Mark this as a concatenation-point, as if it had been ##. */
5304 /* Handle the start of a symbol. */
5305 if (is_idchar[c] && nargs > 0) {
5306 U_CHAR *id_beg = p - 1;
5310 while (p != limit && is_idchar[*p]) p++;
5311 id_len = p - id_beg;
5313 if (is_idstart[c]) {
5314 register struct arglist *arg;
5316 for (arg = arglist; arg != NULL; arg = arg->next) {
5317 struct reflist *tpat;
5319 if (arg->name[0] == c
5320 && arg->length == id_len
5321 && strncmp (arg->name, id_beg, id_len) == 0) {
5322 if (expected_delimiter && warn_stringify) {
5324 warning ("macro argument `%.*s' is stringified.",
5327 warning ("macro arg `%.*s' would be stringified with -traditional.",
5331 /* If ANSI, don't actually substitute inside a string. */
5332 if (!traditional && expected_delimiter)
5334 /* make a pat node for this arg and append it to the end of
5336 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
5338 tpat->raw_before = concat == id_beg;
5339 tpat->raw_after = 0;
5340 tpat->rest_args = arg->rest_args;
5341 tpat->stringify = (traditional ? expected_delimiter != '\0'
5342 : stringify == id_beg);
5345 defn->pattern = tpat;
5347 endpat->next = tpat;
5350 tpat->argno = arg->argno;
5351 tpat->nchars = exp_p - lastp;
5353 register U_CHAR *p1 = p;
5354 SKIP_WHITE_SPACE (p1);
5355 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
5356 tpat->raw_after = 1;
5358 lastp = exp_p; /* place to start copying from next time */
5365 /* If this was not a macro arg, copy it into the expansion. */
5366 if (! skipped_arg) {
5367 register U_CHAR *lim1 = p;
5371 if (stringify == id_beg)
5372 error ("`#' operator should be followed by a macro argument name");
5378 /* Convert trailing whitespace to Newline-markers. */
5379 while (limit < end && is_space[*limit]) {
5381 *exp_p++ = *limit++;
5383 } else if (!traditional && expected_delimiter == 0) {
5384 /* There is no trailing whitespace, so invent some in ANSI mode.
5385 But not if "inside a string" (which in ANSI mode
5386 happens only for -D option). */
5393 defn->length = exp_p - defn->expansion;
5395 /* Crash now if we overrun the allocated size. */
5396 if (defn->length + 1 > maxsize)
5400 /* This isn't worth the time it takes. */
5401 /* give back excess storage */
5402 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
5409 do_assert (buf, limit, op, keyword)
5410 U_CHAR *buf, *limit;
5412 struct directive *keyword;
5414 U_CHAR *bp; /* temp ptr into input buffer */
5415 U_CHAR *symname; /* remember where symbol name starts */
5416 int sym_length; /* and how long it is */
5417 struct arglist *tokens = NULL;
5419 if (pedantic && done_initializing && !instack[indepth].system_header_p)
5420 pedwarn ("ANSI C does not allow `#assert'");
5424 while (is_hor_space[*bp])
5427 symname = bp; /* remember where it starts */
5428 sym_length = check_macro_name (bp, "assertion");
5430 /* #define doesn't do this, but we should. */
5431 SKIP_WHITE_SPACE (bp);
5433 /* Lossage will occur if identifiers or control tokens are broken
5434 across lines using backslash. This is not the right place to take
5438 error ("missing token-sequence in `#assert'");
5445 bp++; /* skip '(' */
5446 SKIP_WHITE_SPACE (bp);
5448 tokens = read_token_list (&bp, limit, &error_flag);
5452 error ("empty token-sequence in `#assert'");
5456 ++bp; /* skip paren */
5457 SKIP_WHITE_SPACE (bp);
5460 /* If this name isn't already an assertion name, make it one.
5461 Error if it was already in use in some other way. */
5464 ASSERTION_HASHNODE *hp;
5465 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
5466 struct tokenlist_list *value
5467 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
5469 hp = assertion_lookup (symname, sym_length, hashcode);
5471 if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
5472 error ("`defined' redefined as assertion");
5473 hp = assertion_install (symname, sym_length, hashcode);
5476 /* Add the spec'd token-sequence to the list of such. */
5477 value->tokens = tokens;
5478 value->next = hp->value;
5486 do_unassert (buf, limit, op, keyword)
5487 U_CHAR *buf, *limit;
5489 struct directive *keyword;
5491 U_CHAR *bp; /* temp ptr into input buffer */
5492 U_CHAR *symname; /* remember where symbol name starts */
5493 int sym_length; /* and how long it is */
5495 struct arglist *tokens = NULL;
5496 int tokens_specified = 0;
5498 if (pedantic && done_initializing && !instack[indepth].system_header_p)
5499 pedwarn ("ANSI C does not allow `#unassert'");
5503 while (is_hor_space[*bp])
5506 symname = bp; /* remember where it starts */
5507 sym_length = check_macro_name (bp, "assertion");
5509 /* #define doesn't do this, but we should. */
5510 SKIP_WHITE_SPACE (bp);
5512 /* Lossage will occur if identifiers or control tokens are broken
5513 across lines using backslash. This is not the right place to take
5519 bp++; /* skip '(' */
5520 SKIP_WHITE_SPACE (bp);
5522 tokens = read_token_list (&bp, limit, &error_flag);
5526 error ("empty token list in `#unassert'");
5530 tokens_specified = 1;
5532 ++bp; /* skip paren */
5533 SKIP_WHITE_SPACE (bp);
5537 ASSERTION_HASHNODE *hp;
5538 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
5539 struct tokenlist_list *tail, *prev;
5541 hp = assertion_lookup (symname, sym_length, hashcode);
5545 /* If no token list was specified, then eliminate this assertion
5547 if (! tokens_specified) {
5548 struct tokenlist_list *next;
5549 for (tail = hp->value; tail; tail = next) {
5551 free_token_list (tail->tokens);
5554 delete_assertion (hp);
5556 /* If a list of tokens was given, then delete any matching list. */
5561 struct tokenlist_list *next = tail->next;
5562 if (compare_token_lists (tail->tokens, tokens)) {
5566 hp->value = tail->next;
5567 free_token_list (tail->tokens);
5580 /* Test whether there is an assertion named NAME
5581 and optionally whether it has an asserted token list TOKENS.
5582 NAME is not null terminated; its length is SYM_LENGTH.
5583 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
5586 check_assertion (name, sym_length, tokens_specified, tokens)
5589 int tokens_specified;
5590 struct arglist *tokens;
5592 ASSERTION_HASHNODE *hp;
5593 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
5595 if (pedantic && !instack[indepth].system_header_p)
5596 pedwarn ("ANSI C does not allow testing assertions");
5598 hp = assertion_lookup (name, sym_length, hashcode);
5600 /* It is not an assertion; just return false. */
5603 /* If no token list was specified, then value is 1. */
5604 if (! tokens_specified)
5608 struct tokenlist_list *tail;
5612 /* If a list of tokens was given,
5613 then succeed if the assertion records a matching list. */
5616 if (compare_token_lists (tail->tokens, tokens))
5621 /* Fail if the assertion has no matching list. */
5626 /* Compare two lists of tokens for equality including order of tokens. */
5629 compare_token_lists (l1, l2)
5630 struct arglist *l1, *l2;
5633 if (l1->length != l2->length)
5635 if (strncmp (l1->name, l2->name, l1->length))
5641 /* Succeed if both lists end at the same time. */
5645 /* Read a space-separated list of tokens ending in a close parenthesis.
5646 Return a list of strings, in the order they were written.
5647 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
5648 Parse the text starting at *BPP, and update *BPP.
5649 Don't parse beyond LIMIT. */
5651 static struct arglist *
5652 read_token_list (bpp, limit, error_flag)
5657 struct arglist *token_ptrs = 0;
5663 /* Loop over the assertion value tokens. */
5665 struct arglist *temp;
5669 /* Find the end of the token. */
5673 } else if (*bp == ')') {
5678 } else if (*bp == '"' || *bp == '\'')
5679 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
5681 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
5682 && *bp != '"' && *bp != '\'' && bp != limit)
5685 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
5686 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
5687 bcopy (beg, temp->name, bp - beg);
5688 temp->name[bp - beg] = 0;
5689 temp->next = token_ptrs;
5691 temp->length = bp - beg;
5693 SKIP_WHITE_SPACE (bp);
5696 error ("unterminated token sequence in `#assert' or `#unassert'");
5703 /* We accumulated the names in reverse order.
5704 Now reverse them to get the proper order. */
5706 register struct arglist *prev = 0, *this, *next;
5707 for (this = token_ptrs; this; this = next) {
5717 free_token_list (tokens)
5718 struct arglist *tokens;
5721 struct arglist *next = tokens->next;
5722 free (tokens->name);
5729 * Install a name in the assertion hash table.
5731 * If LEN is >= 0, it is the length of the name.
5732 * Otherwise, compute the length by scanning the entire name.
5734 * If HASH is >= 0, it is the precomputed hash code.
5735 * Otherwise, compute the hash code.
5737 static ASSERTION_HASHNODE *
5738 assertion_install (name, len, hash)
5743 register ASSERTION_HASHNODE *hp;
5744 register int i, bucket;
5745 register U_CHAR *p, *q;
5747 i = sizeof (ASSERTION_HASHNODE) + len + 1;
5748 hp = (ASSERTION_HASHNODE *) xmalloc (i);
5750 hp->bucket_hdr = &assertion_hashtab[bucket];
5751 hp->next = assertion_hashtab[bucket];
5752 assertion_hashtab[bucket] = hp;
5754 if (hp->next != NULL)
5755 hp->next->prev = hp;
5758 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
5761 for (i = 0; i < len; i++)
5768 * find the most recent hash node for name name (ending with first
5769 * non-identifier char) installed by install
5771 * If LEN is >= 0, it is the length of the name.
5772 * Otherwise, compute the length by scanning the entire name.
5774 * If HASH is >= 0, it is the precomputed hash code.
5775 * Otherwise, compute the hash code.
5777 static ASSERTION_HASHNODE *
5778 assertion_lookup (name, len, hash)
5783 register U_CHAR *bp;
5784 register ASSERTION_HASHNODE *bucket;
5786 bucket = assertion_hashtab[hash];
5788 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
5790 bucket = bucket->next;
5796 delete_assertion (hp)
5797 ASSERTION_HASHNODE *hp;
5800 if (hp->prev != NULL)
5801 hp->prev->next = hp->next;
5802 if (hp->next != NULL)
5803 hp->next->prev = hp->prev;
5805 /* make sure that the bucket chain header that
5806 the deleted guy was on points to the right thing afterwards. */
5807 if (hp == *hp->bucket_hdr)
5808 *hp->bucket_hdr = hp->next;
5814 * interpret #line command. Remembers previously seen fnames
5815 * in its very own hash table.
5817 #define FNAME_HASHSIZE 37
5820 do_line (buf, limit, op, keyword)
5821 U_CHAR *buf, *limit;
5823 struct directive *keyword;
5825 register U_CHAR *bp;
5826 FILE_BUF *ip = &instack[indepth];
5829 enum file_change_code file_change = same_file;
5831 /* Expand any macros. */
5832 tem = expand_to_temp_buffer (buf, limit, 0, 0);
5834 /* Point to macroexpanded line, which is null-terminated now. */
5836 SKIP_WHITE_SPACE (bp);
5838 if (!isdigit (*bp)) {
5839 error ("invalid format `#line' command");
5843 /* The Newline at the end of this line remains to be processed.
5844 To put the next line at the specified line number,
5845 we must store a line number now that is one less. */
5846 new_lineno = atoi (bp) - 1;
5848 /* NEW_LINENO is one less than the actual line number here. */
5849 if (pedantic && new_lineno < 0)
5850 pedwarn ("line number out of range in `#line' command");
5852 /* skip over the line number. */
5853 while (isdigit (*bp))
5856 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
5857 if (*bp && !is_space[*bp]) {
5858 error ("invalid format `#line' command");
5863 SKIP_WHITE_SPACE (bp);
5866 static HASHNODE *fname_table[FNAME_HASHSIZE];
5867 HASHNODE *hp, **hash_bucket;
5873 while (*bp && *bp != '\"')
5876 error ("invalid format `#line' command");
5880 fname_length = bp - fname;
5883 SKIP_WHITE_SPACE (bp);
5886 pedwarn ("garbage at end of `#line' command");
5888 file_change = enter_file;
5889 else if (*bp == '2')
5890 file_change = leave_file;
5891 else if (*bp == '3')
5892 ip->system_header_p = 1;
5894 error ("invalid format `#line' command");
5899 SKIP_WHITE_SPACE (bp);
5901 ip->system_header_p = 1;
5903 SKIP_WHITE_SPACE (bp);
5906 error ("invalid format `#line' command");
5912 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
5913 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
5914 if (hp->length == fname_length &&
5915 strncmp (hp->value.cpval, fname, fname_length) == 0) {
5916 ip->nominal_fname = hp->value.cpval;
5920 /* Didn't find it; cons up a new one. */
5921 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
5922 hp->next = *hash_bucket;
5925 hp->length = fname_length;
5926 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
5927 bcopy (fname, hp->value.cpval, fname_length);
5930 error ("invalid format `#line' command");
5934 ip->lineno = new_lineno;
5935 output_line_command (ip, op, 0, file_change);
5936 check_expand (op, ip->length - (ip->bufp - ip->buf));
5941 * remove the definition of a symbol from the symbol table.
5942 * according to un*x /lib/cpp, it is not an error to undef
5943 * something that has no definitions, so it isn't one here either.
5947 do_undef (buf, limit, op, keyword)
5948 U_CHAR *buf, *limit;
5950 struct directive *keyword;
5954 U_CHAR *orig_buf = buf;
5956 /* If this is a precompiler run (with -pcp) pass thru #undef commands. */
5957 if (pcp_outfile && op)
5958 pass_thru_directive (buf, limit, op, keyword);
5960 SKIP_WHITE_SPACE (buf);
5961 sym_length = check_macro_name (buf, "macro");
5963 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
5964 /* If we are generating additional info for debugging (with -g) we
5965 need to pass through all effective #undef commands. */
5966 if (debug_output && op)
5967 pass_thru_directive (orig_buf, limit, op, keyword);
5968 if (hp->type != T_MACRO)
5969 warning ("undefining `%s'", hp->name);
5975 SKIP_WHITE_SPACE (buf);
5977 pedwarn ("garbage after `#undef' directive");
5983 * Report a fatal error detected by the program we are processing.
5984 * Use the text of the line in the error message, then terminate.
5985 * (We use error because it prints the filename & line#.)
5989 do_error (buf, limit, op, keyword)
5990 U_CHAR *buf, *limit;
5992 struct directive *keyword;
5994 int length = limit - buf;
5995 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
5996 bcopy (buf, copy, length);
5998 SKIP_WHITE_SPACE (copy);
5999 error ("#error %s", copy);
6000 exit (FAILURE_EXIT_CODE);
6006 * Report a warning detected by the program we are processing.
6007 * Use the text of the line in the warning message, then continue.
6008 * (We use error because it prints the filename & line#.)
6012 do_warning (buf, limit, op, keyword)
6013 U_CHAR *buf, *limit;
6015 struct directive *keyword;
6017 int length = limit - buf;
6018 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6019 bcopy (buf, copy, length);
6021 SKIP_WHITE_SPACE (copy);
6022 warning ("#warning %s", copy);
6026 /* Remember the name of the current file being read from so that we can
6027 avoid ever including it again. */
6033 FILE_BUF *ip = NULL;
6035 for (i = indepth; i >= 0; i--)
6036 if (instack[i].fname != NULL) {
6042 struct file_name_list *new;
6044 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6045 new->next = dont_repeat_files;
6046 dont_repeat_files = new;
6047 new->fname = savestring (ip->fname);
6048 new->control_macro = 0;
6053 /* #ident has already been copied to the output file, so just ignore it. */
6056 do_ident (buf, limit)
6057 U_CHAR *buf, *limit;
6059 /* Allow #ident in system headers, since that's not user's fault. */
6060 if (pedantic && !instack[indepth].system_header_p)
6061 pedwarn ("ANSI C does not allow `#ident'");
6065 /* #pragma and its argument line have already been copied to the output file.
6066 Just check for some recognized pragmas that need validation here. */
6069 do_pragma (buf, limit)
6070 U_CHAR *buf, *limit;
6072 while (*buf == ' ' || *buf == '\t')
6074 if (!strncmp (buf, "once", 4)) {
6075 /* Allow #pragma once in system headers, since that's not the user's
6077 if (!instack[indepth].system_header_p)
6078 warning ("`#pragma once' is obsolete");
6082 if (!strncmp (buf, "implementation", 14)) {
6083 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6084 been included yet. */
6085 struct file_name_list *ptr;
6086 U_CHAR *p = buf + 14, *fname, *inc_fname;
6087 SKIP_WHITE_SPACE (p);
6088 if (*p == '\n' || *p != '\"')
6092 if (p = (U_CHAR *) index (fname, '\"'))
6095 for (ptr = all_include_files; ptr; ptr = ptr->next) {
6096 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
6097 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
6098 if (inc_fname && !strcmp (inc_fname, fname))
6099 warning ("`#pragma implementation' for `%s' appears after file is included",
6108 /* This was a fun hack, but #pragma seems to start to be useful.
6109 By failing to recognize it, we pass it through unchanged to cc1. */
6112 * the behavior of the #pragma directive is implementation defined.
6113 * this implementation defines it as follows.
6120 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6123 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6125 execl ("/usr/games/hack", "#pragma", 0);
6126 execl ("/usr/games/rogue", "#pragma", 0);
6127 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6128 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6130 fatal ("You are in a maze of twisty compiler features, all different");
6134 /* Just ignore #sccs, on systems where we define it at all. */
6140 pedwarn ("ANSI C does not allow `#sccs'");
6145 * handle #if command by
6146 * 1) inserting special `defined' keyword into the hash table
6147 * that gets turned into 0 or 1 by special_symbol (thus,
6148 * if the luser has a symbol called `defined' already, it won't
6149 * work inside the #if command)
6150 * 2) rescan the input into a temporary output buffer
6151 * 3) pass the output buffer to the yacc parser and collect a value
6152 * 4) clean up the mess left from steps 1 and 2.
6153 * 5) call conditional_skip to skip til the next #endif (etc.),
6154 * or not, depending on the value from step 3.
6158 do_if (buf, limit, op, keyword)
6159 U_CHAR *buf, *limit;
6161 struct directive *keyword;
6164 FILE_BUF *ip = &instack[indepth];
6166 value = eval_if_expression (buf, limit - buf);
6167 conditional_skip (ip, value == 0, T_IF, NULL_PTR);
6172 * handle a #elif directive by not changing if_stack either.
6173 * see the comment above do_else.
6177 do_elif (buf, limit, op, keyword)
6178 U_CHAR *buf, *limit;
6180 struct directive *keyword;
6183 FILE_BUF *ip = &instack[indepth];
6185 if (if_stack == instack[indepth].if_stack) {
6186 error ("`#elif' not within a conditional");
6189 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6190 error ("`#elif' after `#else'");
6191 fprintf (stderr, " (matches line %d", if_stack->lineno);
6192 if (if_stack->fname != NULL && ip->fname != NULL &&
6193 strcmp (if_stack->fname, ip->nominal_fname) != 0)
6194 fprintf (stderr, ", file %s", if_stack->fname);
6195 fprintf (stderr, ")\n");
6197 if_stack->type = T_ELIF;
6200 if (if_stack->if_succeeded)
6201 skip_if_group (ip, 0);
6203 value = eval_if_expression (buf, limit - buf);
6205 skip_if_group (ip, 0);
6207 ++if_stack->if_succeeded; /* continue processing input */
6208 output_line_command (ip, op, 1, same_file);
6215 * evaluate a #if expression in BUF, of length LENGTH,
6216 * then parse the result as a C expression and return the value as an int.
6219 eval_if_expression (buf, length)
6224 HASHNODE *save_defined;
6227 save_defined = install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
6229 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6231 delete_macro (save_defined); /* clean up special symbol */
6233 value = parse_c_expression (temp_obuf.buf);
6235 free (temp_obuf.buf);
6241 * routine to handle ifdef/ifndef. Try to look up the symbol,
6242 * then do or don't skip to the #endif/#else/#elif depending
6243 * on what directive is actually being processed.
6247 do_xifdef (buf, limit, op, keyword)
6248 U_CHAR *buf, *limit;
6250 struct directive *keyword;
6253 FILE_BUF *ip = &instack[indepth];
6255 int start_of_file = 0;
6256 U_CHAR *control_macro = 0;
6258 /* Detect a #ifndef at start of file (not counting comments). */
6259 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
6260 U_CHAR *p = ip->buf;
6261 while (p != directive_start) {
6265 else if (c == '/' && p != ip->bufp && *p == '*') {
6266 /* Skip this comment. */
6268 U_CHAR *save_bufp = ip->bufp;
6270 p = skip_to_end_of_comment (ip, &junk, 1);
6271 ip->bufp = save_bufp;
6276 /* If we get here, this conditional is the beginning of the file. */
6281 /* Discard leading and trailing whitespace. */
6282 SKIP_WHITE_SPACE (buf);
6283 while (limit != buf && is_hor_space[limit[-1]]) limit--;
6285 /* Find the end of the identifier at the beginning. */
6286 for (end = buf; is_idchar[*end]; end++);
6289 skip = (keyword->type == T_IFDEF);
6291 pedwarn (end == limit ? "`#%s' with no argument"
6292 : "`#%s' argument starts with punctuation",
6297 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
6298 pedwarn ("`#%s' argument starts with a digit", keyword->name);
6299 else if (end != limit && !traditional)
6300 pedwarn ("garbage at end of `#%s' argument", keyword->name);
6302 hp = lookup (buf, end-buf, -1);
6305 /* Output a precondition for this macro. */
6306 if (hp && hp->value.defn->predefined)
6307 fprintf (pcp_outfile, "#define %s\n", hp->name);
6310 fprintf (pcp_outfile, "#undef ");
6311 while (is_idchar[*cp]) /* Ick! */
6312 fputc (*cp++, pcp_outfile);
6313 putc ('\n', pcp_outfile);
6317 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
6318 if (start_of_file && !skip) {
6319 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
6320 bcopy (buf, control_macro, end - buf);
6321 control_macro[end - buf] = 0;
6325 conditional_skip (ip, skip, T_IF, control_macro);
6329 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
6330 If this is a #ifndef starting at the beginning of a file,
6331 CONTROL_MACRO is the macro name tested by the #ifndef.
6332 Otherwise, CONTROL_MACRO is 0. */
6335 conditional_skip (ip, skip, type, control_macro)
6338 enum node_type type;
6339 U_CHAR *control_macro;
6341 IF_STACK_FRAME *temp;
6343 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
6344 temp->fname = ip->nominal_fname;
6345 temp->lineno = ip->lineno;
6346 temp->next = if_stack;
6347 temp->control_macro = control_macro;
6350 if_stack->type = type;
6353 skip_if_group (ip, 0);
6356 ++if_stack->if_succeeded;
6357 output_line_command (ip, &outbuf, 1, same_file);
6362 * skip to #endif, #else, or #elif. adjust line numbers, etc.
6363 * leaves input ptr at the sharp sign found.
6364 * If ANY is nonzero, return at next directive of any sort.
6367 skip_if_group (ip, any)
6371 register U_CHAR *bp = ip->bufp, *cp;
6372 register U_CHAR *endb = ip->buf + ip->length;
6373 struct directive *kt;
6374 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
6375 U_CHAR *beg_of_line = bp;
6376 register int ident_length;
6377 U_CHAR *ident, *after_ident;
6381 case '/': /* possible comment */
6382 if (*bp == '\\' && bp[1] == '\n')
6385 || (cplusplus_comments && *bp == '/')) {
6387 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
6392 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
6393 NULL_PTR, NULL_PTR);
6396 /* Char after backslash loses its special meaning. */
6399 ++ip->lineno; /* But do update the line-count. */
6410 /* # keyword: a # must be first nonblank char on the line */
6411 if (beg_of_line == 0)
6413 /* Scan from start of line, skipping whitespace, comments
6414 and backslash-newlines, and see if we reach this #.
6415 If not, this # is not special. */
6418 if (is_hor_space[*bp])
6420 else if (*bp == '\\' && bp[1] == '\n')
6422 else if (*bp == '/' && bp[1] == '*') {
6424 while (!(*bp == '*' && bp[1] == '/'))
6427 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
6429 while (*bp++ != '\n') ;
6433 if (bp != ip->bufp) {
6434 bp = ip->bufp + 1; /* Reset bp to after the #. */
6438 bp = ip->bufp + 1; /* Point after the '#' */
6440 /* Skip whitespace and \-newline. */
6442 if (is_hor_space[*bp])
6444 else if (*bp == '\\' && bp[1] == '\n')
6446 else if (*bp == '/' && bp[1] == '*') {
6448 while (!(*bp == '*' && bp[1] == '/')) {
6454 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
6456 while (*bp++ != '\n') ;
6463 /* Now find end of directive name.
6464 If we encounter a backslash-newline, exchange it with any following
6465 symbol-constituents so that we end up with a contiguous name. */
6471 if (*bp == '\\' && bp[1] == '\n')
6472 name_newline_fix (bp);
6478 ident_length = bp - cp;
6482 /* A line of just `#' becomes blank. */
6484 if (ident_length == 0 && *after_ident == '\n') {
6488 if (ident_length == 0 || !is_idstart[*ident]) {
6490 while (is_idchar[*p]) {
6491 if (*p < '0' || *p > '9')
6495 /* Handle # followed by a line number. */
6496 if (p != ident && !is_idchar[*p]) {
6498 pedwarn ("`#' followed by integer");
6502 /* Avoid error for `###' and similar cases unless -pedantic. */
6504 while (*p == '#' || is_hor_space[*p]) p++;
6506 if (pedantic && !lang_asm)
6507 pedwarn ("invalid preprocessor directive");
6512 if (!lang_asm && pedantic)
6513 pedwarn ("invalid preprocessor directive name");
6517 for (kt = directive_table; kt->length >= 0; kt++) {
6518 IF_STACK_FRAME *temp;
6519 if (ident_length == kt->length
6520 && strncmp (cp, kt->name, kt->length) == 0) {
6521 /* If we are asked to return on next directive, do so now. */
6529 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
6530 temp->next = if_stack;
6532 temp->lineno = ip->lineno;
6533 temp->fname = ip->nominal_fname;
6534 temp->type = kt->type;
6538 if (pedantic && if_stack != save_if_stack)
6541 if (if_stack == instack[indepth].if_stack) {
6542 error ("`#%s' not within a conditional", kt->name);
6545 else if (if_stack == save_if_stack)
6546 return; /* found what we came for */
6548 if (kt->type != T_ENDIF) {
6549 if (if_stack->type == T_ELSE)
6550 error ("`#else' or `#elif' after `#else'");
6551 if_stack->type = kt->type;
6556 if_stack = if_stack->next;
6563 /* Don't let erroneous code go by. */
6564 if (kt->length < 0 && !lang_asm && pedantic)
6565 pedwarn ("invalid preprocessor directive name");
6569 /* after this returns, rescan will exit because ip->bufp
6570 now points to the end of the buffer.
6571 rescan is responsible for the error message also. */
6575 * handle a #else directive. Do this by just continuing processing
6576 * without changing if_stack ; this is so that the error message
6577 * for missing #endif's etc. will point to the original #if. It
6578 * is possible that something different would be better.
6582 do_else (buf, limit, op, keyword)
6583 U_CHAR *buf, *limit;
6585 struct directive *keyword;
6587 FILE_BUF *ip = &instack[indepth];
6590 SKIP_WHITE_SPACE (buf);
6592 pedwarn ("text following `#else' violates ANSI standard");
6595 if (if_stack == instack[indepth].if_stack) {
6596 error ("`#else' not within a conditional");
6599 /* #ifndef can't have its special treatment for containing the whole file
6600 if it has a #else clause. */
6601 if_stack->control_macro = 0;
6603 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6604 error ("`#else' after `#else'");
6605 fprintf (stderr, " (matches line %d", if_stack->lineno);
6606 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
6607 fprintf (stderr, ", file %s", if_stack->fname);
6608 fprintf (stderr, ")\n");
6610 if_stack->type = T_ELSE;
6613 if (if_stack->if_succeeded)
6614 skip_if_group (ip, 0);
6616 ++if_stack->if_succeeded; /* continue processing input */
6617 output_line_command (ip, op, 1, same_file);
6623 * unstack after #endif command
6627 do_endif (buf, limit, op, keyword)
6628 U_CHAR *buf, *limit;
6630 struct directive *keyword;
6633 SKIP_WHITE_SPACE (buf);
6635 pedwarn ("text following `#endif' violates ANSI standard");
6638 if (if_stack == instack[indepth].if_stack)
6639 error ("unbalanced `#endif'");
6641 IF_STACK_FRAME *temp = if_stack;
6642 if_stack = if_stack->next;
6643 if (temp->control_macro != 0) {
6644 /* This #endif matched a #ifndef at the start of the file.
6645 See if it is at the end of the file. */
6646 FILE_BUF *ip = &instack[indepth];
6647 U_CHAR *p = ip->bufp;
6648 U_CHAR *ep = ip->buf + ip->length;
6658 if (p != ep && *p == '*') {
6659 /* Skip this comment. */
6661 U_CHAR *save_bufp = ip->bufp;
6663 p = skip_to_end_of_comment (ip, &junk, 1);
6664 ip->bufp = save_bufp;
6671 /* If we get here, this #endif ends a #ifndef
6672 that contains all of the file (aside from whitespace).
6673 Arrange not to include the file again
6674 if the macro that was tested is defined. */
6676 record_control_macro (ip->fname, temp->control_macro);
6680 output_line_command (&instack[indepth], op, 1, same_file);
6685 /* When an #else or #endif is found while skipping failed conditional,
6686 if -pedantic was specified, this is called to warn about text after
6687 the command name. P points to the first char after the command name. */
6693 /* Advance P over whitespace and comments. */
6695 if (*p == '\\' && p[1] == '\n')
6697 if (is_hor_space[*p])
6699 else if (*p == '/') {
6700 if (p[1] == '\\' && p[2] == '\n')
6701 newline_fix (p + 1);
6704 /* Don't bother warning about unterminated comments
6705 since that will happen later. Just be sure to exit. */
6707 if (p[1] == '\\' && p[2] == '\n')
6708 newline_fix (p + 1);
6709 if (*p == '*' && p[1] == '/') {
6716 else if (cplusplus_comments && p[1] == '/') {
6718 while (*p && *p++ != '\n') ;
6722 if (*p && *p != '\n')
6723 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
6726 /* Skip a comment, assuming the input ptr immediately follows the
6727 initial slash-star. Bump *LINE_COUNTER for each newline.
6728 (The canonical line counter is &ip->lineno.)
6729 Don't use this routine (or the next one) if bumping the line
6730 counter is not sufficient to deal with newlines in the string.
6732 If NOWARN is nonzero, don't warn about slash-star inside a comment.
6733 This feature is useful when processing a comment that is going to be
6734 processed or was processed at another point in the preprocessor,
6735 to avoid a duplicate warning. */
6737 skip_to_end_of_comment (ip, line_counter, nowarn)
6738 register FILE_BUF *ip;
6739 int *line_counter; /* place to remember newlines, or NULL */
6742 register U_CHAR *limit = ip->buf + ip->length;
6743 register U_CHAR *bp = ip->bufp;
6744 FILE_BUF *op = &outbuf; /* JF */
6745 int output = put_out_comments && !line_counter;
6747 /* JF this line_counter stuff is a crock to make sure the
6748 comment is only put out once, no matter how many times
6749 the comment is skipped. It almost works */
6754 if (cplusplus_comments && bp[-1] == '/') {
6757 if ((*op->bufp++ = *bp++) == '\n') {
6765 while (bp < limit) {
6766 if (*bp++ == '\n') {
6775 while (bp < limit) {
6780 if (warn_comments && !nowarn && bp < limit && *bp == '*')
6781 warning ("`/*' within comment");
6784 if (line_counter != NULL)
6790 if (*bp == '\\' && bp[1] == '\n')
6806 * Skip over a quoted string. BP points to the opening quote.
6807 * Returns a pointer after the closing quote. Don't go past LIMIT.
6808 * START_LINE is the line number of the starting point (but it need
6809 * not be valid if the starting point is inside a macro expansion).
6811 * The input stack state is not changed.
6813 * If COUNT_NEWLINES is nonzero, it points to an int to increment
6814 * for each newline passed.
6816 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
6817 * if we pass a backslash-newline.
6819 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
6822 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
6823 register U_CHAR *bp;
6824 register U_CHAR *limit;
6826 int *count_newlines;
6827 int *backslash_newlines_p;
6830 register U_CHAR c, match;
6835 error_with_line (line_for_error (start_line),
6836 "unterminated string or character constant");
6837 error_with_line (multiline_string_line,
6838 "possible real start of unterminated constant");
6839 multiline_string_line = 0;
6846 while (*bp == '\\' && bp[1] == '\n') {
6847 if (backslash_newlines_p)
6848 *backslash_newlines_p = 1;
6853 if (*bp == '\n' && count_newlines) {
6854 if (backslash_newlines_p)
6855 *backslash_newlines_p = 1;
6859 } else if (c == '\n') {
6861 /* Unterminated strings and character constants are 'legal'. */
6862 bp--; /* Don't consume the newline. */
6867 if (pedantic || match == '\'') {
6868 error_with_line (line_for_error (start_line),
6869 "unterminated string or character constant");
6875 /* If not traditional, then allow newlines inside strings. */
6878 if (multiline_string_line == 0)
6879 multiline_string_line = start_line;
6880 } else if (c == match)
6886 /* Skip across a group of balanced parens, starting from IP->bufp.
6887 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
6889 This does not handle newlines, because it's used for the arg of #if,
6890 where there aren't any newlines. Also, backslash-newline can't appear. */
6893 skip_paren_group (ip)
6894 register FILE_BUF *ip;
6896 U_CHAR *limit = ip->buf + ip->length;
6897 U_CHAR *p = ip->bufp;
6899 int lines_dummy = 0;
6901 while (p != limit) {
6911 return ip->bufp = p;
6917 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
6925 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6927 return ip->bufp = p;
6938 * write out a #line command, for instance, after an #include file.
6939 * If CONDITIONAL is nonzero, we can omit the #line if it would
6940 * appear to be a no-op, and we can output a few newlines instead
6941 * if we want to increase the line number by a small amount.
6942 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
6946 output_line_command (ip, op, conditional, file_change)
6949 enum file_change_code file_change;
6954 if (no_line_commands
6955 || ip->fname == NULL
6957 op->lineno = ip->lineno;
6962 if (ip->lineno == op->lineno)
6965 /* If the inherited line number is a little too small,
6966 output some newlines instead of a #line command. */
6967 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
6968 check_expand (op, 10);
6969 while (ip->lineno > op->lineno) {
6977 /* Don't output a line number of 0 if we can help it. */
6978 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
6979 && *ip->bufp == '\n') {
6984 line_cmd_buf = (char *) alloca (strlen (ip->nominal_fname) + 100);
6985 #ifdef OUTPUT_LINE_COMMANDS
6986 sprintf (line_cmd_buf, "#line %d \"%s\"", ip->lineno, ip->nominal_fname);
6988 sprintf (line_cmd_buf, "# %d \"%s\"", ip->lineno, ip->nominal_fname);
6990 if (file_change != same_file)
6991 strcat (line_cmd_buf, file_change == enter_file ? " 1" : " 2");
6992 /* Tell cc1 if following text comes from a system header file. */
6993 if (ip->system_header_p)
6994 strcat (line_cmd_buf, " 3");
6995 len = strlen (line_cmd_buf);
6996 line_cmd_buf[len++] = '\n';
6997 check_expand (op, len + 1);
6998 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7000 bcopy (line_cmd_buf, op->bufp, len);
7002 op->lineno = ip->lineno;
7005 /* This structure represents one parsed argument in a macro call.
7006 `raw' points to the argument text as written (`raw_length' is its length).
7007 `expanded' points to the argument's macro-expansion
7008 (its length is `expand_length').
7009 `stringified_length' is the length the argument would have
7011 `use_count' is the number of times this macro arg is substituted
7012 into the macro. If the actual use count exceeds 10,
7013 the value stored is 10.
7014 `free1' and `free2', if nonzero, point to blocks to be freed
7015 when the macro argument data is no longer needed. */
7018 U_CHAR *raw, *expanded;
7019 int raw_length, expand_length;
7020 int stringified_length;
7021 U_CHAR *free1, *free2;
7027 /* Expand a macro call.
7028 HP points to the symbol that is the macro being called.
7029 Put the result of expansion onto the input stack
7030 so that subsequent input by our caller will use it.
7032 If macro wants arguments, caller has already verified that
7033 an argument list follows; arguments come from the input stack. */
7036 macroexpand (hp, op)
7041 DEFINITION *defn = hp->value.defn;
7042 register U_CHAR *xbuf;
7044 int start_line = instack[indepth].lineno;
7045 int rest_args, rest_zero;
7047 CHECK_DEPTH (return;);
7049 /* it might not actually be a macro. */
7050 if (hp->type != T_MACRO) {
7051 special_symbol (hp, op);
7055 /* This macro is being used inside a #if, which means it must be */
7056 /* recorded as a precondition. */
7057 if (pcp_inside_if && pcp_outfile && defn->predefined)
7058 dump_single_macro (hp, pcp_outfile);
7060 nargs = defn->nargs;
7064 struct argdata *args;
7065 char *parse_error = 0;
7067 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7069 for (i = 0; i < nargs; i++) {
7070 args[i].raw = (U_CHAR *) "";
7071 args[i].expanded = 0;
7072 args[i].raw_length = args[i].expand_length
7073 = args[i].stringified_length = 0;
7074 args[i].free1 = args[i].free2 = 0;
7075 args[i].use_count = 0;
7078 /* Parse all the macro args that are supplied. I counts them.
7079 The first NARGS args are stored in ARGS.
7080 The rest are discarded.
7081 If rest_args is set then we assume macarg absorbed the rest of the args.
7086 /* Discard the open-parenthesis or comma before the next arg. */
7087 ++instack[indepth].bufp;
7090 if (i < nargs || (nargs == 0 && i == 0)) {
7091 /* if we are working on last arg which absorbs rest of args... */
7092 if (i == nargs - 1 && defn->rest_args)
7094 parse_error = macarg (&args[i], rest_args);
7097 parse_error = macarg (NULL_PTR, 0);
7099 error_with_line (line_for_error (start_line), parse_error);
7103 } while (*instack[indepth].bufp != ')');
7105 /* If we got one arg but it was just whitespace, call that 0 args. */
7107 register U_CHAR *bp = args[0].raw;
7108 register U_CHAR *lim = bp + args[0].raw_length;
7109 /* cpp.texi says for foo ( ) we provide one argument.
7110 However, if foo wants just 0 arguments, treat this as 0. */
7112 while (bp != lim && is_space[*bp]) bp++;
7117 /* Don't output an error message if we have already output one for
7118 a parse error above. */
7120 if (nargs == 0 && i > 0) {
7122 error ("arguments given to macro `%s'", hp->name);
7123 } else if (i < nargs) {
7124 /* traditional C allows foo() if foo wants one argument. */
7125 if (nargs == 1 && i == 0 && traditional)
7127 /* the rest args token is allowed to absorb 0 tokens */
7128 else if (i == nargs - 1 && defn->rest_args)
7130 else if (parse_error)
7133 error ("macro `%s' used without args", hp->name);
7135 error ("macro `%s' used with just one arg", hp->name);
7137 error ("macro `%s' used with only %d args", hp->name, i);
7138 } else if (i > nargs) {
7140 error ("macro `%s' used with too many (%d) args", hp->name, i);
7143 /* Swallow the closeparen. */
7144 ++instack[indepth].bufp;
7146 /* If macro wants zero args, we parsed the arglist for checking only.
7147 Read directly from the macro definition. */
7149 xbuf = defn->expansion;
7150 xbuf_len = defn->length;
7152 register U_CHAR *exp = defn->expansion;
7153 register int offset; /* offset in expansion,
7154 copied a piece at a time */
7155 register int totlen; /* total amount of exp buffer filled so far */
7157 register struct reflist *ap, *last_ap;
7159 /* Macro really takes args. Compute the expansion of this call. */
7161 /* Compute length in characters of the macro's expansion.
7162 Also count number of times each arg is used. */
7163 xbuf_len = defn->length;
7164 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
7166 xbuf_len += args[ap->argno].stringified_length;
7167 else if (ap->raw_before || ap->raw_after || traditional)
7168 /* Add 4 for two newline-space markers to prevent
7169 token concatenation. */
7170 xbuf_len += args[ap->argno].raw_length + 4;
7172 /* We have an ordinary (expanded) occurrence of the arg.
7173 So compute its expansion, if we have not already. */
7174 if (args[ap->argno].expanded == 0) {
7176 obuf = expand_to_temp_buffer (args[ap->argno].raw,
7177 args[ap->argno].raw + args[ap->argno].raw_length,
7180 args[ap->argno].expanded = obuf.buf;
7181 args[ap->argno].expand_length = obuf.length;
7182 args[ap->argno].free2 = obuf.buf;
7185 /* Add 4 for two newline-space markers to prevent
7186 token concatenation. */
7187 xbuf_len += args[ap->argno].expand_length + 4;
7189 if (args[ap->argno].use_count < 10)
7190 args[ap->argno].use_count++;
7193 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
7195 /* Generate in XBUF the complete expansion
7196 with arguments substituted in.
7197 TOTLEN is the total size generated so far.
7198 OFFSET is the index in the definition
7199 of where we are copying from. */
7200 offset = totlen = 0;
7201 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
7202 last_ap = ap, ap = ap->next) {
7203 register struct argdata *arg = &args[ap->argno];
7204 int count_before = totlen;
7206 /* Add chars to XBUF. */
7207 for (i = 0; i < ap->nchars; i++, offset++)
7208 xbuf[totlen++] = exp[offset];
7210 /* If followed by an empty rest arg with concatenation,
7211 delete the last run of nonwhite chars. */
7212 if (rest_zero && totlen > count_before
7213 && ((ap->rest_args && ap->raw_before)
7214 || (last_ap != NULL && last_ap->rest_args
7215 && last_ap->raw_after))) {
7216 /* Delete final whitespace. */
7217 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
7221 /* Delete the nonwhites before them. */
7222 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
7227 if (ap->stringify != 0) {
7228 int arglen = arg->raw_length;
7234 && (c = arg->raw[i], is_space[c]))
7237 && (c = arg->raw[arglen - 1], is_space[c]))
7240 xbuf[totlen++] = '\"'; /* insert beginning quote */
7241 for (; i < arglen; i++) {
7244 /* Special markers Newline Space
7245 generate nothing for a stringified argument. */
7246 if (c == '\n' && arg->raw[i+1] != '\n') {
7251 /* Internal sequences of whitespace are replaced by one space
7252 except within an string or char token. */
7254 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
7256 /* Note that Newline Space does occur within whitespace
7257 sequences; consider it part of the sequence. */
7258 if (c == '\n' && is_space[arg->raw[i+1]])
7260 else if (c != '\n' && is_space[c])
7277 } else if (c == '\"' || c == '\'')
7281 /* Escape these chars */
7282 if (c == '\"' || (in_string && c == '\\'))
7283 xbuf[totlen++] = '\\';
7287 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
7292 xbuf[totlen++] = '\"'; /* insert ending quote */
7293 } else if (ap->raw_before || ap->raw_after || traditional) {
7294 U_CHAR *p1 = arg->raw;
7295 U_CHAR *l1 = p1 + arg->raw_length;
7296 if (ap->raw_before) {
7297 while (p1 != l1 && is_space[*p1]) p1++;
7298 while (p1 != l1 && is_idchar[*p1])
7299 xbuf[totlen++] = *p1++;
7300 /* Delete any no-reexpansion marker that follows
7301 an identifier at the beginning of the argument
7302 if the argument is concatenated with what precedes it. */
7303 if (p1[0] == '\n' && p1[1] == '-')
7305 } else if (!traditional) {
7306 /* Ordinary expanded use of the argument.
7307 Put in newline-space markers to prevent token pasting. */
7308 xbuf[totlen++] = '\n';
7309 xbuf[totlen++] = ' ';
7311 if (ap->raw_after) {
7312 /* Arg is concatenated after: delete trailing whitespace,
7313 whitespace markers, and no-reexpansion markers. */
7315 if (is_space[l1[-1]]) l1--;
7316 else if (l1[-1] == '-') {
7317 U_CHAR *p2 = l1 - 1;
7318 /* If a `-' is preceded by an odd number of newlines then it
7319 and the last newline are a no-reexpansion marker. */
7320 while (p2 != p1 && p2[-1] == '\n') p2--;
7321 if ((l1 - 1 - p2) & 1) {
7330 bcopy (p1, xbuf + totlen, l1 - p1);
7332 if (!traditional && !ap->raw_after) {
7333 /* Ordinary expanded use of the argument.
7334 Put in newline-space markers to prevent token pasting. */
7335 xbuf[totlen++] = '\n';
7336 xbuf[totlen++] = ' ';
7339 /* Ordinary expanded use of the argument.
7340 Put in newline-space markers to prevent token pasting. */
7342 xbuf[totlen++] = '\n';
7343 xbuf[totlen++] = ' ';
7345 bcopy (arg->expanded, xbuf + totlen, arg->expand_length);
7346 totlen += arg->expand_length;
7348 xbuf[totlen++] = '\n';
7349 xbuf[totlen++] = ' ';
7351 /* If a macro argument with newlines is used multiple times,
7352 then only expand the newlines once. This avoids creating output
7353 lines which don't correspond to any input line, which confuses
7355 if (arg->use_count > 1 && arg->newlines > 0) {
7356 /* Don't bother doing change_newlines for subsequent
7360 = change_newlines (arg->expanded, arg->expand_length);
7364 if (totlen > xbuf_len)
7368 /* if there is anything left of the definition
7369 after handling the arg list, copy that in too. */
7371 for (i = offset; i < defn->length; i++) {
7372 /* if we've reached the end of the macro */
7375 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
7376 && last_ap->raw_after))
7377 xbuf[totlen++] = exp[i];
7383 for (i = 0; i < nargs; i++) {
7384 if (args[i].free1 != 0)
7385 free (args[i].free1);
7386 if (args[i].free2 != 0)
7387 free (args[i].free2);
7391 xbuf = defn->expansion;
7392 xbuf_len = defn->length;
7395 /* Now put the expansion on the input stack
7396 so our caller will commence reading from it. */
7398 register FILE_BUF *ip2;
7400 ip2 = &instack[++indepth];
7403 ip2->nominal_fname = 0;
7406 ip2->length = xbuf_len;
7408 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
7410 ip2->if_stack = if_stack;
7411 ip2->system_header_p = 0;
7413 /* Recursive macro use sometimes works traditionally.
7414 #define foo(x,y) bar (x (y,0), y)
7418 hp->type = T_DISABLED;
7423 * Parse a macro argument and store the info on it into *ARGPTR.
7424 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
7425 * Return nonzero to indicate a syntax error.
7429 macarg (argptr, rest_args)
7430 register struct argdata *argptr;
7433 FILE_BUF *ip = &instack[indepth];
7438 /* Try to parse as much of the argument as exists at this
7439 input stack level. */
7440 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
7441 &paren, &newlines, &comments, rest_args);
7443 /* If we find the end of the argument at this level,
7444 set up *ARGPTR to point at it in the input stack. */
7445 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
7446 && bp != ip->buf + ip->length) {
7448 argptr->raw = ip->bufp;
7449 argptr->raw_length = bp - ip->bufp;
7450 argptr->newlines = newlines;
7454 /* This input stack level ends before the macro argument does.
7455 We must pop levels and keep parsing.
7456 Therefore, we must allocate a temporary buffer and copy
7457 the macro argument into it. */
7458 int bufsize = bp - ip->bufp;
7459 int extra = newlines;
7460 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
7461 int final_start = 0;
7463 bcopy (ip->bufp, buffer, bufsize);
7465 ip->lineno += newlines;
7467 while (bp == ip->buf + ip->length) {
7468 if (instack[indepth].macro == 0) {
7470 return "unterminated macro call";
7472 ip->macro->type = T_MACRO;
7474 free (ip->free_ptr);
7475 ip = &instack[--indepth];
7478 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
7479 &newlines, &comments, rest_args);
7480 final_start = bufsize;
7481 bufsize += bp - ip->bufp;
7483 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
7484 bcopy (ip->bufp, buffer + bufsize - (bp - ip->bufp), bp - ip->bufp);
7486 ip->lineno += newlines;
7489 /* Now, if arg is actually wanted, record its raw form,
7490 discarding comments and duplicating newlines in whatever
7491 part of it did not come from a macro expansion.
7492 EXTRA space has been preallocated for duplicating the newlines.
7493 FINAL_START is the index of the start of that part. */
7495 argptr->raw = buffer;
7496 argptr->raw_length = bufsize;
7497 argptr->free1 = buffer;
7498 argptr->newlines = newlines;
7499 argptr->comments = comments;
7500 if ((newlines || comments) && ip->fname != 0)
7503 discard_comments (argptr->raw + final_start,
7504 argptr->raw_length - final_start,
7506 argptr->raw[argptr->raw_length] = 0;
7507 if (argptr->raw_length > bufsize + extra)
7512 /* If we are not discarding this argument,
7513 macroexpand it and compute its length as stringified.
7514 All this info goes into *ARGPTR. */
7517 register U_CHAR *buf, *lim;
7518 register int totlen;
7521 lim = buf + argptr->raw_length;
7523 while (buf != lim && is_space[*buf])
7525 while (buf != lim && is_space[lim[-1]])
7527 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
7528 while (buf != lim) {
7529 register U_CHAR c = *buf++;
7531 /* Internal sequences of whitespace are replaced by one space
7532 in most cases, but not always. So count all the whitespace
7533 in case we need to keep it all. */
7536 SKIP_ALL_WHITE_SPACE (buf);
7539 if (c == '\"' || c == '\\') /* escape these chars */
7541 else if (!isprint (c))
7544 argptr->stringified_length = totlen;
7549 /* Scan text from START (inclusive) up to LIMIT (exclusive),
7550 counting parens in *DEPTHPTR,
7551 and return if reach LIMIT
7552 or before a `)' that would make *DEPTHPTR negative
7553 or before a comma when *DEPTHPTR is zero.
7554 Single and double quotes are matched and termination
7555 is inhibited within them. Comments also inhibit it.
7556 Value returned is pointer to stopping place.
7558 Increment *NEWLINES each time a newline is passed.
7559 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
7560 Set *COMMENTS to 1 if a comment is seen. */
7563 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
7565 register U_CHAR *limit;
7566 int *depthptr, *newlines, *comments;
7569 register U_CHAR *bp = start;
7571 while (bp < limit) {
7577 if (--(*depthptr) < 0)
7581 /* Traditionally, backslash makes following char not special. */
7582 if (bp + 1 < limit && traditional)
7585 /* But count source lines anyway. */
7594 if (bp[1] == '\\' && bp[2] == '\n')
7595 newline_fix (bp + 1);
7596 if (cplusplus_comments && bp[1] == '/') {
7599 while (bp < limit && *bp++ != '\n') ;
7603 if (bp[1] != '*' || bp + 1 >= limit)
7607 while (bp + 1 < limit) {
7609 && bp[1] == '\\' && bp[2] == '\n')
7610 newline_fix (bp + 1);
7611 if (bp[0] == '*' && bp[1] == '/')
7613 if (*bp == '\n') ++*newlines;
7621 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
7626 while (*bp == '\\' && bp[1] == '\n') {
7629 } else if (*bp == '\n') {
7638 /* if we've returned to lowest level and we aren't absorbing all args */
7639 if ((*depthptr) == 0 && rest_args == 0)
7649 /* Discard comments and duplicate newlines
7650 in the string of length LENGTH at START,
7651 except inside of string constants.
7652 The string is copied into itself with its beginning staying fixed.
7654 NEWLINES is the number of newlines that must be duplicated.
7655 We assume that that much extra space is available past the end
7659 discard_comments (start, length, newlines)
7664 register U_CHAR *ibp;
7665 register U_CHAR *obp;
7666 register U_CHAR *limit;
7669 /* If we have newlines to duplicate, copy everything
7670 that many characters up. Then, in the second part,
7671 we will have room to insert the newlines
7673 NEWLINES may actually be too large, because it counts
7674 newlines in string constants, and we don't duplicate those.
7675 But that does no harm. */
7677 ibp = start + length;
7678 obp = ibp + newlines;
7680 while (limit != ibp)
7684 ibp = start + newlines;
7685 limit = start + length + newlines;
7688 while (ibp < limit) {
7689 *obp++ = c = *ibp++;
7692 /* Duplicate the newline. */
7704 if (*ibp == '\\' && ibp[1] == '\n')
7706 /* Delete any comment. */
7707 if (cplusplus_comments && ibp[0] == '/') {
7710 while (ibp < limit && *ibp++ != '\n') ;
7713 if (ibp[0] != '*' || ibp + 1 >= limit)
7717 while (ibp + 1 < limit) {
7719 && ibp[1] == '\\' && ibp[2] == '\n')
7720 newline_fix (ibp + 1);
7721 if (ibp[0] == '*' && ibp[1] == '/')
7730 /* Notice and skip strings, so that we don't
7731 think that comments start inside them,
7732 and so we don't duplicate newlines in them. */
7735 while (ibp < limit) {
7736 *obp++ = c = *ibp++;
7739 if (c == '\n' && quotec == '\'')
7741 if (c == '\\' && ibp < limit) {
7742 while (*ibp == '\\' && ibp[1] == '\n')
7755 /* Turn newlines to spaces in the string of length LENGTH at START,
7756 except inside of string constants.
7757 The string is copied into itself with its beginning staying fixed. */
7760 change_newlines (start, length)
7764 register U_CHAR *ibp;
7765 register U_CHAR *obp;
7766 register U_CHAR *limit;
7770 limit = start + length;
7773 while (ibp < limit) {
7774 *obp++ = c = *ibp++;
7777 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
7778 string. Skip past the newline and its duplicate.
7779 Put a space in the output. */
7790 /* Notice and skip strings, so that we don't delete newlines in them. */
7793 while (ibp < limit) {
7794 *obp++ = c = *ibp++;
7797 if (c == '\n' && quotec == '\'')
7809 * error - print error message and increment count of errors.
7813 error (msg, arg1, arg2, arg3)
7815 char *arg1, *arg2, *arg3;
7818 FILE_BUF *ip = NULL;
7820 print_containing_files ();
7822 for (i = indepth; i >= 0; i--)
7823 if (instack[i].fname != NULL) {
7829 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
7830 fprintf (stderr, msg, arg1, arg2, arg3);
7831 fprintf (stderr, "\n");
7835 /* Error including a message from `errno'. */
7838 error_from_errno (name)
7842 FILE_BUF *ip = NULL;
7844 print_containing_files ();
7846 for (i = indepth; i >= 0; i--)
7847 if (instack[i].fname != NULL) {
7853 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
7855 if (errno < sys_nerr)
7856 fprintf (stderr, "%s: %s\n", name, sys_errlist[errno]);
7858 fprintf (stderr, "%s: undocumented I/O error\n", name);
7863 /* Print error message but don't count it. */
7866 warning (msg, arg1, arg2, arg3)
7868 char *arg1, *arg2, *arg3;
7871 FILE_BUF *ip = NULL;
7873 if (inhibit_warnings)
7876 if (warnings_are_errors)
7879 print_containing_files ();
7881 for (i = indepth; i >= 0; i--)
7882 if (instack[i].fname != NULL) {
7888 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
7889 fprintf (stderr, "warning: ");
7890 fprintf (stderr, msg, arg1, arg2, arg3);
7891 fprintf (stderr, "\n");
7895 error_with_line (line, msg, arg1, arg2, arg3)
7898 char *arg1, *arg2, *arg3;
7901 FILE_BUF *ip = NULL;
7903 print_containing_files ();
7905 for (i = indepth; i >= 0; i--)
7906 if (instack[i].fname != NULL) {
7912 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
7913 fprintf (stderr, msg, arg1, arg2, arg3);
7914 fprintf (stderr, "\n");
7919 warning_with_line (line, msg, arg1, arg2, arg3)
7922 char *arg1, *arg2, *arg3;
7925 FILE_BUF *ip = NULL;
7927 if (inhibit_warnings)
7930 if (warnings_are_errors)
7933 print_containing_files ();
7935 for (i = indepth; i >= 0; i--)
7936 if (instack[i].fname != NULL) {
7942 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
7943 fprintf (stderr, "warning: ");
7944 fprintf (stderr, msg, arg1, arg2, arg3);
7945 fprintf (stderr, "\n");
7948 /* print an error message and maybe count it. */
7951 pedwarn (msg, arg1, arg2, arg3)
7953 char *arg1, *arg2, *arg3;
7955 if (pedantic_errors)
7956 error (msg, arg1, arg2, arg3);
7958 warning (msg, arg1, arg2, arg3);
7962 pedwarn_with_line (line, msg, arg1, arg2, arg3)
7965 char *arg1, *arg2, *arg3;
7967 if (pedantic_errors)
7968 error_with_line (line, msg, arg1, arg2, arg3);
7970 warning_with_line (line, msg, arg1, arg2, arg3);
7973 /* Report a warning (or an error if pedantic_errors)
7974 giving specified file name and line number, not current. */
7977 pedwarn_with_file_and_line (file, line, msg, arg1, arg2, arg3)
7981 char *arg1, *arg2, *arg3;
7984 if (!pedantic_errors && inhibit_warnings)
7987 fprintf (stderr, "%s:%d: ", file, line);
7988 if (pedantic_errors)
7990 if (!pedantic_errors)
7991 fprintf (stderr, "warning: ");
7992 fprintf (stderr, msg, arg1, arg2, arg3);
7993 fprintf (stderr, "\n");
7996 /* Print the file names and line numbers of the #include
7997 commands which led to the current file. */
8000 print_containing_files ()
8002 FILE_BUF *ip = NULL;
8006 /* If stack of files hasn't changed since we last printed
8007 this info, don't repeat it. */
8008 if (last_error_tick == input_file_stack_tick)
8011 for (i = indepth; i >= 0; i--)
8012 if (instack[i].fname != NULL) {
8017 /* Give up if we don't find a source file. */
8021 /* Find the other, outer source files. */
8022 for (i--; i >= 0; i--)
8023 if (instack[i].fname != NULL) {
8027 fprintf (stderr, "In file included");
8029 fprintf (stderr, ",\n ");
8032 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
8035 fprintf (stderr, ":\n");
8037 /* Record we have printed the status as of this time. */
8038 last_error_tick = input_file_stack_tick;
8041 /* Return the line at which an error occurred.
8042 The error is not necessarily associated with the current spot
8043 in the input stack, so LINE says where. LINE will have been
8044 copied from ip->lineno for the current input level.
8045 If the current level is for a file, we return LINE.
8046 But if the current level is not for a file, LINE is meaningless.
8047 In that case, we return the lineno of the innermost file. */
8050 line_for_error (line)
8056 for (i = indepth; i >= 0; ) {
8057 if (instack[i].fname != 0)
8062 line1 = instack[i].lineno;
8070 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
8072 * As things stand, nothing is ever placed in the output buffer to be
8073 * removed again except when it's KNOWN to be part of an identifier,
8074 * so flushing and moving down everything left, instead of expanding,
8078 /* You might think void was cleaner for the return type,
8079 but that would get type mismatch in check_expand in strict ANSI. */
8081 grow_outbuf (obuf, needed)
8082 register FILE_BUF *obuf;
8083 register int needed;
8088 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
8091 /* Make it at least twice as big as it is now. */
8093 /* Make it have at least 150% of the free space we will need. */
8094 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
8095 if (minsize > obuf->length)
8096 obuf->length = minsize;
8098 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
8101 obuf->bufp = p + (obuf->bufp - obuf->buf);
8107 /* Symbol table for macro names and special symbols */
8110 * install a name in the main hash table, even if it is already there.
8111 * name stops with first non alphanumeric, except leading '#'.
8112 * caller must check against redefinition if that is desired.
8113 * delete_macro () removes things installed by install () in fifo order.
8114 * this is important because of the `defined' special symbol used
8115 * in #if, and also if pushdef/popdef directives are ever implemented.
8117 * If LEN is >= 0, it is the length of the name.
8118 * Otherwise, compute the length by scanning the entire name.
8120 * If HASH is >= 0, it is the precomputed hash code.
8121 * Otherwise, compute the hash code.
8124 install (name, len, type, ivalue, value, hash)
8127 enum node_type type;
8132 register HASHNODE *hp;
8133 register int i, bucket;
8134 register U_CHAR *p, *q;
8138 while (is_idchar[*p])
8144 hash = hashf (name, len, HASHSIZE);
8146 i = sizeof (HASHNODE) + len + 1;
8147 hp = (HASHNODE *) xmalloc (i);
8149 hp->bucket_hdr = &hashtab[bucket];
8150 hp->next = hashtab[bucket];
8151 hashtab[bucket] = hp;
8153 if (hp->next != NULL)
8154 hp->next->prev = hp;
8157 if (hp->type == T_CONST)
8158 hp->value.ival = ivalue;
8160 hp->value.cpval = value;
8161 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
8164 for (i = 0; i < len; i++)
8171 * find the most recent hash node for name name (ending with first
8172 * non-identifier char) installed by install
8174 * If LEN is >= 0, it is the length of the name.
8175 * Otherwise, compute the length by scanning the entire name.
8177 * If HASH is >= 0, it is the precomputed hash code.
8178 * Otherwise, compute the hash code.
8181 lookup (name, len, hash)
8186 register U_CHAR *bp;
8187 register HASHNODE *bucket;
8190 for (bp = name; is_idchar[*bp]; bp++) ;
8195 hash = hashf (name, len, HASHSIZE);
8197 bucket = hashtab[hash];
8199 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
8201 bucket = bucket->next;
8207 * Delete a hash node. Some weirdness to free junk from macros.
8208 * More such weirdness will have to be added if you define more hash
8209 * types that need it.
8212 /* Note that the DEFINITION of a macro is removed from the hash table
8213 but its storage is not freed. This would be a storage leak
8214 except that it is not reasonable to keep undefining and redefining
8215 large numbers of macros many times.
8216 In any case, this is necessary, because a macro can be #undef'd
8217 in the middle of reading the arguments to a call to it.
8218 If #undef freed the DEFINITION, that would crash. */
8225 if (hp->prev != NULL)
8226 hp->prev->next = hp->next;
8227 if (hp->next != NULL)
8228 hp->next->prev = hp->prev;
8230 /* make sure that the bucket chain header that
8231 the deleted guy was on points to the right thing afterwards. */
8232 if (hp == *hp->bucket_hdr)
8233 *hp->bucket_hdr = hp->next;
8236 if (hp->type == T_MACRO) {
8237 DEFINITION *d = hp->value.defn;
8238 struct reflist *ap, *nextap;
8240 for (ap = d->pattern; ap != NULL; ap = nextap) {
8251 * return hash function on name. must be compatible with the one
8252 * computed a step at a time, elsewhere
8255 hashf (name, len, hashsize)
8256 register U_CHAR *name;
8263 r = HASHSTEP (r, *name++);
8265 return MAKE_POS (r) % hashsize;
8269 /* Dump the definition of a single macro HP to OF. */
8271 dump_single_macro (hp, of)
8272 register HASHNODE *hp;
8275 register DEFINITION *defn = hp->value.defn;
8281 /* Print the definition of the macro HP. */
8283 fprintf (of, "#define %s", hp->name);
8285 if (defn->nargs >= 0) {
8289 for (i = 0; i < defn->nargs; i++) {
8290 dump_arg_n (defn, i, of);
8291 if (i + 1 < defn->nargs)
8301 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8302 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
8303 if (ap->nchars != 0)
8305 offset += ap->nchars;
8308 if (ap->raw_before && !concat)
8309 fprintf (of, " ## ");
8311 dump_arg_n (defn, ap->argno, of);
8312 if (ap->raw_after) {
8313 fprintf (of, " ## ");
8317 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
8321 /* Dump all macro definitions as #defines to stdout. */
8328 for (bucket = 0; bucket < HASHSIZE; bucket++) {
8329 register HASHNODE *hp;
8331 for (hp = hashtab[bucket]; hp; hp= hp->next) {
8332 if (hp->type == T_MACRO)
8333 dump_single_macro (hp, stdout);
8338 /* Output to OF a substring of a macro definition.
8339 BASE is the beginning of the definition.
8340 Output characters START thru LENGTH.
8341 Discard newlines outside of strings, thus
8342 converting funny-space markers to ordinary spaces. */
8345 dump_defn_1 (base, start, length, of)
8351 U_CHAR *p = base + start;
8352 U_CHAR *limit = base + start + length;
8357 else if (*p == '\"' || *p =='\'') {
8358 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
8359 NULL_PTR, NULL_PTR);
8360 fwrite (p, p1 - p, 1, of);
8367 /* Print the name of argument number ARGNUM of macro definition DEFN
8369 Recall that DEFN->args.argnames contains all the arg names
8370 concatenated in reverse order with comma-space in between. */
8373 dump_arg_n (defn, argnum, of)
8378 register U_CHAR *p = defn->args.argnames;
8379 while (argnum + 1 < defn->nargs) {
8380 p = (U_CHAR *) index (p, ' ') + 1;
8384 while (*p && *p != ',') {
8390 /* Initialize syntactic classifications of characters. */
8393 initialize_char_syntax ()
8398 * Set up is_idchar and is_idstart tables. These should be
8399 * faster than saying (is_alpha (c) || c == '_'), etc.
8400 * Set up these things before calling any routines tthat
8403 for (i = 'a'; i <= 'z'; i++) {
8404 is_idchar[i - 'a' + 'A'] = 1;
8406 is_idstart[i - 'a' + 'A'] = 1;
8409 for (i = '0'; i <= '9'; i++)
8412 is_idstart['_'] = 1;
8413 is_idchar['$'] = dollars_in_ident;
8414 is_idstart['$'] = dollars_in_ident;
8416 /* horizontal space table */
8417 is_hor_space[' '] = 1;
8418 is_hor_space['\t'] = 1;
8419 is_hor_space['\v'] = 1;
8420 is_hor_space['\f'] = 1;
8421 is_hor_space['\r'] = 1;
8431 /* Initialize the built-in macros. */
8434 initialize_builtins (inp, outp)
8438 install ("__LINE__", -1, T_SPECLINE, 0, 0, -1);
8439 install ("__DATE__", -1, T_DATE, 0, 0, -1);
8440 install ("__FILE__", -1, T_FILE, 0, 0, -1);
8441 install ("__BASE_FILE__", -1, T_BASE_FILE, 0, 0, -1);
8442 install ("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, 0, -1);
8443 install ("__VERSION__", -1, T_VERSION, 0, 0, -1);
8444 #ifndef NO_BUILTIN_SIZE_TYPE
8445 install ("__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, 0, -1);
8447 #ifndef NO_BUILTIN_PTRDIFF_TYPE
8448 install ("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, 0, -1);
8450 install ("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, 0, -1);
8451 install ("__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE, 0, 0, -1);
8452 install ("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, 0, -1);
8453 install ("__TIME__", -1, T_TIME, 0, 0, -1);
8455 install ("__STDC__", -1, T_CONST, STDC_VALUE, 0, -1);
8457 install ("__OBJC__", -1, T_CONST, 1, 0, -1);
8458 /* This is supplied using a -D by the compiler driver
8459 so that it is present only when truly compiling with GNU C. */
8460 /* install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
8464 char directive[2048];
8465 register struct directive *dp = &directive_table[0];
8466 struct tm *timebuf = timestamp ();
8468 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
8469 instack[0].nominal_fname);
8470 output_line_command (inp, outp, 0, same_file);
8471 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8473 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
8474 output_line_command (inp, outp, 0, same_file);
8475 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8477 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
8478 output_line_command (inp, outp, 0, same_file);
8479 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8481 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
8482 output_line_command (inp, outp, 0, same_file);
8483 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8485 sprintf (directive, " __WCHAR_TYPE__ %s\n", WCHAR_TYPE);
8486 output_line_command (inp, outp, 0, same_file);
8487 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8489 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
8490 monthnames[timebuf->tm_mon],
8491 timebuf->tm_mday, timebuf->tm_year + 1900);
8492 output_line_command (inp, outp, 0, same_file);
8493 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8495 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
8496 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
8497 output_line_command (inp, outp, 0, same_file);
8498 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
8502 sprintf (directive, " __STDC__ 1");
8503 output_line_command (inp, outp, 0, same_file);
8504 pass_thru_directive (directive, &directive[strlen (directive)],
8509 sprintf (directive, " __OBJC__ 1");
8510 output_line_command (inp, outp, 0, same_file);
8511 pass_thru_directive (directive, &directive[strlen (directive)],
8518 * process a given definition string, for initialization
8519 * If STR is just an identifier, define it with value 1.
8520 * If STR has anything after the identifier, then it should
8521 * be identifier=definition.
8525 make_definition (str, op)
8530 struct directive *kt;
8535 if (!is_idstart[*p]) {
8536 error ("malformed option `-D %s'", str);
8539 while (is_idchar[*++p])
8542 buf = (U_CHAR *) alloca (p - buf + 4);
8543 strcpy ((char *)buf, str);
8544 strcat ((char *)buf, " 1");
8545 } else if (*p != '=') {
8546 error ("malformed option `-D %s'", str);
8550 /* Copy the entire option so we can modify it. */
8551 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
8552 strncpy (buf, str, p - str);
8553 /* Change the = to a space. */
8555 /* Scan for any backslash-newline and remove it. */
8559 if (*p == '\\' && p[1] == '\n')
8561 /* Change newline chars into newline-markers. */
8562 else if (*p == '\n')
8574 ip = &instack[++indepth];
8575 ip->nominal_fname = ip->fname = "*Initialization*";
8577 ip->buf = ip->bufp = buf;
8578 ip->length = strlen (buf);
8582 ip->if_stack = if_stack;
8583 ip->system_header_p = 0;
8585 for (kt = directive_table; kt->type != T_DEFINE; kt++)
8588 /* Pass NULL instead of OP, since this is a "predefined" macro. */
8589 do_define (buf, buf + strlen (buf), NULL, kt);
8593 /* JF, this does the work for the -U option */
8596 make_undef (str, op)
8601 struct directive *kt;
8603 ip = &instack[++indepth];
8604 ip->nominal_fname = ip->fname = "*undef*";
8606 ip->buf = ip->bufp = str;
8607 ip->length = strlen (str);
8611 ip->if_stack = if_stack;
8612 ip->system_header_p = 0;
8614 for (kt = directive_table; kt->type != T_UNDEF; kt++)
8617 do_undef (str, str + strlen (str), op, kt);
8621 /* Process the string STR as if it appeared as the body of a #assert.
8622 OPTION is the option name for which STR was the argument. */
8625 make_assertion (option, str)
8630 struct directive *kt;
8631 U_CHAR *buf, *p, *q;
8633 /* Copy the entire option so we can modify it. */
8634 buf = (U_CHAR *) alloca (strlen (str) + 1);
8635 strcpy ((char *) buf, str);
8636 /* Scan for any backslash-newline and remove it. */
8639 if (*p == '\\' && p[1] == '\n')
8647 if (!is_idstart[*p]) {
8648 error ("malformed option `%s %s'", option, str);
8651 while (is_idchar[*++p])
8653 while (*p == ' ' || *p == '\t') p++;
8654 if (! (*p == 0 || *p == '(')) {
8655 error ("malformed option `%s %s'", option, str);
8659 ip = &instack[++indepth];
8660 ip->nominal_fname = ip->fname = "*Initialization*";
8662 ip->buf = ip->bufp = buf;
8663 ip->length = strlen (buf);
8667 ip->if_stack = if_stack;
8668 ip->system_header_p = 0;
8670 for (kt = directive_table; kt->type != T_ASSERT; kt++)
8673 /* pass NULL as output ptr to do_define since we KNOW it never
8674 does any output.... */
8675 do_assert (buf, buf + strlen (buf) , NULL_PTR, kt);
8679 /* Append a chain of `struct file_name_list's
8680 to the end of the main include chain.
8681 FIRST is the beginning of the chain to append, and LAST is the end. */
8684 append_include_chain (first, last)
8685 struct file_name_list *first, *last;
8687 struct file_name_list *dir;
8689 if (!first || !last)
8695 last_include->next = first;
8697 if (first_bracket_include == 0)
8698 first_bracket_include = first;
8700 for (dir = first; ; dir = dir->next) {
8701 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
8702 if (len > max_include_len)
8703 max_include_len = len;
8709 last_include = last;
8712 /* Add output to `deps_buffer' for the -M switch.
8713 STRING points to the text to be output.
8714 SIZE is the number of bytes, or 0 meaning output until a null.
8715 Outputting the empty string breaks the line if it is long enough. */
8718 deps_output (string, size)
8723 size = strlen (string);
8725 #ifndef MAX_OUTPUT_COLUMNS
8726 #define MAX_OUTPUT_COLUMNS 75
8728 if (size == 0 && deps_column != 0
8729 && size + deps_column > MAX_OUTPUT_COLUMNS) {
8730 deps_output ("\\\n ", 0);
8734 if (deps_size + size + 1 > deps_allocated_size) {
8735 deps_allocated_size = deps_size + size + 50;
8736 deps_allocated_size *= 2;
8737 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
8739 bcopy (string, &deps_buffer[deps_size], size);
8741 deps_column += size;
8742 deps_buffer[deps_size] = 0;
8745 #if defined(USG) || defined(VMS)
8751 register unsigned length;
8753 while (length-- > 0)
8758 bcopy (b1, b2, length)
8761 register unsigned length;
8763 while (length-- > 0)
8768 bcmp (b1, b2, length) /* This could be a macro! */
8771 register unsigned length;
8773 while (length-- > 0)
8779 #endif /* not BSTRING */
8780 #endif /* USG or VMS */
8787 fprintf (stderr, "%s: ", progname);
8788 fprintf (stderr, str, arg);
8789 fprintf (stderr, "\n");
8790 exit (FAILURE_EXIT_CODE);
8793 /* More 'friendly' abort that prints the line and file.
8794 config.h can #define abort fancy_abort if you like that sort of thing. */
8799 fatal ("Internal gcc abort.");
8803 perror_with_name (name)
8806 fprintf (stderr, "%s: ", progname);
8807 if (errno < sys_nerr)
8808 fprintf (stderr, "%s: %s\n", name, sys_errlist[errno]);
8810 fprintf (stderr, "%s: undocumented I/O error\n", name);
8815 pfatal_with_name (name)
8818 perror_with_name (name);
8822 exit (FAILURE_EXIT_CODE);
8826 /* Handler for SIGPIPE. */
8830 /* If this is missing, some compilers complain. */
8833 fatal ("output pipe has been closed");
8839 fatal ("Memory exhausted.");
8847 register char *ptr = (char *) malloc (size);
8848 if (ptr != 0) return (ptr);
8855 xrealloc (old, size)
8859 register char *ptr = (char *) realloc (old, size);
8860 if (ptr != 0) return (ptr);
8867 xcalloc (number, size)
8868 unsigned number, size;
8870 register unsigned total = number * size;
8871 register char *ptr = (char *) malloc (total);
8876 /* It's not too long, so loop, zeroing by longs.
8877 It must be safe because malloc values are always well aligned. */
8878 register long *zp = (long *) ptr;
8879 register long *zl = (long *) (ptr + total - 4);
8880 register int i = total - 4;
8899 unsigned size = strlen (input);
8900 char *output = xmalloc (size + 1);
8901 strcpy (output, input);
8905 /* Get the file-mode and data size of the file open on FD
8906 and store them in *MODE_POINTER and *SIZE_POINTER. */
8909 file_size_and_mode (fd, mode_pointer, size_pointer)
8912 long int *size_pointer;
8916 if (fstat (fd, &sbuf) < 0) return (-1);
8917 if (mode_pointer) *mode_pointer = sbuf.st_mode;
8918 if (size_pointer) *size_pointer = sbuf.st_size;
8924 /* Under VMS we need to fix up the "include" specification
8925 filename so that everything following the 1st slash is
8926 changed into its correct VMS file specification. */
8929 hack_vms_include_specification (fname)
8932 register char *cp, *cp1, *cp2;
8933 int f, check_filename_before_returning, no_prefix_seen;
8936 check_filename_before_returning = 0;
8939 /* Ignore leading "./"s */
8940 while (fname[0] == '.' && fname[1] == '/') {
8941 strcpy (fname, fname+2);
8942 no_prefix_seen = 1; /* mark this for later */
8944 /* Look for the boundary between the VMS and UNIX filespecs */
8945 cp = rindex (fname, ']'); /* Look for end of dirspec. */
8946 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
8947 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
8951 cp = index (fname, '/'); /* Look for the "/" */
8954 cp2 = Local; /* initialize */
8956 /* We are trying to do a number of things here. First of all, we are
8957 trying to hammer the filenames into a standard format, such that later
8958 processing can handle them.
8960 If the file name contains something like [dir.], then it recognizes this
8961 as a root, and strips the ".]". Later processing will add whatever is
8962 needed to get things working properly.
8964 If no device is specified, then the first directory name is taken to be
8965 a device name (or a rooted logical). */
8967 /* See if we found that 1st slash */
8968 if (cp == 0) return; /* Nothing to do!!! */
8969 if (*cp != '/') return; /* Nothing to do!!! */
8970 /* Point to the UNIX filename part (which needs to be fixed!) */
8972 /* If the directory spec is not rooted, we can just copy
8973 the UNIX filename part and we are done */
8974 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
8975 if (cp[-2] != '.') {
8977 * The VMS part ends in a `]', and the preceding character is not a `.'.
8978 * We strip the `]', and then splice the two parts of the name in the
8979 * usual way. Given the default locations for include files in cccp.c,
8980 * we will only use this code if the user specifies alternate locations
8981 * with the /include (-I) switch on the command line. */
8982 cp -= 1; /* Strip "]" */
8983 cp1--; /* backspace */
8986 * The VMS part has a ".]" at the end, and this will not do. Later
8987 * processing will add a second directory spec, and this would be a syntax
8988 * error. Thus we strip the ".]", and thus merge the directory specs.
8989 * We also backspace cp1, so that it points to a '/'. This inhibits the
8990 * generation of the 000000 root directory spec (which does not belong here
8993 cp -= 2; /* Strip ".]" */
8994 cp1--; }; /* backspace */
8997 /* We drop in here if there is no VMS style directory specification yet.
8998 * If there is no device specification either, we make the first dir a
8999 * device and try that. If we do not do this, then we will be essentially
9000 * searching the users default directory (as if they did a #include "asdf.h").
9002 * Then all we need to do is to push a '[' into the output string. Later
9003 * processing will fill this in, and close the bracket.
9005 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
9006 *cp2++ = '['; /* Open the directory specification */
9009 /* at this point we assume that we have the device spec, and (at least
9010 the opening "[" for a directory specification. We may have directories
9011 specified already */
9013 /* If there are no other slashes then the filename will be
9014 in the "root" directory. Otherwise, we need to add
9015 directory specifications. */
9016 if (index (cp1, '/') == 0) {
9017 /* Just add "000000]" as the directory string */
9018 strcpy (cp2, "000000]");
9019 cp2 += strlen (cp2);
9020 check_filename_before_returning = 1; /* we might need to fool with this later */
9022 /* As long as there are still subdirectories to add, do them. */
9023 while (index (cp1, '/') != 0) {
9024 /* If this token is "." we can ignore it */
9025 if ((cp1[0] == '.') && (cp1[1] == '/')) {
9029 /* Add a subdirectory spec. Do not duplicate "." */
9030 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
9032 /* If this is ".." then the spec becomes "-" */
9033 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
9034 /* Add "-" and skip the ".." */
9039 /* Copy the subdirectory */
9040 while (*cp1 != '/') *cp2++= *cp1++;
9041 cp1++; /* Skip the "/" */
9043 /* Close the directory specification */
9044 if (cp2[-1] == '.') /* no trailing periods */
9048 /* Now add the filename */
9049 while (*cp1) *cp2++ = *cp1++;
9051 /* Now append it to the original VMS spec. */
9054 /* If we put a [000000] in the filename, try to open it first. If this fails,
9055 remove the [000000], and return that name. This provides flexibility
9056 to the user in that they can use both rooted and non-rooted logical names
9057 to point to the location of the file. */
9059 if (check_filename_before_returning && no_prefix_seen) {
9060 f = open (fname, O_RDONLY, 0666);
9062 /* The file name is OK as it is, so return it as is. */
9066 /* The filename did not work. Try to remove the [000000] from the name,
9068 cp = index (fname, '[');
9069 cp2 = index (fname, ']') + 1;
9070 strcpy (cp, cp2); /* this gets rid of it */
9078 /* These are the read/write replacement routines for
9079 VAX-11 "C". They make read/write behave enough
9080 like their UNIX counterparts that CCCP will work */
9083 read (fd, buf, size)
9088 #undef read /* Get back the REAL read routine */
9090 register int total = 0;
9092 /* Read until the buffer is exhausted */
9094 /* Limit each read to 32KB */
9095 i = (size > (32*1024)) ? (32*1024) : size;
9096 i = read (fd, buf, i);
9098 if (i == 0) return (total);
9101 /* Account for this read */
9110 write (fd, buf, size)
9115 #undef write /* Get back the REAL write routine */
9119 /* Limit individual writes to 32Kb */
9122 j = (i > (32*1024)) ? (32*1024) : i;
9123 if (write (fd, buf, j) < 0) return (-1);
9124 /* Account for the data written */
9131 /* The following wrapper functions supply additional arguments to the VMS
9132 I/O routines to optimize performance with file handling. The arguments
9134 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
9135 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
9136 "fop=tef"- Truncate unused portions of file when closing file.
9137 "shr=nil"- Disallow file sharing while file is open.
9141 freopen (fname, type, oldfile)
9146 #undef freopen /* Get back the REAL fopen routine */
9147 if (strcmp (type, "w") == 0)
9148 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
9149 return freopen (fname, type, oldfile, "mbc=16");
9157 #undef fopen /* Get back the REAL fopen routine */
9158 if (strcmp (type, "w") == 0)
9159 return fopen (fname, type, "mbc=16", "deq=64", "fop=tef", "shr=nil");
9160 return fopen (fname, type, "mbc=16");
9164 open (fname, flags, prot)
9169 #undef open /* Get back the REAL open routine */
9170 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
9173 /* Avoid run-time library bug, where copying M out of N+M characters with
9174 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
9175 gcc-cpp exercises this particular bug. */
9178 strncat (dst, src, cnt)
9183 register char *d = dst, *s = (char *) src;
9184 register int n = cnt; /* convert to _signed_ type */
9186 while (*d) d++; /* advance to end */
9188 if (!(*d++ = *s++)) break;
9189 if (n < 0) *d = '\0';