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