* tradcpp.c: New file.
[official-gcc.git] / gcc / tradcpp.c
blobec42b63db99eb4ae701457994c648d75c576e494
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 1987, 1989, 2000 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
5 Dusted off, polished, and adapted for use as traditional
6 preprocessor only, Zack Weinberg, Jul 2000
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 1, or (at your option) any
11 later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22 In other words, you are welcome to use, share and improve this program.
23 You are forbidden to forbid anyone else to use, share and improve
24 what you give them. Help stamp out software-hoarding! */
26 #include "config.h"
27 #include "system.h"
28 #include "version.h"
29 #include "cppdefault.h"
31 #include <signal.h>
33 typedef unsigned char U_CHAR;
35 /* Name under which this program was invoked. */
37 char *progname;
39 /* Current maximum length of directory names in the search path
40 for include files. (Altered as we get more of them.) */
42 size_t max_include_len;
44 /* Nonzero means copy comments into the output file. */
46 int put_out_comments = 0;
48 /* Nonzero means print the names of included files rather than
49 the preprocessed output. 1 means just the #include "...",
50 2 means #include <...> as well. */
52 int print_deps = 0;
54 /* Nonzero means don't output line number information. */
56 int no_line_commands;
58 /* Nonzero means inhibit output of the preprocessed text
59 and instead output the definitions of all user-defined macros
60 in a form suitable for use as input to cccp. */
62 int dump_macros;
64 /* Nonzero means don't print warning messages. -w. */
66 int inhibit_warnings = 0;
68 /* Nonzero means warn if slash-star appears in a comment. */
70 int warn_comments;
72 /* Nonzero causes output not to be done,
73 but directives such as #define that have side effects
74 are still obeyed. */
76 int no_output;
78 /* Value of __USER_LABEL_PREFIX__. Target-dependent, also controlled
79 by -f(no-)leading-underscore. */
80 const char *user_label_prefix;
82 /* I/O buffer structure.
83 The `fname' field is nonzero for source files and #include files
84 and for the dummy text used for -D and -U.
85 It is zero for rescanning results of macro expansion
86 and for expanding macro arguments. */
87 #define INPUT_STACK_MAX 200
88 struct file_buf {
89 const char *fname;
90 int lineno;
91 int length;
92 U_CHAR *buf;
93 U_CHAR *bufp;
94 /* Macro that this level is the expansion of.
95 Included so that we can reenable the macro
96 at the end of this level. */
97 struct hashnode *macro;
98 /* Value of if_stack at start of this file.
99 Used to prohibit unmatched #endif (etc) in an include file. */
100 struct if_stack *if_stack;
101 /* Object to be freed at end of input at this level. */
102 U_CHAR *free_ptr;
103 } instack[INPUT_STACK_MAX];
105 typedef struct file_buf FILE_BUF;
107 /* Current nesting level of input sources.
108 `instack[indepth]' is the level currently being read. */
109 int indepth = -1;
110 #define CHECK_DEPTH(code) \
111 if (indepth >= (INPUT_STACK_MAX - 1)) \
113 error_with_line (line_for_error (instack[indepth].lineno), \
114 "macro or #include recursion too deep"); \
115 code; \
118 /* Current depth in #include directives that use <...>. */
119 int system_include_depth = 0;
121 /* The output buffer. Its LENGTH field is the amount of room allocated
122 for the buffer, not the number of chars actually present. To get
123 that, subtract outbuf.buf from outbuf.bufp. */
125 #define OUTBUF_SIZE 10 /* initial size of output buffer */
126 FILE_BUF outbuf;
128 /* Grow output buffer OBUF points at
129 so it can hold at least NEEDED more chars. */
131 #define check_expand(OBUF, NEEDED) do { \
132 if ((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
133 grow_outbuf ((OBUF), (NEEDED)); \
134 } while (0)
136 struct file_name_list
138 struct file_name_list *next;
139 const char *fname;
142 struct file_name_list *include = 0; /* First dir to search */
143 /* First dir to search for <file> */
144 struct file_name_list *first_bracket_include = 0;
145 struct file_name_list *last_include = 0; /* Last in chain */
147 /* List of included files that contained #once. */
148 struct file_name_list *dont_repeat_files = 0;
150 /* List of other included files. */
151 struct file_name_list *all_include_files = 0;
153 /* Structure allocated for every #define. For a simple replacement
154 such as
155 #define foo bar ,
156 nargs = -1, the `pattern' list is null, and the expansion is just
157 the replacement text. Nargs = 0 means a functionlike macro with no args,
158 e.g.,
159 #define getchar() getc (stdin) .
160 When there are args, the expansion is the replacement text with the
161 args squashed out, and the reflist is a list describing how to
162 build the output from the input: e.g., "3 chars, then the 1st arg,
163 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
164 The chars here come from the expansion. Whatever is left of the
165 expansion after the last arg-occurrence is copied after that arg.
166 Note that the reflist can be arbitrarily long---
167 its length depends on the number of times the arguments appear in
168 the replacement text, not how many args there are. Example:
169 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
170 pattern list
171 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
172 where (x, y) means (nchars, argno). */
174 typedef struct definition DEFINITION;
175 struct definition {
176 int nargs;
177 int length; /* length of expansion string */
178 U_CHAR *expansion;
179 struct reflist {
180 struct reflist *next;
181 char stringify; /* nonzero if this arg was preceded by a
182 # operator. */
183 char raw_before; /* Nonzero if a ## operator before arg. */
184 char raw_after; /* Nonzero if a ## operator after arg. */
185 int nchars; /* Number of literal chars to copy before
186 this arg occurrence. */
187 int argno; /* Number of arg to substitute (origin-0) */
188 } *pattern;
189 /* Names of macro args, concatenated in reverse order
190 with comma-space between them.
191 The only use of this is that we warn on redefinition
192 if this differs between the old and new definitions. */
193 U_CHAR *argnames;
196 /* different kinds of things that can appear in the value field
197 of a hash node. Actually, this may be useless now. */
198 union hashval {
199 const char *cpval;
200 DEFINITION *defn;
204 /* The structure of a node in the hash table. The hash table
205 has entries for all tokens defined by #define commands (type T_MACRO),
206 plus some special tokens like __LINE__ (these each have their own
207 type, and the appropriate code is run when that type of node is seen.
208 It does not contain control words like "#define", which are recognized
209 by a separate piece of code. */
211 /* different flavors of hash nodes --- also used in keyword table */
212 enum node_type {
213 T_DEFINE = 1, /* `#define' */
214 T_INCLUDE, /* `#include' */
215 T_IFDEF, /* `#ifdef' */
216 T_IFNDEF, /* `#ifndef' */
217 T_IF, /* `#if' */
218 T_ELSE, /* `#else' */
219 T_ELIF, /* `#elif' */
220 T_UNDEF, /* `#undef' */
221 T_LINE, /* `#line' */
222 T_ENDIF, /* `#endif' */
223 T_SPECLINE, /* special symbol `__LINE__' */
224 T_DATE, /* `__DATE__' */
225 T_FILE, /* `__FILE__' */
226 T_BASE_FILE, /* `__BASE_FILE__' */
227 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
228 T_VERSION, /* `__VERSION__' */
229 T_TIME, /* `__TIME__' */
230 T_CONST, /* Constant value, used by `__STDC__' */
231 T_MACRO, /* macro defined by `#define' */
232 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
233 T_UNUSED /* Used for something not defined. */
236 struct hashnode {
237 struct hashnode *next; /* double links for easy deletion */
238 struct hashnode *prev;
239 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
240 chain is kept, in case the node is the head
241 of the chain and gets deleted. */
242 enum node_type type; /* type of special token */
243 int length; /* length of token, for quick comparison */
244 U_CHAR *name; /* the actual name */
245 union hashval value; /* pointer to expansion, or whatever */
248 typedef struct hashnode HASHNODE;
250 /* Some definitions for the hash table. The hash function MUST be
251 computed as shown in hashf () below. That is because the rescan
252 loop computes the hash value `on the fly' for most tokens,
253 in order to avoid the overhead of a lot of procedure calls to
254 the hashf () function. Hashf () only exists for the sake of
255 politeness, for use when speed isn't so important. */
257 #define HASHSIZE 1403
258 HASHNODE *hashtab[HASHSIZE];
259 #define HASHSTEP(old, c) ((old << 2) + c)
260 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
262 /* `struct directive' defines one #-directive, including how to handle it. */
264 struct directive {
265 int length; /* Length of name */
266 void (*func) PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
267 /* Function to handle directive */
268 const char *name; /* Name of directive */
269 enum node_type type; /* Code which describes which directive. */
272 /* Last arg to output_line_command. */
273 enum file_change_code {same_file, enter_file, leave_file};
275 /* This structure represents one parsed argument in a macro call.
276 `raw' points to the argument text as written (`raw_length' is its length).
277 `expanded' points to the argument's macro-expansion
278 (its length is `expand_length').
279 `stringified_length' is the length the argument would have
280 if stringified.
281 `free1' and `free2', if nonzero, point to blocks to be freed
282 when the macro argument data is no longer needed. */
284 struct argdata {
285 U_CHAR *raw, *expanded;
286 int raw_length, expand_length;
287 int stringified_length;
288 U_CHAR *free1, *free2;
289 char newlines;
290 char comments;
293 /* The arglist structure is built by do_define to tell
294 collect_definition where the argument names begin. That
295 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
296 would contain pointers to the strings x, y, and z.
297 Collect_definition would then build a DEFINITION node,
298 with reflist nodes pointing to the places x, y, and z had
299 appeared. So the arglist is just convenience data passed
300 between these two routines. It is not kept around after
301 the current #define has been processed and entered into the
302 hash table. */
304 struct arglist {
305 struct arglist *next;
306 U_CHAR *name;
307 int length;
308 int argno;
311 /* Function prototypes. */
313 void do_define PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
314 void do_line PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
315 void do_include PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
316 void do_undef PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
317 void do_if PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
318 void do_xifdef PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
319 void do_else PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
320 void do_elif PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
321 void do_endif PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
323 struct hashnode *install PARAMS ((const U_CHAR *, int, enum node_type, int));
324 struct hashnode *lookup PARAMS ((const U_CHAR *, int, int));
325 int hashf PARAMS ((const U_CHAR *, int, int));
326 int compare_defs PARAMS ((DEFINITION *, DEFINITION *));
327 int comp_def_part PARAMS ((int, U_CHAR *, int, U_CHAR *, int, int));
328 void delete_macro PARAMS ((HASHNODE *));
330 /* First arg to v_message. */
331 enum msgtype { WARNING = 0, ERROR, FATAL };
332 void v_message PARAMS ((enum msgtype mtype, int line,
333 const char *msgid, va_list ap));
335 void warning PARAMS ((const char *msgid, ...));
336 void error PARAMS ((const char *msgid, ...));
337 void fatal PARAMS ((const char *msgid, ...)) ATTRIBUTE_NORETURN;
338 void error_with_line PARAMS ((int, const char *msgid, ...));
339 void error_from_errno PARAMS ((const char *msgid));
341 void perror_with_name PARAMS ((const char *msgid));
342 void pfatal_with_name PARAMS ((const char *msgid)) ATTRIBUTE_NORETURN;
343 void fancy_abort PARAMS ((int, const char *)) ATTRIBUTE_NORETURN;
345 int line_for_error PARAMS ((int));
347 /* We know perfectly well which file this is, so we don't need to
348 use __FILE__. */
349 #undef abort
350 #if (GCC_VERSION >= 2007)
351 #define abort() fancy_abort(__LINE__, __FUNCTION__)
352 #else
353 #define abort() fancy_abort(__LINE__, 0);
354 #endif
356 void macroexpand PARAMS ((HASHNODE *, FILE_BUF *));
357 void special_symbol PARAMS ((HASHNODE *, FILE_BUF *));
358 void dump_all_macros PARAMS ((void));
359 void dump_defn_1 PARAMS ((U_CHAR *, int, int));
360 void dump_arg_n PARAMS ((DEFINITION *, int));
361 void conditional_skip PARAMS ((FILE_BUF *, int, enum node_type));
362 void skip_if_group PARAMS ((FILE_BUF *, int));
363 void output_line_command PARAMS ((FILE_BUF *, FILE_BUF *,
364 int, enum file_change_code));
366 int eval_if_expression PARAMS ((U_CHAR *, int));
367 int parse_c_expression PARAMS ((char *)); /* in tradcif.y */
369 void initialize_char_syntax PARAMS ((void));
370 void initialize_builtins PARAMS ((void));
371 void make_definition PARAMS ((U_CHAR *));
372 void make_undef PARAMS ((U_CHAR *));
374 void grow_outbuf PARAMS ((FILE_BUF *, int));
375 int handle_directive PARAMS ((FILE_BUF *, FILE_BUF *));
376 void finclude PARAMS ((int, const char *, FILE_BUF *));
377 void deps_output PARAMS ((const char *, int));
378 void rescan PARAMS ((FILE_BUF *, int));
379 void newline_fix PARAMS ((U_CHAR *));
380 void name_newline_fix PARAMS ((U_CHAR *));
381 U_CHAR *macarg1 PARAMS ((U_CHAR *, U_CHAR *, int *, int *, int *));
382 const char *macarg PARAMS ((struct argdata *));
383 int discard_comments PARAMS ((U_CHAR *, int, int));
384 int file_size_and_mode PARAMS ((int, int *, long *));
386 U_CHAR *skip_to_end_of_comment PARAMS ((FILE_BUF *, int *));
387 U_CHAR *skip_quoted_string PARAMS ((U_CHAR *, U_CHAR *, int,
388 int *, int *, int *));
390 void pipe_closed PARAMS ((int));
391 int main PARAMS ((int, char **));
393 /* Convenience. Write U"string" to get an unsigned string constant. */
394 #define U (const unsigned char *)
396 /* Here is the actual list of #-directives, most-often-used first. */
398 struct directive directive_table[] = {
399 { 6, do_define, "define", T_DEFINE },
400 { 7, do_include, "include", T_INCLUDE },
401 { 5, do_endif, "endif", T_ENDIF },
402 { 5, do_xifdef, "ifdef", T_IFDEF },
403 { 2, do_if, "if", T_IF, },
404 { 4, do_else, "else", T_ELSE },
405 { 6, do_xifdef, "ifndef", T_IFNDEF },
406 { 5, do_undef, "undef", T_UNDEF },
407 { 4, do_line, "line", T_LINE },
408 { 4, do_elif, "elif", T_ELIF },
409 { -1, 0, "", T_UNUSED},
412 /* table to tell if char can be part of a C identifier. */
413 U_CHAR is_idchar[256];
414 /* table to tell if char can be first char of a c identifier. */
415 U_CHAR is_idstart[256];
416 /* table to tell if c is horizontal space. */
417 U_CHAR is_hor_space[256];
418 /* table to tell if c is horizontal or vertical space. */
419 U_CHAR is_space[256];
421 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
422 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
424 int errors = 0; /* Error counter for exit code */
426 FILE_BUF expand_to_temp_buffer PARAMS ((U_CHAR *, U_CHAR *, int));
427 DEFINITION *collect_expansion PARAMS ((U_CHAR *, U_CHAR *, int,
428 struct arglist *));
430 /* Stack of conditionals currently in progress
431 (including both successful and failing conditionals). */
433 struct if_stack {
434 struct if_stack *next; /* for chaining to the next stack frame */
435 const char *fname; /* copied from input when frame is made */
436 int lineno; /* similarly */
437 int if_succeeded; /* true if a leg of this if-group
438 has been passed through rescan */
439 enum node_type type; /* type of last directive seen in this group */
441 typedef struct if_stack IF_STACK_FRAME;
442 IF_STACK_FRAME *if_stack = NULL;
444 /* Buffer of -M output. */
446 char *deps_buffer;
448 /* Number of bytes allocated in above. */
449 int deps_allocated_size;
451 /* Number of bytes used. */
452 int deps_size;
454 /* Number of bytes since the last newline. */
455 int deps_column;
457 /* Nonzero means -I- has been seen,
458 so don't look for #include "foo" the source-file directory. */
459 int ignore_srcdir;
461 /* Handler for SIGPIPE. */
463 void
464 pipe_closed (dummy)
465 int dummy ATTRIBUTE_UNUSED;
467 exit (FATAL_EXIT_CODE);
471 main (argc, argv)
472 int argc;
473 char **argv;
475 int st_mode;
476 long st_size;
477 const char *in_fname, *out_fname;
478 int f, i;
479 FILE_BUF *fp;
480 const char **pend_files = (const char **) xmalloc (argc * sizeof (char *));
481 const char **pend_defs = (const char **) xmalloc (argc * sizeof (char *));
482 const char **pend_undefs = (const char **) xmalloc (argc * sizeof (char *));
483 int no_standard_includes = 0;
485 /* Non-0 means don't output the preprocessed program. */
486 int inhibit_output = 0;
488 /* Stream on which to print the dependency information. */
489 FILE *deps_stream = 0;
490 /* Target-name to write with the dependency information. */
491 char *deps_target = 0;
493 #ifdef RLIMIT_STACK
494 /* Get rid of any avoidable limit on stack size. */
496 struct rlimit rlim;
498 /* Set the stack limit huge so that alloca (particularly stringtab
499 * in dbxread.c) does not fail. */
500 getrlimit (RLIMIT_STACK, &rlim);
501 rlim.rlim_cur = rlim.rlim_max;
502 setrlimit (RLIMIT_STACK, &rlim);
504 #endif /* RLIMIT_STACK defined */
506 progname = argv[0];
508 in_fname = NULL;
509 out_fname = NULL;
511 /* Initialize is_idchar to allow $. */
512 initialize_char_syntax ();
514 no_line_commands = 0;
515 dump_macros = 0;
516 no_output = 0;
518 signal (SIGPIPE, pipe_closed);
520 max_include_len = cpp_GCC_INCLUDE_DIR_len + 7; /* ??? */
522 memset (pend_files, 0, argc * sizeof (char *));
523 memset (pend_defs, 0, argc * sizeof (char *));
524 memset (pend_undefs, 0, argc * sizeof (char *));
526 /* Process switches and find input file name. */
528 for (i = 1; i < argc; i++) {
529 if (argv[i][0] != '-') {
530 if (out_fname != NULL)
531 fatal ("Usage: %s [switches] input output", argv[0]);
532 else if (in_fname != NULL)
533 out_fname = argv[i];
534 else
535 in_fname = argv[i];
536 } else {
537 switch (argv[i][1]) {
538 case 'A':
539 case 'E':
540 case '$':
541 case 'g':
542 break; /* Ignore for compatibility with ISO/extended cpp. */
544 case 'l':
545 if (!strcmp (argv[i], "-lang-c++")
546 || !strcmp (argv[i], "-lang-objc++"))
547 fatal ("-traditional is not supported in C++");
548 else if (!strcmp (argv[i], "-lang-c89"))
549 fatal ("-traditional and -ansi are mutually exclusive");
550 else if (!strcmp (argv[i], "-lang-objc"))
551 pend_defs[i] = "__OBJC__";
552 else if (!strcmp (argv[i], "-lang-asm"))
553 pend_defs[i] = "__ASSEMBLER__";
554 else if (!strcmp (argv[i], "-lang-fortran"))
555 pend_defs[i] = "_LANGUAGE_FORTRAN";
556 /* All other possibilities ignored. */
557 break;
559 case 'i':
560 if (!strcmp (argv[i], "-include"))
562 if (i + 1 == argc)
563 fatal ("Filename missing after -i option");
564 else
565 pend_files[i] = argv[i+1], i++;
567 else if (!strcmp (argv[i], "-iprefix"))
568 i++; /* Ignore for compatibility */
569 else if (!strcmp (argv[i], "-isystem")
570 || !strcmp (argv[i], "-iwithprefix")
571 || !strcmp (argv[i], "-iwithprefixbefore")
572 || !strcmp (argv[i], "-idirafter"))
573 goto include; /* best we can do */
575 break;
577 case 'o':
578 if (out_fname != NULL)
579 fatal ("Output filename specified twice");
580 if (i + 1 == argc)
581 fatal ("Filename missing after -o option");
582 out_fname = argv[++i];
583 if (!strcmp (out_fname, "-"))
584 out_fname = "";
585 break;
587 case 'w':
588 inhibit_warnings = 1;
589 break;
591 case 'W':
592 if (!strcmp (argv[i], "-Wcomments"))
593 warn_comments = 1;
594 else if (!strcmp (argv[i], "-Wcomment"))
595 warn_comments = 1;
596 else if (!strcmp (argv[i], "-Wall")) {
597 warn_comments = 1;
599 break;
601 case 'f':
602 if (!strcmp (argv[i], "-fleading-underscore"))
603 user_label_prefix = "_";
604 else if (!strcmp (argv[i], "-fno-leading-underscore"))
605 user_label_prefix = "";
606 break;
608 case 'M':
609 if (!strcmp (argv[i], "-M"))
610 print_deps = 2;
611 else if (!strcmp (argv[i], "-MM"))
612 print_deps = 1;
613 inhibit_output = 1;
614 break;
616 case 'd':
617 dump_macros = 1;
618 no_output = 1;
619 break;
621 case 'v':
622 fprintf (stderr, "GNU traditional CPP version %s\n", version_string);
623 break;
625 case 'D':
627 char *p, *p1;
629 if (argv[i][2] != 0)
630 p = argv[i] + 2;
631 else if (i + 1 == argc)
632 fatal ("Macro name missing after -D option");
633 else
634 p = argv[++i];
636 if ((p1 = (char *) strchr (p, '=')) != NULL)
637 *p1 = ' ';
638 pend_defs[i] = p;
640 break;
642 case 'U': /* JF #undef something */
643 if (argv[i][2] != 0)
644 pend_undefs[i] = argv[i] + 2;
645 else if (i + 1 == argc)
646 fatal ("Macro name missing after -U option");
647 else
648 pend_undefs[i] = argv[i+1], i++;
649 break;
651 case 'C':
652 put_out_comments = 1;
653 break;
655 case 'p':
656 if (!strcmp (argv[i], "-pedantic"))
657 fatal ("-pedantic and -traditional are mutually exclusive");
658 break;
660 case 't':
661 if (!strcmp (argv[i], "-trigraphs"))
662 fatal ("-trigraphs and -traditional are mutually exclusive");
663 break;
665 case 'P':
666 no_line_commands = 1;
667 break;
669 case 'I': /* Add directory to path for includes. */
670 include:
672 struct file_name_list *dirtmp;
674 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-"))
675 ignore_srcdir = 1;
676 else {
677 dirtmp = (struct file_name_list *)
678 xmalloc (sizeof (struct file_name_list));
679 dirtmp->next = 0; /* New one goes on the end */
680 if (include == 0)
681 include = dirtmp;
682 else
683 last_include->next = dirtmp;
684 last_include = dirtmp; /* Tail follows the last one */
685 if (argv[i][1] == 'I' && argv[i][2] != 0)
686 dirtmp->fname = argv[i] + 2;
687 else if (i + 1 == argc)
688 fatal ("Directory name missing after -I option");
689 else
690 dirtmp->fname = argv[++i];
691 if (strlen (dirtmp->fname) > max_include_len)
692 max_include_len = strlen (dirtmp->fname);
693 if (ignore_srcdir && first_bracket_include == 0)
694 first_bracket_include = dirtmp;
697 break;
699 case 'n':
700 /* -nostdinc causes no default include directories.
701 You must specify all include-file directories with -I. */
702 no_standard_includes = 1;
703 break;
705 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
706 if (in_fname == NULL) {
707 in_fname = "";
708 break;
709 } else if (out_fname == NULL) {
710 out_fname = "";
711 break;
712 } /* else fall through into error */
714 default:
715 fatal ("Invalid option `%s'", argv[i]);
720 if (user_label_prefix == 0)
721 user_label_prefix = USER_LABEL_PREFIX;
723 /* Initialize is_idchar. */
724 initialize_char_syntax ();
726 /* Install __LINE__, etc. Must follow initialize_char_syntax
727 and option processing. */
728 initialize_builtins ();
730 /* Do defines specified with -D. */
731 for (i = 1; i < argc; i++)
732 if (pend_defs[i])
733 make_definition ((U_CHAR *)pend_defs[i]);
735 /* Do undefines specified with -U. */
736 for (i = 1; i < argc; i++)
737 if (pend_undefs[i])
738 make_undef ((U_CHAR *)pend_undefs[i]);
740 /* Unless -fnostdinc,
741 tack on the standard include file dirs to the specified list */
742 if (!no_standard_includes) {
743 const struct default_include *di;
744 struct file_name_list *old_last_include = last_include;
745 struct file_name_list *dirtmp;
746 for (di = cpp_include_defaults; di->fname; di++) {
747 if (di->cplusplus)
748 continue;
749 dirtmp = (struct file_name_list *)
750 xmalloc (sizeof (struct file_name_list));
751 dirtmp->next = 0; /* New one goes on the end */
752 if (include == 0)
753 include = dirtmp;
754 else
755 last_include->next = dirtmp;
756 last_include = dirtmp; /* Tail follows the last one */
757 dirtmp->fname = di->fname;
760 if (ignore_srcdir && first_bracket_include == 0)
761 first_bracket_include = old_last_include->next;
764 /* Initialize output buffer */
766 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
767 outbuf.bufp = outbuf.buf;
768 outbuf.length = OUTBUF_SIZE;
770 /* Scan the -i files before the main input.
771 Much like #including them, but with no_output set
772 so that only their macro definitions matter. */
774 no_output++;
775 for (i = 1; i < argc; i++)
776 if (pend_files[i]) {
777 int fd = open (pend_files[i], O_RDONLY, 0666);
778 if (fd < 0) {
779 perror_with_name (pend_files[i]);
780 return FATAL_EXIT_CODE;
782 finclude (fd, pend_files[i], &outbuf);
784 no_output--;
786 /* Create an input stack level for the main input file
787 and copy the entire contents of the file into it. */
789 fp = &instack[++indepth];
791 /* JF check for stdin */
792 if (in_fname == NULL || *in_fname == 0) {
793 in_fname = "";
794 f = 0;
795 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
796 goto perror;
798 /* Either of two environment variables can specify output of deps.
799 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
800 where OUTPUT_FILE is the file to write deps info to
801 and DEPS_TARGET is the target to mention in the deps. */
803 if (print_deps == 0
804 && (getenv ("SUNPRO_DEPENDENCIES") != 0
805 || getenv ("DEPENDENCIES_OUTPUT") != 0))
807 char *spec = getenv ("DEPENDENCIES_OUTPUT");
808 char *s;
809 char *output_file;
811 if (spec == 0)
813 spec = getenv ("SUNPRO_DEPENDENCIES");
814 print_deps = 2;
816 else
817 print_deps = 1;
819 /* Find the space before the DEPS_TARGET, if there is one. */
820 s = strchr (spec, ' ');
821 if (s)
823 deps_target = s + 1;
824 output_file = (char *) xmalloc (s - spec + 1);
825 memcpy (output_file, spec, s - spec);
826 output_file[s - spec] = 0;
828 else
830 deps_target = 0;
831 output_file = spec;
834 deps_stream = fopen (output_file, "a");
835 if (deps_stream == 0)
836 pfatal_with_name (output_file);
838 /* If the -M option was used, output the deps to standard output. */
839 else if (print_deps)
840 deps_stream = stdout;
842 /* For -M, print the expected object file name
843 as the target of this Make-rule. */
844 if (print_deps) {
845 deps_allocated_size = 200;
846 deps_buffer = (char *) xmalloc (deps_allocated_size);
847 deps_buffer[0] = 0;
848 deps_size = 0;
849 deps_column = 0;
851 if (deps_target) {
852 deps_output (deps_target, 0);
853 deps_output (":", 0);
854 } else if (*in_fname == 0)
855 deps_output ("-: ", 0);
856 else {
857 int len;
858 const char *p = in_fname;
859 const char *p1 = p;
860 /* Discard all directory prefixes from P. */
861 while (*p1) {
862 if (*p1 == '/')
863 p = p1 + 1;
864 p1++;
866 /* Output P, but remove known suffixes. */
867 len = strlen (p);
868 if (p[len - 2] == '.'
869 && (p[len - 1] == 'c' || p[len - 1] == 'C' || p[len - 1] == 'S'))
870 deps_output (p, len - 2);
871 else if (p[len - 3] == '.'
872 && p[len - 2] == 'c'
873 && p[len - 1] == 'c')
874 deps_output (p, len - 3);
875 else
876 deps_output (p, 0);
877 /* Supply our own suffix. */
878 deps_output (".o : ", 0);
879 deps_output (in_fname, 0);
880 deps_output (" ", 0);
884 if (file_size_and_mode (f, &st_mode, &st_size))
885 goto perror;
886 fp->fname = in_fname;
887 fp->lineno = 1;
888 /* JF all this is mine about reading pipes and ttys */
889 if (!S_ISREG (st_mode)) {
890 /* Read input from a file that is not a normal disk file.
891 We cannot preallocate a buffer with the correct size,
892 so we must read in the file a piece at the time and make it bigger. */
893 int size;
894 int bsize;
895 int cnt;
896 U_CHAR *bufp;
898 bsize = 2000;
899 size = 0;
900 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
901 bufp = fp->buf;
902 for (;;) {
903 cnt = read (f, bufp, bsize - size);
904 if (cnt < 0) goto perror; /* error! */
905 if (cnt == 0) break; /* End of file */
906 size += cnt;
907 bufp += cnt;
908 if (bsize == size) { /* Buffer is full! */
909 bsize *= 2;
910 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
911 bufp = fp->buf + size; /* May have moved */
914 fp->length = size;
915 } else {
916 /* Read a file whose size we can determine in advance.
917 For the sake of VMS, st_size is just an upper bound. */
918 long i;
919 fp->length = 0;
920 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
922 while (st_size > 0) {
923 i = read (f, fp->buf + fp->length, st_size);
924 if (i <= 0) {
925 if (i == 0) break;
926 goto perror;
928 fp->length += i;
929 st_size -= i;
932 fp->bufp = fp->buf;
933 fp->if_stack = if_stack;
935 /* Make sure data ends with a newline. And put a null after it. */
937 if (fp->length > 0 && fp->buf[fp->length-1] != '\n')
938 fp->buf[fp->length++] = '\n';
939 fp->buf[fp->length] = '\0';
941 /* Now that we know the input file is valid, open the output. */
943 if (!out_fname || !strcmp (out_fname, ""))
944 out_fname = "stdout";
945 else if (! freopen (out_fname, "w", stdout))
946 pfatal_with_name (out_fname);
948 output_line_command (fp, &outbuf, 0, same_file);
950 /* Scan the input, processing macros and directives. */
952 rescan (&outbuf, 0);
954 /* Now we have processed the entire input
955 Write whichever kind of output has been requested. */
958 if (dump_macros)
959 dump_all_macros ();
960 else if (! inhibit_output && deps_stream != stdout) {
961 if (write (fileno (stdout), outbuf.buf, outbuf.bufp - outbuf.buf) < 0)
962 fatal ("I/O error on output");
965 if (print_deps) {
966 fputs (deps_buffer, deps_stream);
967 putc ('\n', deps_stream);
968 if (deps_stream != stdout) {
969 fclose (deps_stream);
970 if (ferror (deps_stream))
971 fatal ("I/O error on output");
975 if (ferror (stdout))
976 fatal ("I/O error on output");
978 if (errors)
979 exit (FATAL_EXIT_CODE);
980 exit (SUCCESS_EXIT_CODE);
982 perror:
983 pfatal_with_name (in_fname);
986 /* Move all backslash-newline pairs out of embarrassing places.
987 Exchange all such pairs following BP
988 with any potentially-embarrasing characters that follow them.
989 Potentially-embarrassing characters are / and *
990 (because a backslash-newline inside a comment delimiter
991 would cause it not to be recognized). */
992 void
993 newline_fix (bp)
994 U_CHAR *bp;
996 register U_CHAR *p = bp;
997 register int count = 0;
999 /* First count the backslash-newline pairs here. */
1001 while (*p++ == '\\' && *p++ == '\n')
1002 count++;
1004 p = bp + count * 2;
1006 /* Exit if what follows the backslash-newlines is not embarrassing. */
1008 if (count == 0 || (*p != '/' && *p != '*'))
1009 return;
1011 /* Copy all potentially embarrassing characters
1012 that follow the backslash-newline pairs
1013 down to where the pairs originally started. */
1015 while (*p == '*' || *p == '/')
1016 *bp++ = *p++;
1018 /* Now write the same number of pairs after the embarrassing chars. */
1019 while (count-- > 0) {
1020 *bp++ = '\\';
1021 *bp++ = '\n';
1025 /* Like newline_fix but for use within a directive-name.
1026 Move any backslash-newlines up past any following symbol constituents. */
1027 void
1028 name_newline_fix (bp)
1029 U_CHAR *bp;
1031 register U_CHAR *p = bp;
1032 register int count = 0;
1034 /* First count the backslash-newline pairs here. */
1036 while (*p++ == '\\' && *p++ == '\n')
1037 count++;
1039 p = bp + count * 2;
1041 /* What follows the backslash-newlines is not embarrassing. */
1043 if (count == 0 || !is_idchar[*p])
1044 return;
1046 /* Copy all potentially embarrassing characters
1047 that follow the backslash-newline pairs
1048 down to where the pairs originally started. */
1050 while (is_idchar[*p])
1051 *bp++ = *p++;
1053 /* Now write the same number of pairs after the embarrassing chars. */
1054 while (count-- > 0) {
1055 *bp++ = '\\';
1056 *bp++ = '\n';
1061 * The main loop of the program.
1063 * Read characters from the input stack, transferring them to the
1064 * output buffer OP.
1066 * Macros are expanded and push levels on the input stack.
1067 * At the end of such a level it is popped off and we keep reading.
1068 * At the end of any other kind of level, we return.
1069 * #-directives are handled, except within macros.
1071 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
1072 * and insert them when appropriate. This is set while scanning macro
1073 * arguments before substitution. It is zero when scanning for final output.
1074 * There are three types of Newline markers:
1075 * * Newline - follows a macro name that was not expanded
1076 * because it appeared inside an expansion of the same macro.
1077 * This marker prevents future expansion of that identifier.
1078 * When the input is rescanned into the final output, these are deleted.
1079 * These are also deleted by ## concatenation.
1080 * * Newline Space (or Newline and any other whitespace character)
1081 * stands for a place that tokens must be separated or whitespace
1082 * is otherwise desirable, but where the ANSI standard specifies there
1083 * is no whitespace. This marker turns into a Space (or whichever other
1084 * whitespace char appears in the marker) in the final output,
1085 * but it turns into nothing in an argument that is stringified with #.
1086 * Such stringified arguments are the only place where the ANSI standard
1087 * specifies with precision that whitespace may not appear.
1089 * During this function, IP->bufp is kept cached in IBP for speed of access.
1090 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
1091 * IBP, IP and OBP must be copied back to memory. IP and IBP are
1092 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
1093 * explicitly, and before RECACHE, since RECACHE uses OBP.
1096 void
1097 rescan (op, output_marks)
1098 FILE_BUF *op;
1099 int output_marks;
1101 /* Character being scanned in main loop. */
1102 register U_CHAR c;
1104 /* Length of pending accumulated identifier. */
1105 register int ident_length = 0;
1107 /* Hash code of pending accumulated identifier. */
1108 register int hash = 0;
1110 /* Current input level (&instack[indepth]). */
1111 FILE_BUF *ip;
1113 /* Pointer for scanning input. */
1114 register U_CHAR *ibp;
1116 /* Pointer to end of input. End of scan is controlled by LIMIT. */
1117 register U_CHAR *limit;
1119 /* Pointer for storing output. */
1120 register U_CHAR *obp;
1122 /* REDO_CHAR is nonzero if we are processing an identifier
1123 after backing up over the terminating character.
1124 Sometimes we process an identifier without backing up over
1125 the terminating character, if the terminating character
1126 is not special. Backing up is done so that the terminating character
1127 will be dispatched on again once the identifier is dealt with. */
1128 int redo_char = 0;
1130 /* 1 if within an identifier inside of which a concatenation
1131 marker (Newline -) has been seen. */
1132 int concatenated = 0;
1134 /* While scanning a comment or a string constant,
1135 this records the line it started on, for error messages. */
1136 int start_line;
1138 /* Record position of last `real' newline. */
1139 U_CHAR *beg_of_line;
1141 /* Pop the innermost input stack level, assuming it is a macro expansion. */
1143 #define POPMACRO \
1144 do { ip->macro->type = T_MACRO; \
1145 if (ip->free_ptr) free (ip->free_ptr); \
1146 --indepth; } while (0)
1148 /* Reload `rescan's local variables that describe the current
1149 level of the input stack. */
1151 #define RECACHE \
1152 do { ip = &instack[indepth]; \
1153 ibp = ip->bufp; \
1154 limit = ip->buf + ip->length; \
1155 op->bufp = obp; \
1156 check_expand (op, limit - ibp); \
1157 beg_of_line = 0; \
1158 obp = op->bufp; } while (0)
1160 if (no_output && instack[indepth].fname != 0)
1161 skip_if_group (&instack[indepth], 1);
1163 obp = op->bufp;
1164 RECACHE;
1165 beg_of_line = ibp;
1167 /* Our caller must always put a null after the end of
1168 the input at each input stack level. */
1169 if (*limit != 0)
1170 abort ();
1172 while (1) {
1173 c = *ibp++;
1174 *obp++ = c;
1176 switch (c) {
1177 case '\\':
1178 if (ibp >= limit)
1179 break;
1180 if (*ibp == '\n') {
1181 /* Always merge lines ending with backslash-newline,
1182 even in middle of identifier. */
1183 ++ibp;
1184 ++ip->lineno;
1185 --obp; /* remove backslash from obuf */
1186 break;
1188 /* Otherwise, backslash suppresses specialness of following char,
1189 so copy it here to prevent the switch from seeing it.
1190 But first get any pending identifier processed. */
1191 if (ident_length > 0)
1192 goto specialchar;
1193 *obp++ = *ibp++;
1194 break;
1196 case '#':
1197 /* If this is expanding a macro definition, don't recognize
1198 preprocessor directives. */
1199 if (ip->macro != 0)
1200 goto randomchar;
1201 if (ident_length)
1202 goto specialchar;
1204 /* # keyword: a # must be first nonblank char on the line */
1205 if (beg_of_line == 0)
1206 goto randomchar;
1208 U_CHAR *bp;
1210 /* Scan from start of line, skipping whitespace, comments
1211 and backslash-newlines, and see if we reach this #.
1212 If not, this # is not special. */
1213 bp = beg_of_line;
1214 while (1) {
1215 if (is_hor_space[*bp])
1216 bp++;
1217 else if (*bp == '\\' && bp[1] == '\n')
1218 bp += 2;
1219 else if (*bp == '/' && (newline_fix (bp + 1), bp[1]) == '*') {
1220 bp += 2;
1221 while (!(*bp == '*' && (newline_fix (bp + 1), bp[1]) == '/'))
1222 bp++;
1223 bp += 1;
1225 else break;
1227 if (bp + 1 != ibp)
1228 goto randomchar;
1231 /* This # can start a directive. */
1233 --obp; /* Don't copy the '#' */
1235 ip->bufp = ibp;
1236 op->bufp = obp;
1237 if (! handle_directive (ip, op)) {
1238 #ifdef USE_C_ALLOCA
1239 alloca (0);
1240 #endif
1241 /* Not a known directive: treat it as ordinary text.
1242 IP, OP, IBP, etc. have not been changed. */
1243 if (no_output && instack[indepth].fname) {
1244 /* If not generating expanded output,
1245 what we do with ordinary text is skip it.
1246 Discard everything until next # directive. */
1247 skip_if_group (&instack[indepth], 1);
1248 RECACHE;
1249 beg_of_line = ibp;
1250 break;
1252 ++obp; /* Copy the '#' after all */
1253 goto randomchar;
1255 #ifdef USE_C_ALLOCA
1256 alloca (0);
1257 #endif
1258 /* A # directive has been successfully processed. */
1259 /* If not generating expanded output, ignore everything until
1260 next # directive. */
1261 if (no_output && instack[indepth].fname)
1262 skip_if_group (&instack[indepth], 1);
1263 obp = op->bufp;
1264 RECACHE;
1265 beg_of_line = ibp;
1266 break;
1268 case '\"': /* skip quoted string */
1269 case '\'':
1270 /* A single quoted string is treated like a double -- some
1271 programs (e.g., troff) are perverse this way */
1273 if (ident_length)
1274 goto specialchar;
1276 start_line = ip->lineno;
1278 /* Skip ahead to a matching quote. */
1280 while (1) {
1281 if (ibp >= limit) {
1282 if (ip->macro != 0) {
1283 /* try harder: this string crosses a macro expansion boundary */
1284 POPMACRO;
1285 RECACHE;
1286 continue;
1288 break;
1290 *obp++ = *ibp;
1291 switch (*ibp++) {
1292 case '\n':
1293 ++ip->lineno;
1294 ++op->lineno;
1295 /* Traditionally, end of line ends a string constant with no error.
1296 So exit the loop and record the new line. */
1297 beg_of_line = ibp;
1298 goto while2end;
1300 case '\\':
1301 if (ibp >= limit)
1302 break;
1303 if (*ibp == '\n') {
1304 /* Backslash newline is replaced by nothing at all,
1305 but keep the line counts correct. */
1306 --obp;
1307 ++ibp;
1308 ++ip->lineno;
1309 } else {
1310 /* ANSI stupidly requires that in \\ the second \
1311 is *not* prevented from combining with a newline. */
1312 while (*ibp == '\\' && ibp[1] == '\n') {
1313 ibp += 2;
1314 ++ip->lineno;
1316 *obp++ = *ibp++;
1318 break;
1320 case '\"':
1321 case '\'':
1322 if (ibp[-1] == c)
1323 goto while2end;
1324 break;
1327 while2end:
1328 break;
1330 case '/':
1331 if (*ibp == '\\' && ibp[1] == '\n')
1332 newline_fix (ibp);
1333 /* Don't look for comments inside a macro definition. */
1334 if (ip->macro != 0)
1335 goto randomchar;
1336 /* A comment constitutes white space, so it can terminate an identifier.
1337 Process the identifier, if any. */
1338 if (ident_length)
1339 goto specialchar;
1341 if (*ibp != '*')
1342 goto randomchar;
1344 /* We have a comment. Skip it, optionally copying it to output. */
1346 start_line = ip->lineno;
1348 ++ibp; /* Skip the star. */
1350 /* In K+R C, a comment is equivalent to nothing. Note that we
1351 already output the slash; we might not want it. */
1352 if (! put_out_comments)
1353 obp--;
1354 else
1355 *obp++ = '*';
1358 U_CHAR *before_bp = ibp;
1360 while (ibp < limit) {
1361 switch (*ibp++) {
1362 case '/':
1363 if (warn_comments && ibp < limit && *ibp == '*')
1364 warning("`/*' within comment");
1365 break;
1366 case '*':
1367 if (*ibp == '\\' && ibp[1] == '\n')
1368 newline_fix (ibp);
1369 if (ibp >= limit || *ibp == '/')
1370 goto comment_end;
1371 break;
1372 case '\n':
1373 ++ip->lineno;
1374 /* Copy the newline into the output buffer, in order to
1375 avoid the pain of a #line every time a multiline comment
1376 is seen. */
1377 if (!put_out_comments)
1378 *obp++ = '\n';
1379 ++op->lineno;
1382 comment_end:
1384 if (ibp >= limit)
1385 error_with_line (line_for_error (start_line),
1386 "unterminated comment");
1387 else {
1388 ibp++;
1389 if (put_out_comments) {
1390 memcpy (obp, before_bp, ibp - before_bp);
1391 obp += ibp - before_bp;
1395 break;
1397 case '0': case '1': case '2': case '3': case '4':
1398 case '5': case '6': case '7': case '8': case '9':
1399 /* If digit is not part of identifier, it starts a number,
1400 which means that following letters are not an identifier.
1401 "0x5" does not refer to an identifier "x5".
1402 So copy all alphanumerics that follow without accumulating
1403 as an identifier. Periods also, for sake of "3.e7". */
1405 if (ident_length == 0) {
1406 while (ibp < limit) {
1407 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
1408 ++ip->lineno;
1409 ibp += 2;
1411 c = *ibp++;
1412 if (!isalnum (c) && c != '.' && c != '_') {
1413 --ibp;
1414 break;
1416 *obp++ = c;
1417 /* A sign can be part of a preprocessing number
1418 if it follows an e. */
1419 if (c == 'e' || c == 'E') {
1420 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
1421 ++ip->lineno;
1422 ibp += 2;
1424 if (ibp < limit && (*ibp == '+' || *ibp == '-')) {
1425 *obp++ = *ibp++;
1426 /* Traditional C does not let the token go past the sign. */
1427 break;
1431 break;
1433 /* fall through */
1435 case '_':
1436 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1437 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1438 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
1439 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
1440 case 'y': case 'z':
1441 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1442 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
1443 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
1444 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1445 case 'Y': case 'Z':
1446 ident_length++;
1447 /* Compute step of hash function, to avoid a proc call on every token */
1448 hash = HASHSTEP (hash, c);
1449 break;
1451 case '\n':
1452 /* If reprocessing a macro expansion, newline is a special marker. */
1453 if (ip->macro != 0) {
1454 /* Newline White is a "funny space" to separate tokens that are
1455 supposed to be separate but without space between.
1456 Here White means any horizontal whitespace character.
1457 Newline - marks a recursive macro use that is not
1458 supposed to be expandable. */
1460 if (*ibp == '-') {
1461 /* Newline - inhibits expansion of preceding token.
1462 If expanding a macro arg, we keep the newline -.
1463 In final output, it is deleted. */
1464 if (! concatenated) {
1465 ident_length = 0;
1466 hash = 0;
1468 ibp++;
1469 if (!output_marks) {
1470 obp--;
1471 } else {
1472 /* If expanding a macro arg, keep the newline -. */
1473 *obp++ = '-';
1475 } else if (is_space[*ibp]) {
1476 /* Newline Space does not prevent expansion of preceding token
1477 so expand the preceding token and then come back. */
1478 if (ident_length > 0)
1479 goto specialchar;
1481 /* If generating final output, newline space makes a space. */
1482 if (!output_marks) {
1483 obp[-1] = *ibp++;
1484 /* And Newline Newline makes a newline, so count it. */
1485 if (obp[-1] == '\n')
1486 op->lineno++;
1487 } else {
1488 /* If expanding a macro arg, keep the newline space.
1489 If the arg gets stringified, newline space makes nothing. */
1490 *obp++ = *ibp++;
1492 } else abort (); /* Newline followed by something random? */
1493 break;
1496 /* If there is a pending identifier, handle it and come back here. */
1497 if (ident_length > 0)
1498 goto specialchar;
1500 beg_of_line = ibp;
1502 /* Update the line counts and output a #line if necessary. */
1503 ++ip->lineno;
1504 ++op->lineno;
1505 if (ip->lineno != op->lineno) {
1506 op->bufp = obp;
1507 output_line_command (ip, op, 1, same_file);
1508 check_expand (op, ip->length - (ip->bufp - ip->buf));
1509 obp = op->bufp;
1511 break;
1513 /* Come here either after (1) a null character that is part of the input
1514 or (2) at the end of the input, because there is a null there. */
1515 case 0:
1516 if (ibp <= limit)
1517 /* Our input really contains a null character. */
1518 goto randomchar;
1520 /* At end of a macro-expansion level, pop it and read next level. */
1521 if (ip->macro != 0) {
1522 obp--;
1523 ibp--;
1524 /* If we have an identifier that ends here, process it now, so
1525 we get the right error for recursion. */
1526 if (ident_length && ! is_idchar[*instack[indepth - 1].bufp]) {
1527 redo_char = 1;
1528 goto randomchar;
1530 POPMACRO;
1531 RECACHE;
1532 break;
1535 /* If we don't have a pending identifier,
1536 return at end of input. */
1537 if (ident_length == 0) {
1538 obp--;
1539 ibp--;
1540 op->bufp = obp;
1541 ip->bufp = ibp;
1542 goto ending;
1545 /* If we do have a pending identifier, just consider this null
1546 a special character and arrange to dispatch on it again.
1547 The second time, IDENT_LENGTH will be zero so we will return. */
1549 /* Fall through */
1551 specialchar:
1553 /* Handle the case of a character such as /, ', " or null
1554 seen following an identifier. Back over it so that
1555 after the identifier is processed the special char
1556 will be dispatched on again. */
1558 ibp--;
1559 obp--;
1560 redo_char = 1;
1562 default:
1564 randomchar:
1566 if (ident_length > 0) {
1567 register HASHNODE *hp;
1569 /* We have just seen an identifier end. If it's a macro, expand it.
1571 IDENT_LENGTH is the length of the identifier
1572 and HASH is its hash code.
1574 The identifier has already been copied to the output,
1575 so if it is a macro we must remove it.
1577 If REDO_CHAR is 0, the char that terminated the identifier
1578 has been skipped in the output and the input.
1579 OBP-IDENT_LENGTH-1 points to the identifier.
1580 If the identifier is a macro, we must back over the terminator.
1582 If REDO_CHAR is 1, the terminating char has already been
1583 backed over. OBP-IDENT_LENGTH points to the identifier. */
1585 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
1586 hp = hp->next) {
1588 if (hp->length == ident_length) {
1589 U_CHAR *obufp_before_macroname;
1590 int op_lineno_before_macroname;
1591 register int i = ident_length;
1592 register U_CHAR *p = hp->name;
1593 register U_CHAR *q = obp - i;
1595 if (! redo_char)
1596 q--;
1598 do { /* All this to avoid a strncmp () */
1599 if (*p++ != *q++)
1600 goto hashcollision;
1601 } while (--i);
1603 /* We found a use of a macro name.
1604 see if the context shows it is a macro call. */
1606 /* Back up over terminating character if not already done. */
1607 if (! redo_char) {
1608 ibp--;
1609 obp--;
1612 obufp_before_macroname = obp - ident_length;
1613 op_lineno_before_macroname = op->lineno;
1615 /* If macro wants an arglist, verify that a '(' follows.
1616 first skip all whitespace, copying it to the output
1617 after the macro name. Then, if there is no '(',
1618 decide this is not a macro call and leave things that way. */
1619 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
1621 while (1) {
1622 /* Scan forward over whitespace, copying it to the output. */
1623 if (ibp == limit && ip->macro != 0) {
1624 POPMACRO;
1625 RECACHE;
1627 /* A comment: copy it unchanged or discard it. */
1628 else if (*ibp == '/' && ibp+1 != limit && ibp[1] == '*') {
1629 if (put_out_comments) {
1630 *obp++ = '/';
1631 *obp++ = '*';
1633 ibp += 2;
1634 while (ibp + 1 != limit
1635 && !(ibp[0] == '*' && ibp[1] == '/')) {
1636 /* We need not worry about newline-marks,
1637 since they are never found in comments. */
1638 if (*ibp == '\n') {
1639 /* Newline in a file. Count it. */
1640 ++ip->lineno;
1641 ++op->lineno;
1643 if (put_out_comments)
1644 *obp++ = *ibp++;
1645 else
1646 ibp++;
1648 ibp += 2;
1649 if (put_out_comments) {
1650 *obp++ = '*';
1651 *obp++ = '/';
1654 else if (is_space[*ibp]) {
1655 *obp++ = *ibp++;
1656 if (ibp[-1] == '\n') {
1657 if (ip->macro == 0) {
1658 /* Newline in a file. Count it. */
1659 ++ip->lineno;
1660 ++op->lineno;
1661 } else if (!output_marks) {
1662 /* A newline mark, and we don't want marks
1663 in the output. If it is newline-hyphen,
1664 discard it entirely. Otherwise, it is
1665 newline-whitechar, so keep the whitechar. */
1666 obp--;
1667 if (*ibp == '-')
1668 ibp++;
1669 else {
1670 if (*ibp == '\n')
1671 ++op->lineno;
1672 *obp++ = *ibp++;
1674 } else {
1675 /* A newline mark; copy both chars to the output. */
1676 *obp++ = *ibp++;
1680 else break;
1682 if (*ibp != '(')
1683 break;
1686 /* This is now known to be a macro call.
1687 Discard the macro name from the output,
1688 along with any following whitespace just copied. */
1689 obp = obufp_before_macroname;
1690 op->lineno = op_lineno_before_macroname;
1692 /* Expand the macro, reading arguments as needed,
1693 and push the expansion on the input stack. */
1694 ip->bufp = ibp;
1695 op->bufp = obp;
1696 macroexpand (hp, op);
1698 /* Reexamine input stack, since macroexpand has pushed
1699 a new level on it. */
1700 obp = op->bufp;
1701 RECACHE;
1702 break;
1704 hashcollision:
1706 } /* End hash-table-search loop */
1707 ident_length = hash = 0; /* Stop collecting identifier */
1708 redo_char = 0;
1709 concatenated = 0;
1710 } /* End if (ident_length > 0) */
1711 } /* End switch */
1712 } /* End per-char loop */
1714 /* Come here to return -- but first give an error message
1715 if there was an unterminated successful conditional. */
1716 ending:
1717 if (if_stack != ip->if_stack) {
1718 const char *str;
1719 switch (if_stack->type) {
1720 case T_IF:
1721 str = "if";
1722 break;
1723 case T_IFDEF:
1724 str = "ifdef";
1725 break;
1726 case T_IFNDEF:
1727 str = "ifndef";
1728 break;
1729 case T_ELSE:
1730 str = "else";
1731 break;
1732 case T_ELIF:
1733 str = "elif";
1734 break;
1735 default:
1736 abort ();
1738 error_with_line (line_for_error (if_stack->lineno),
1739 "unterminated #%s conditional", str);
1741 if_stack = ip->if_stack;
1745 * Rescan a string into a temporary buffer and return the result
1746 * as a FILE_BUF. Note this function returns a struct, not a pointer.
1748 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
1749 * and insert such markers when appropriate. See `rescan' for details.
1750 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
1751 * before substitution; it is 0 for other uses.
1753 FILE_BUF
1754 expand_to_temp_buffer (buf, limit, output_marks)
1755 U_CHAR *buf, *limit;
1756 int output_marks;
1758 register FILE_BUF *ip;
1759 FILE_BUF obuf;
1760 int length = limit - buf;
1761 U_CHAR *buf1;
1762 int odepth = indepth;
1764 if (length < 0)
1765 abort ();
1767 /* Set up the input on the input stack. */
1769 buf1 = (U_CHAR *) alloca (length + 1);
1771 register U_CHAR *p1 = buf;
1772 register U_CHAR *p2 = buf1;
1774 while (p1 != limit)
1775 *p2++ = *p1++;
1777 buf1[length] = 0;
1779 /* Set up to receive the output. */
1781 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
1782 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
1783 obuf.fname = 0;
1784 obuf.macro = 0;
1785 obuf.free_ptr = 0;
1787 CHECK_DEPTH ({return obuf;});
1789 ++indepth;
1791 ip = &instack[indepth];
1792 ip->fname = 0;
1793 ip->macro = 0;
1794 ip->free_ptr = 0;
1795 ip->length = length;
1796 ip->buf = ip->bufp = buf1;
1797 ip->if_stack = if_stack;
1799 ip->lineno = obuf.lineno = 1;
1801 /* Scan the input, create the output. */
1803 rescan (&obuf, output_marks);
1805 /* Pop input stack to original state. */
1806 --indepth;
1808 if (indepth != odepth)
1809 abort ();
1811 /* Record the output. */
1812 obuf.length = obuf.bufp - obuf.buf;
1814 return obuf;
1818 * Process a # directive. Expects IP->bufp to point to the '#', as in
1819 * `#define foo bar'. Passes to the command handler
1820 * (do_define, do_include, etc.): the addresses of the 1st and
1821 * last chars of the command (starting immediately after the #
1822 * keyword), plus op and the keyword table pointer. If the command
1823 * contains comments it is copied into a temporary buffer sans comments
1824 * and the temporary buffer is passed to the command handler instead.
1825 * Likewise for backslash-newlines.
1827 * Returns nonzero if this was a known # directive.
1828 * Otherwise, returns zero, without advancing the input pointer.
1832 handle_directive (ip, op)
1833 FILE_BUF *ip, *op;
1835 register U_CHAR *bp, *cp;
1836 register struct directive *kt;
1837 register int ident_length;
1838 U_CHAR *resume_p;
1840 /* Nonzero means we must copy the entire command
1841 to get rid of comments or backslash-newlines. */
1842 int copy_command = 0;
1844 U_CHAR *ident, *after_ident;
1846 bp = ip->bufp;
1847 /* Skip whitespace and \-newline. */
1848 while (1) {
1849 if (is_hor_space[*bp])
1850 bp++;
1851 else if (*bp == '/' && (newline_fix (bp + 1), bp[1]) == '*') {
1852 ip->bufp = bp;
1853 skip_to_end_of_comment (ip, &ip->lineno);
1854 bp = ip->bufp;
1855 } else if (*bp == '\\' && bp[1] == '\n') {
1856 bp += 2; ip->lineno++;
1857 } else break;
1860 /* Now find end of directive name.
1861 If we encounter a backslash-newline, exchange it with any following
1862 symbol-constituents so that we end up with a contiguous name. */
1864 cp = bp;
1865 while (1) {
1866 if (is_idchar[*cp])
1867 cp++;
1868 else {
1869 if (*cp == '\\' && cp[1] == '\n')
1870 name_newline_fix (cp);
1871 if (is_idchar[*cp])
1872 cp++;
1873 else break;
1876 ident_length = cp - bp;
1877 ident = bp;
1878 after_ident = cp;
1880 /* A line of just `#' becomes blank. */
1882 if (ident_length == 0 && *after_ident == '\n') {
1883 ip->bufp = after_ident;
1884 return 1;
1888 * Decode the keyword and call the appropriate expansion
1889 * routine, after moving the input pointer up to the next line.
1891 for (kt = directive_table; kt->length > 0; kt++) {
1892 if (kt->length == ident_length
1893 && !strncmp (kt->name, (char *)ident, ident_length)) {
1894 register U_CHAR *buf;
1895 register U_CHAR *limit = ip->buf + ip->length;
1896 int unterminated = 0;
1898 /* Nonzero means do not delete comments within the directive.
1899 #define needs this to detect traditional token paste. */
1900 int keep_comments = kt->type == T_DEFINE;
1902 /* Find the end of this command (first newline not backslashed
1903 and not in a string or comment).
1904 Set COPY_COMMAND if the command must be copied
1905 (it contains a backslash-newline or a comment). */
1907 buf = bp = after_ident;
1908 while (bp < limit) {
1909 register U_CHAR c = *bp++;
1910 switch (c) {
1911 case '\\':
1912 if (bp < limit) {
1913 if (*bp == '\n') {
1914 ip->lineno++;
1915 copy_command = 1;
1917 bp++;
1919 break;
1921 case '\'':
1922 case '\"':
1923 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_command, &unterminated);
1924 if (unterminated) {
1925 /* Traditional preprocessing permits unterminated strings. */
1926 ip->bufp = bp;
1927 goto endloop1;
1929 break;
1931 /* <...> is special for #include. */
1932 case '<':
1933 if (kt->type != T_INCLUDE)
1934 break;
1935 while (*bp && *bp != '>') bp++;
1936 break;
1938 case '/':
1939 if (*bp == '\\' && bp[1] == '\n')
1940 newline_fix (bp);
1941 if (*bp == '*') {
1942 U_CHAR *obp = bp - 1;
1943 ip->bufp = bp + 1;
1944 skip_to_end_of_comment (ip, &ip->lineno);
1945 bp = ip->bufp;
1946 /* No need to copy the command because of a comment at the end;
1947 just don't include the comment in the directive. */
1948 if (bp == limit || *bp == '\n') {
1949 bp = obp;
1950 goto endloop1;
1952 /* Don't remove the comments if this is #define. */
1953 if (! keep_comments)
1954 copy_command++;
1956 break;
1958 case '\n':
1959 --bp; /* Point to the newline */
1960 ip->bufp = bp;
1961 goto endloop1;
1964 ip->bufp = bp;
1966 endloop1:
1967 resume_p = ip->bufp;
1968 /* BP is the end of the directive.
1969 RESUME_P is the next interesting data after the directive.
1970 A comment may come between. */
1972 if (copy_command) {
1973 register U_CHAR *xp = buf;
1974 /* Need to copy entire command into temp buffer before dispatching */
1976 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
1977 some slop */
1978 buf = cp;
1980 /* Copy to the new buffer, deleting comments
1981 and backslash-newlines (and whitespace surrounding the latter). */
1983 while (xp < bp) {
1984 register U_CHAR c = *xp++;
1985 *cp++ = c;
1987 switch (c) {
1988 case '\n':
1989 break;
1991 /* <...> is special for #include. */
1992 case '<':
1993 if (kt->type != T_INCLUDE)
1994 break;
1995 while (xp < bp && c != '>') {
1996 c = *xp++;
1997 if (c == '\\' && xp < bp && *xp == '\n')
1998 xp++, ip->lineno++;
1999 else
2000 *cp++ = c;
2002 break;
2004 case '\\':
2005 if (*xp == '\n') {
2006 xp++;
2007 cp--;
2008 if (cp != buf && is_space[cp[-1]]) {
2009 while (cp != buf && is_space[cp[-1]]) cp--;
2010 cp++;
2011 SKIP_WHITE_SPACE (xp);
2012 } else if (is_space[*xp]) {
2013 *cp++ = *xp++;
2014 SKIP_WHITE_SPACE (xp);
2016 } else {
2017 *cp++ = *xp++;
2019 break;
2021 case '\'':
2022 case '\"':
2024 register U_CHAR *bp1
2025 = skip_quoted_string (xp - 1, limit, ip->lineno, 0, 0, 0);
2026 while (xp != bp1)
2027 *cp++ = *xp++;
2029 break;
2031 case '/':
2032 if (*xp == '*') {
2033 ip->bufp = xp + 1;
2034 skip_to_end_of_comment (ip, 0);
2035 if (keep_comments)
2036 while (xp != ip->bufp)
2037 *cp++ = *xp++;
2038 /* Delete the slash. */
2039 else
2040 cp--;
2041 xp = ip->bufp;
2046 /* Null-terminate the copy. */
2048 *cp = 0;
2050 else
2051 cp = bp;
2053 ip->bufp = resume_p;
2055 /* Call the appropriate command handler. buf now points to
2056 either the appropriate place in the input buffer, or to
2057 the temp buffer if it was necessary to make one. cp
2058 points to the first char after the contents of the (possibly
2059 copied) command, in either case. */
2060 (*kt->func) (buf, cp, op, kt);
2061 check_expand (op, ip->length - (ip->bufp - ip->buf));
2063 return 1;
2067 return 0;
2070 static const char *const
2071 monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2072 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
2075 * expand things like __FILE__. Place the expansion into the output
2076 * buffer *without* rescanning.
2078 void
2079 special_symbol (hp, op)
2080 HASHNODE *hp;
2081 FILE_BUF *op;
2083 char *buf = 0;
2084 time_t t;
2085 int i, len;
2086 int true_indepth;
2087 FILE_BUF *ip = NULL;
2088 static struct tm *timebuf = NULL;
2090 int paren = 0; /* For special `defined' keyword */
2092 for (i = indepth; i >= 0; i--)
2093 if (instack[i].fname != NULL) {
2094 ip = &instack[i];
2095 break;
2097 if (ip == NULL)
2098 fatal ("not in any file?!");
2100 switch (hp->type) {
2101 case T_FILE:
2102 case T_BASE_FILE:
2104 const char *string;
2105 if (hp->type == T_FILE)
2106 string = ip->fname;
2107 else
2108 string = instack[0].fname;
2110 if (string)
2112 buf = (char *) alloca (3 + strlen (string));
2113 sprintf (buf, "\"%s\"", string);
2115 else
2116 strcpy (buf, "\"\"");
2118 break;
2121 case T_INCLUDE_LEVEL:
2122 true_indepth = 0;
2123 for (i = indepth; i >= 0; i--)
2124 if (instack[i].fname != NULL)
2125 true_indepth++;
2127 buf = (char *) alloca (8); /* Eigth bytes ought to be more than enough */
2128 sprintf (buf, "%d", true_indepth - 1);
2129 break;
2131 case T_VERSION:
2132 buf = (char *) alloca (3 + strlen (version_string));
2133 sprintf (buf, "\"%s\"", version_string);
2134 break;
2136 case T_CONST:
2137 buf = (char *) hp->value.cpval;
2138 break;
2140 case T_SPECLINE:
2141 buf = (char *) alloca (10);
2142 sprintf (buf, "%d", ip->lineno);
2143 break;
2145 case T_DATE:
2146 case T_TIME:
2147 if (timebuf == NULL) {
2148 t = time (0);
2149 timebuf = localtime (&t);
2151 buf = (char *) alloca (20);
2152 if (hp->type == T_DATE)
2153 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2154 timebuf->tm_mday, timebuf->tm_year + 1900);
2155 else
2156 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2157 timebuf->tm_sec);
2158 break;
2160 case T_SPEC_DEFINED:
2161 buf = (char *) " 0 "; /* Assume symbol is not defined */
2162 ip = &instack[indepth];
2163 SKIP_WHITE_SPACE (ip->bufp);
2164 if (*ip->bufp == '(') {
2165 paren++;
2166 ip->bufp++; /* Skip over the paren */
2167 SKIP_WHITE_SPACE (ip->bufp);
2170 if (!is_idstart[*ip->bufp])
2171 goto oops;
2172 if (lookup (ip->bufp, -1, -1))
2173 buf = (char *) " 1 ";
2174 while (is_idchar[*ip->bufp])
2175 ++ip->bufp;
2176 SKIP_WHITE_SPACE (ip->bufp);
2177 if (paren) {
2178 if (*ip->bufp != ')')
2179 goto oops;
2180 ++ip->bufp;
2182 break;
2184 oops:
2186 error ("`defined' must be followed by ident or (ident)");
2187 break;
2189 default:
2190 error ("cccp error: invalid special hash type"); /* time for gdb */
2191 abort ();
2193 len = strlen (buf);
2194 check_expand (op, len);
2195 memcpy (op->bufp, buf, len);
2196 op->bufp += len;
2200 /* Routines to handle #directives */
2203 * Process include file by reading it in and calling rescan.
2204 * Expects to see "fname" or <fname> on the input.
2206 void
2207 do_include (buf, limit, op, keyword)
2208 U_CHAR *buf, *limit;
2209 FILE_BUF *op;
2210 struct directive *keyword ATTRIBUTE_UNUSED;
2212 char *fname; /* Dynamically allocated fname buffer */
2213 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
2215 struct file_name_list *stackp = include; /* Chain of dirs to search */
2216 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
2217 int flen;
2219 int f; /* file number */
2221 int retried = 0; /* Have already tried macro
2222 expanding the include line*/
2223 FILE_BUF trybuf; /* It got expanded into here */
2224 int system_header_p = 0; /* 0 for "...", 1 for <...> */
2226 f= -1; /* JF we iz paranoid! */
2228 get_filename:
2230 fbeg = buf;
2231 SKIP_WHITE_SPACE (fbeg);
2232 /* Discard trailing whitespace so we can easily see
2233 if we have parsed all the significant chars we were given. */
2234 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
2236 switch (*fbeg++) {
2237 case '\"':
2238 fend = fbeg;
2239 while (fend != limit && *fend != '\"')
2240 fend++;
2241 if (*fend == '\"' && fend + 1 == limit) {
2242 FILE_BUF *fp;
2244 /* We have "filename". Figure out directory this source
2245 file is coming from and put it on the front of the list. */
2247 /* If -I- was specified, don't search current dir, only spec'd ones. */
2248 if (ignore_srcdir) break;
2250 for (fp = &instack[indepth]; fp >= instack; fp--)
2252 size_t n;
2253 const char *ep, *nam;
2255 if ((nam = fp->fname) != NULL) {
2256 /* Found a named file. Figure out dir of the file,
2257 and put it in front of the search list. */
2258 dsp[0].next = stackp;
2259 stackp = dsp;
2260 ep = strrchr (nam, '/');
2261 if (ep != NULL) {
2262 char *f;
2263 n = ep - nam;
2264 f = (char *) alloca (n + 1);
2265 strncpy (f, nam, n);
2266 f[n] = '\0';
2267 dsp[0].fname = f;
2268 if (n > max_include_len) max_include_len = n;
2269 } else {
2270 dsp[0].fname = 0; /* Current directory */
2272 break;
2275 break;
2277 goto fail;
2279 case '<':
2280 fend = fbeg;
2281 while (fend != limit && *fend != '>') fend++;
2282 if (*fend == '>' && fend + 1 == limit) {
2283 system_header_p = 1;
2284 /* If -I-, start with the first -I dir after the -I-. */
2285 if (first_bracket_include)
2286 stackp = first_bracket_include;
2287 break;
2289 goto fail;
2291 default:
2292 fail:
2293 if (retried) {
2294 error ("#include expects \"fname\" or <fname>");
2295 return;
2296 } else {
2297 trybuf = expand_to_temp_buffer (buf, limit, 0);
2298 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
2299 memcpy (buf, trybuf.buf, trybuf.bufp - trybuf.buf);
2300 limit = buf + (trybuf.bufp - trybuf.buf);
2301 free (trybuf.buf);
2302 retried++;
2303 goto get_filename;
2307 flen = fend - fbeg;
2308 fname = (char *) alloca (max_include_len + flen + 2);
2309 /* + 2 above for slash and terminating null. */
2311 /* If specified file name is absolute, just open it. */
2313 if (*fbeg == '/') {
2314 strncpy (fname, (char *)fbeg, flen);
2315 fname[flen] = 0;
2316 f = open (fname, O_RDONLY, 0666);
2317 } else {
2318 /* Search directory path, trying to open the file.
2319 Copy each filename tried into FNAME. */
2321 for (; stackp; stackp = stackp->next) {
2322 if (stackp->fname) {
2323 strcpy (fname, stackp->fname);
2324 strcat (fname, "/");
2325 fname[strlen (fname) + flen] = 0;
2326 } else {
2327 fname[0] = 0;
2329 strncat (fname, (char *)fbeg, flen);
2330 if ((f = open (fname, O_RDONLY, 0666)) >= 0)
2331 break;
2335 if (f < 0) {
2336 strncpy (fname, (char *)fbeg, flen);
2337 fname[flen] = 0;
2338 error_from_errno (fname);
2340 /* For -M, add this file to the dependencies. */
2341 if (print_deps > (system_header_p || (system_include_depth > 0))) {
2342 if (system_header_p)
2343 warning ("nonexistent file <%.*s> omitted from dependency output",
2344 fend - fbeg, fbeg);
2345 else
2347 deps_output ((const char *)fbeg, fend - fbeg);
2348 deps_output (" ", 0);
2351 } else {
2353 /* Check to see if this include file is a once-only include file.
2354 If so, give up. */
2356 struct file_name_list* ptr;
2358 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
2359 if (!strcmp (ptr->fname, fname)) {
2360 close (f);
2361 return; /* This file was once'd. */
2365 for (ptr = all_include_files; ptr; ptr = ptr->next) {
2366 if (!strcmp (ptr->fname, fname))
2367 break; /* This file was included before. */
2370 if (ptr == 0) {
2371 /* This is the first time for this file. */
2372 /* Add it to list of files included. */
2374 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2375 ptr->next = all_include_files;
2376 all_include_files = ptr;
2377 ptr->fname = xstrdup (fname);
2379 /* For -M, add this file to the dependencies. */
2380 if (print_deps > (system_header_p || (system_include_depth > 0))) {
2381 deps_output (fname, strlen (fname));
2382 deps_output (" ", 0);
2386 if (system_header_p)
2387 system_include_depth++;
2389 /* Actually process the file. */
2390 finclude (f, fname, op);
2392 if (system_header_p)
2393 system_include_depth--;
2395 close (f);
2399 /* Process the contents of include file FNAME, already open on descriptor F,
2400 with output to OP. */
2402 void
2403 finclude (f, fname, op)
2404 int f;
2405 const char *fname;
2406 FILE_BUF *op;
2408 int st_mode;
2409 long st_size;
2410 long i;
2411 FILE_BUF *fp; /* For input stack frame */
2413 CHECK_DEPTH (return;);
2415 if (file_size_and_mode (f, &st_mode, &st_size))
2416 goto nope;
2418 fp = &instack[indepth + 1];
2419 memset (fp, 0, sizeof (FILE_BUF));
2420 fp->fname = fname;
2421 fp->length = 0;
2422 fp->lineno = 1;
2423 fp->if_stack = if_stack;
2425 if (S_ISREG (st_mode)) {
2426 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2427 fp->bufp = fp->buf;
2429 /* Read the file contents, knowing that st_size is an upper bound
2430 on the number of bytes we can read. */
2431 while (st_size > 0) {
2432 i = read (f, fp->buf + fp->length, st_size);
2433 if (i <= 0) {
2434 if (i == 0) break;
2435 goto nope;
2437 fp->length += i;
2438 st_size -= i;
2441 else {
2442 /* Cannot count its file size before reading. */
2444 U_CHAR *bufp;
2445 U_CHAR *basep;
2446 int bsize = 2000;
2448 st_size = 0;
2449 basep = (U_CHAR *) xmalloc (bsize + 2);
2450 bufp = basep;
2452 for (;;) {
2453 i = read (f, bufp, bsize - st_size);
2454 if (i < 0)
2455 goto nope; /* error! */
2456 if (i == 0)
2457 break; /* End of file */
2458 st_size += i;
2459 bufp += i;
2460 if (bsize == st_size) { /* Buffer is full! */
2461 bsize *= 2;
2462 basep = (U_CHAR *) xrealloc (basep, bsize + 2);
2463 bufp = basep + st_size; /* May have moved */
2466 fp->buf = basep;
2467 fp->bufp = fp->buf;
2468 fp->length = st_size;
2470 close (f);
2472 /* Make sure data ends with a newline. And put a null after it. */
2474 if (fp->length > 0 && fp->buf[fp->length-1] != '\n')
2475 fp->buf[fp->length++] = '\n';
2476 fp->buf[fp->length] = '\0';
2478 indepth++;
2479 output_line_command (fp, op, 0, enter_file);
2480 rescan (op, 0);
2481 indepth--;
2482 output_line_command (&instack[indepth], op, 0, leave_file);
2483 free (fp->buf);
2484 return;
2486 nope:
2487 perror_with_name (fname);
2488 close (f);
2492 /* Process a #define command.
2493 BUF points to the contents of the #define command, as a continguous string.
2494 LIMIT points to the first character past the end of the definition.
2495 KEYWORD is the keyword-table entry for #define. */
2497 void
2498 do_define (buf, limit, op, keyword)
2499 U_CHAR *buf, *limit;
2500 FILE_BUF *op ATTRIBUTE_UNUSED;
2501 struct directive *keyword ATTRIBUTE_UNUSED;
2503 U_CHAR *bp; /* temp ptr into input buffer */
2504 U_CHAR *symname; /* remember where symbol name starts */
2505 int sym_length; /* and how long it is */
2507 DEFINITION *defn;
2508 int arglengths = 0; /* Accumulate lengths of arg names
2509 plus number of args. */
2510 int hashcode;
2512 bp = buf;
2514 while (is_hor_space[*bp])
2515 bp++;
2517 symname = bp; /* remember where it starts */
2518 while (is_idchar[*bp] && bp < limit) {
2519 bp++;
2521 sym_length = bp - symname;
2522 if (sym_length == 0)
2523 error ("invalid macro name");
2524 else if (!is_idstart[*symname]) {
2525 U_CHAR *msg; /* what pain... */
2526 msg = (U_CHAR *) alloca (sym_length + 1);
2527 memcpy (msg, symname, sym_length);
2528 msg[sym_length] = 0;
2529 error ("invalid macro name `%s'", msg);
2530 } else {
2531 if (! strncmp ((char *)symname, "defined", 7) && sym_length == 7)
2532 error ("defining `defined' as a macro");
2535 /* lossage will occur if identifiers or control keywords are broken
2536 across lines using backslash. This is not the right place to take
2537 care of that. */
2539 if (*bp == '(') {
2540 struct arglist *arg_ptrs = NULL;
2541 int argno = 0;
2543 bp++; /* skip '(' */
2544 SKIP_WHITE_SPACE (bp);
2546 /* Loop over macro argument names. */
2547 while (*bp != ')') {
2548 struct arglist *temp;
2550 temp = (struct arglist *) alloca (sizeof (struct arglist));
2551 temp->name = bp;
2552 temp->next = arg_ptrs;
2553 temp->argno = argno++;
2554 arg_ptrs = temp;
2556 if (!is_idstart[*bp])
2557 warning ("parameter name starts with a digit in #define");
2559 /* Find the end of the arg name. */
2560 while (is_idchar[*bp]) {
2561 bp++;
2563 temp->length = bp - temp->name;
2564 arglengths += temp->length + 2;
2565 SKIP_WHITE_SPACE (bp);
2566 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2567 error ("badly punctuated parameter list in #define");
2568 return;
2570 if (*bp == ',') {
2571 bp++;
2572 SKIP_WHITE_SPACE (bp);
2574 if (bp >= limit) {
2575 error ("unterminated parameter list in #define");
2576 return;
2580 ++bp; /* skip paren */
2581 /* Skip exactly one space or tab if any. */
2582 if (bp < limit && (*bp == ' ' || *bp == '\t')) ++bp;
2583 /* now everything from bp before limit is the definition. */
2584 defn = collect_expansion (bp, limit, argno, arg_ptrs);
2586 /* Now set defn->argnames to the result of concatenating
2587 the argument names in reverse order
2588 with comma-space between them. */
2589 defn->argnames = (U_CHAR *) xmalloc (arglengths + 1);
2591 struct arglist *temp;
2592 int i = 0;
2593 for (temp = arg_ptrs; temp; temp = temp->next) {
2594 memcpy (&defn->argnames[i], temp->name, temp->length);
2595 i += temp->length;
2596 if (temp->next != 0) {
2597 defn->argnames[i++] = ',';
2598 defn->argnames[i++] = ' ';
2601 defn->argnames[i] = 0;
2603 } else {
2604 /* simple expansion or empty definition; gobble it */
2605 if (is_hor_space[*bp])
2606 ++bp; /* skip exactly one blank/tab char */
2607 /* now everything from bp before limit is the definition. */
2608 defn = collect_expansion (bp, limit, -1, 0);
2609 defn->argnames = (U_CHAR *) "";
2612 hashcode = hashf (symname, sym_length, HASHSIZE);
2615 HASHNODE *hp;
2616 if ((hp = lookup (symname, sym_length, hashcode)) == NULL)
2617 hp = install (symname, sym_length, T_MACRO, hashcode);
2618 else {
2619 if (hp->type != T_MACRO || compare_defs (defn, hp->value.defn))
2620 warning ("\"%.*s\" redefined", sym_length, symname);
2622 /* Replace the old definition. */
2623 hp->type = T_MACRO;
2626 hp->value.defn = defn;
2631 * return zero if two DEFINITIONs are isomorphic
2634 compare_defs (d1, d2)
2635 DEFINITION *d1, *d2;
2637 register struct reflist *a1, *a2;
2638 register U_CHAR *p1 = d1->expansion;
2639 register U_CHAR *p2 = d2->expansion;
2640 int first = 1;
2642 if (d1->nargs != d2->nargs)
2643 return 1;
2644 if (strcmp ((char *)d1->argnames, (char *)d2->argnames))
2645 return 1;
2646 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
2647 a1 = a1->next, a2 = a2->next) {
2648 if (!((a1->nchars == a2->nchars
2649 && ! strncmp ((char *)p1, (char *)p2, a1->nchars))
2650 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2651 || a1->argno != a2->argno
2652 || a1->stringify != a2->stringify
2653 || a1->raw_before != a2->raw_before
2654 || a1->raw_after != a2->raw_after)
2655 return 1;
2656 first = 0;
2657 p1 += a1->nchars;
2658 p2 += a2->nchars;
2660 if (a1 != a2)
2661 return 1;
2662 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
2663 p2, d2->length - (p2 - d2->expansion), 1))
2664 return 1;
2665 return 0;
2668 /* Return 1 if two parts of two macro definitions are effectively different.
2669 One of the parts starts at BEG1 and has LEN1 chars;
2670 the other has LEN2 chars at BEG2.
2671 Any sequence of whitespace matches any other sequence of whitespace.
2672 FIRST means these parts are the first of a macro definition;
2673 so ignore leading whitespace entirely.
2674 LAST means these parts are the last of a macro definition;
2675 so ignore trailing whitespace entirely. */
2677 comp_def_part (first, beg1, len1, beg2, len2, last)
2678 int first;
2679 U_CHAR *beg1, *beg2;
2680 int len1, len2;
2681 int last;
2683 register U_CHAR *end1 = beg1 + len1;
2684 register U_CHAR *end2 = beg2 + len2;
2685 if (first) {
2686 while (beg1 != end1 && is_space[*beg1]) beg1++;
2687 while (beg2 != end2 && is_space[*beg2]) beg2++;
2689 if (last) {
2690 while (beg1 != end1 && is_space[end1[-1]]) end1--;
2691 while (beg2 != end2 && is_space[end2[-1]]) end2--;
2693 while (beg1 != end1 && beg2 != end2) {
2694 if (is_space[*beg1] && is_space[*beg2]) {
2695 while (beg1 != end1 && is_space[*beg1]) beg1++;
2696 while (beg2 != end2 && is_space[*beg2]) beg2++;
2697 } else if (*beg1 == *beg2) {
2698 beg1++; beg2++;
2699 } else break;
2701 return (beg1 != end1) || (beg2 != end2);
2704 /* Read a replacement list for a macro with parameters.
2705 Build the DEFINITION structure.
2706 Reads characters of text starting at BUF until LIMIT.
2707 ARGLIST specifies the formal parameters to look for
2708 in the text of the definition; NARGS is the number of args
2709 in that list, or -1 for a macro name that wants no argument list.
2710 MACRONAME is the macro name itself (so we can avoid recursive expansion)
2711 and NAMELEN is its length in characters.
2713 Note that comments and backslash-newlines have already been deleted
2714 from the argument. */
2716 /* Leading and trailing Space, Tab, etc. are converted to markers
2717 Newline Space, Newline Tab, etc.
2718 Newline Space makes a space in the final output
2719 but is discarded if stringified. (Newline Tab is similar but
2720 makes a Tab instead.)
2722 If there is no trailing whitespace, a Newline Space is added at the end
2723 to prevent concatenation that would be contrary to the standard. */
2725 DEFINITION *
2726 collect_expansion (buf, end, nargs, arglist)
2727 U_CHAR *buf, *end;
2728 int nargs;
2729 struct arglist *arglist;
2731 DEFINITION *defn;
2732 register U_CHAR *p, *limit, *lastp, *exp_p;
2733 struct reflist *endpat = NULL;
2734 /* Pointer to first nonspace after last ## seen. */
2735 U_CHAR *concat = 0;
2736 /* Pointer to first nonspace after last single-# seen. */
2737 U_CHAR *stringify = 0;
2738 int maxsize;
2739 int expected_delimiter = '\0';
2741 /* Scan thru the replacement list, ignoring comments and quoted
2742 strings, picking up on the macro calls. It does a linear search
2743 thru the arg list on every potential symbol. Profiling might say
2744 that something smarter should happen. */
2746 if (end < buf)
2747 abort ();
2749 /* Find the beginning of the trailing whitespace. */
2750 /* Find end of leading whitespace. */
2751 limit = end;
2752 p = buf;
2753 while (p < limit && is_space[limit[-1]]) limit--;
2754 while (p < limit && is_space[*p]) p++;
2756 /* Allocate space for the text in the macro definition.
2757 Leading and trailing whitespace chars need 2 bytes each.
2758 Each other input char may or may not need 1 byte,
2759 so this is an upper bound.
2760 The extra 2 are for invented trailing newline-marker and final null. */
2761 maxsize = (sizeof (DEFINITION)
2762 + 2 * (end - limit) + 2 * (p - buf)
2763 + (limit - p) + 3);
2764 defn = (DEFINITION *) xcalloc (1, maxsize);
2766 defn->nargs = nargs;
2767 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
2768 lastp = exp_p;
2770 p = buf;
2772 /* Convert leading whitespace to Newline-markers. */
2773 while (p < limit && is_space[*p]) {
2774 *exp_p++ = '\n';
2775 *exp_p++ = *p++;
2778 /* Process the main body of the definition. */
2779 while (p < limit) {
2780 int skipped_arg = 0;
2781 register U_CHAR c = *p++;
2783 *exp_p++ = c;
2785 /* In -traditional mode, recognize arguments inside strings and
2786 and character constants, and ignore special properties of #.
2787 Arguments inside strings are considered "stringified", but no
2788 extra quote marks are supplied. */
2789 switch (c) {
2790 case '\'':
2791 case '\"':
2792 if (expected_delimiter != '\0') {
2793 if (c == expected_delimiter)
2794 expected_delimiter = '\0';
2795 } else
2796 expected_delimiter = c;
2797 break;
2799 case '\\':
2800 /* Backslash quotes delimiters and itself, but not macro args. */
2801 if (expected_delimiter != 0 && p < limit
2802 && (*p == expected_delimiter || *p == '\\')) {
2803 *exp_p++ = *p++;
2804 continue;
2806 break;
2808 case '/':
2809 if (expected_delimiter != '\0') /* No comments inside strings. */
2810 break;
2811 if (*p == '*') {
2812 /* If we find a comment that wasn't removed by handle_directive,
2813 this must be -traditional. So replace the comment with
2814 nothing at all. */
2815 exp_p--;
2816 p += 1;
2817 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
2818 p++;
2820 break;
2823 if (is_idchar[c] && nargs > 0) {
2824 U_CHAR *id_beg = p - 1;
2825 int id_len;
2827 --exp_p;
2828 while (p != limit && is_idchar[*p]) p++;
2829 id_len = p - id_beg;
2831 if (is_idstart[c]) {
2832 register struct arglist *arg;
2834 for (arg = arglist; arg != NULL; arg = arg->next) {
2835 struct reflist *tpat;
2837 if (arg->name[0] == c
2838 && arg->length == id_len
2839 && strncmp ((char *)arg->name, (char *)id_beg, id_len) == 0) {
2840 /* make a pat node for this arg and append it to the end of
2841 the pat list */
2842 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
2843 tpat->next = NULL;
2844 tpat->raw_before = concat == id_beg;
2845 tpat->raw_after = 0;
2846 tpat->stringify = expected_delimiter != '\0';
2848 if (endpat == NULL)
2849 defn->pattern = tpat;
2850 else
2851 endpat->next = tpat;
2852 endpat = tpat;
2854 tpat->argno = arg->argno;
2855 tpat->nchars = exp_p - lastp;
2857 register U_CHAR *p1 = p;
2858 SKIP_WHITE_SPACE (p1);
2859 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
2860 tpat->raw_after = 1;
2862 lastp = exp_p; /* place to start copying from next time */
2863 skipped_arg = 1;
2864 break;
2869 /* If this was not a macro arg, copy it into the expansion. */
2870 if (! skipped_arg) {
2871 register U_CHAR *lim1 = p;
2872 p = id_beg;
2873 while (p != lim1)
2874 *exp_p++ = *p++;
2875 if (stringify == id_beg)
2876 error ("# operator should be followed by a macro argument name");
2881 if (limit < end) {
2882 /* Convert trailing whitespace to Newline-markers. */
2883 while (limit < end && is_space[*limit]) {
2884 *exp_p++ = '\n';
2885 *exp_p++ = *limit++;
2888 *exp_p = '\0';
2890 defn->length = exp_p - defn->expansion;
2892 /* Crash now if we overrun the allocated size. */
2893 if (defn->length + 1 > maxsize)
2894 abort ();
2896 return defn;
2900 * interpret #line command. Remembers previously seen fnames
2901 * in its very own hash table.
2903 #define FNAME_HASHSIZE 37
2904 void
2905 do_line (buf, limit, op, keyword)
2906 U_CHAR *buf, *limit;
2907 FILE_BUF *op;
2908 struct directive *keyword ATTRIBUTE_UNUSED;
2910 register U_CHAR *bp;
2911 FILE_BUF *ip = &instack[indepth];
2912 FILE_BUF tem;
2913 int new_lineno;
2914 enum file_change_code file_change = same_file;
2916 /* Expand any macros. */
2917 tem = expand_to_temp_buffer (buf, limit, 0);
2919 /* Point to macroexpanded line, which is null-terminated now. */
2920 bp = tem.buf;
2921 SKIP_WHITE_SPACE (bp);
2923 if (!isdigit (*bp)) {
2924 error ("invalid format #line command");
2925 return;
2928 /* The Newline at the end of this line remains to be processed.
2929 To put the next line at the specified line number,
2930 we must store a line number now that is one less. */
2931 new_lineno = atoi ((char *)bp) - 1;
2933 /* skip over the line number. */
2934 while (isdigit (*bp))
2935 bp++;
2937 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
2938 if (*bp && !is_space[*bp]) {
2939 error ("invalid format #line command");
2940 return;
2942 #endif
2944 SKIP_WHITE_SPACE (bp);
2946 if (*bp == '\"') {
2947 static HASHNODE *fname_table[FNAME_HASHSIZE];
2948 HASHNODE *hp, **hash_bucket;
2949 U_CHAR *fname;
2950 int fname_length;
2952 fname = ++bp;
2954 while (*bp && *bp != '\"')
2955 bp++;
2956 if (*bp != '\"') {
2957 error ("invalid format #line command");
2958 return;
2961 fname_length = bp - fname;
2963 bp++;
2964 SKIP_WHITE_SPACE (bp);
2965 if (*bp) {
2966 if (*bp == '1')
2967 file_change = enter_file;
2968 else if (*bp == '2')
2969 file_change = leave_file;
2970 else {
2971 error ("invalid format #line command");
2972 return;
2975 bp++;
2976 SKIP_WHITE_SPACE (bp);
2977 if (*bp) {
2978 error ("invalid format #line command");
2979 return;
2983 hash_bucket =
2984 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
2985 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
2986 if (hp->length == fname_length &&
2987 strncmp (hp->value.cpval, (char *)fname, fname_length) == 0) {
2988 ip->fname = hp->value.cpval;
2989 break;
2991 if (hp == 0) {
2992 char *q;
2993 /* Didn't find it; cons up a new one. */
2994 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
2995 hp->next = *hash_bucket;
2996 *hash_bucket = hp;
2998 hp->length = fname_length;
2999 ip->fname = hp->value.cpval = q = ((char *) hp) + sizeof (HASHNODE);
3000 memcpy (q, fname, fname_length);
3002 } else if (*bp) {
3003 error ("invalid format #line command");
3004 return;
3007 ip->lineno = new_lineno;
3008 output_line_command (ip, op, 0, file_change);
3009 check_expand (op, ip->length - (ip->bufp - ip->buf));
3013 * remove all definitions of symbol from symbol table.
3014 * according to un*x /lib/cpp, it is not an error to undef
3015 * something that has no definitions, so it isn't one here either.
3017 void
3018 do_undef (buf, limit, op, keyword)
3019 U_CHAR *buf;
3020 U_CHAR *limit ATTRIBUTE_UNUSED;
3021 FILE_BUF *op ATTRIBUTE_UNUSED;
3022 struct directive *keyword ATTRIBUTE_UNUSED;
3024 HASHNODE *hp;
3026 SKIP_WHITE_SPACE (buf);
3028 if (! strncmp ((char *)buf, "defined", 7) && ! is_idchar[buf[7]])
3029 warning ("undefining `defined'");
3031 while ((hp = lookup (buf, -1, -1)) != NULL) {
3032 if (hp->type != T_MACRO)
3033 warning ("undefining `%s'", hp->name);
3034 delete_macro (hp);
3039 * handle #if command by
3040 * 1) inserting special `defined' keyword into the hash table
3041 * that gets turned into 0 or 1 by special_symbol (thus,
3042 * if the luser has a symbol called `defined' already, it won't
3043 * work inside the #if command)
3044 * 2) rescan the input into a temporary output buffer
3045 * 3) pass the output buffer to the yacc parser and collect a value
3046 * 4) clean up the mess left from steps 1 and 2.
3047 * 5) call conditional_skip to skip til the next #endif (etc.),
3048 * or not, depending on the value from step 3.
3050 void
3051 do_if (buf, limit, op, keyword)
3052 U_CHAR *buf, *limit;
3053 FILE_BUF *op ATTRIBUTE_UNUSED;
3054 struct directive *keyword ATTRIBUTE_UNUSED;
3056 int value;
3057 FILE_BUF *ip = &instack[indepth];
3059 value = eval_if_expression (buf, limit - buf);
3060 conditional_skip (ip, value == 0, T_IF);
3064 * handle a #elif directive by not changing if_stack either.
3065 * see the comment above do_else.
3067 void
3068 do_elif (buf, limit, op, keyword)
3069 U_CHAR *buf, *limit;
3070 FILE_BUF *op;
3071 struct directive *keyword ATTRIBUTE_UNUSED;
3073 int value;
3074 FILE_BUF *ip = &instack[indepth];
3076 if (if_stack == instack[indepth].if_stack) {
3077 error ("#elif not within a conditional");
3078 return;
3079 } else {
3080 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
3081 error ("#elif after #else");
3082 fprintf (stderr, " (matches line %d", if_stack->lineno);
3083 if (if_stack->fname != NULL && ip->fname != NULL &&
3084 strcmp (if_stack->fname, ip->fname) != 0)
3085 fprintf (stderr, ", file %s", if_stack->fname);
3086 fprintf (stderr, ")\n");
3088 if_stack->type = T_ELIF;
3091 if (if_stack->if_succeeded)
3092 skip_if_group (ip, 0);
3093 else {
3094 value = eval_if_expression (buf, limit - buf);
3095 if (value == 0)
3096 skip_if_group (ip, 0);
3097 else {
3098 ++if_stack->if_succeeded; /* continue processing input */
3099 output_line_command (ip, op, 1, same_file);
3105 * evaluate a #if expression in BUF, of length LENGTH,
3106 * then parse the result as a C expression and return the value as an int.
3109 eval_if_expression (buf, length)
3110 U_CHAR *buf;
3111 int length;
3113 FILE_BUF temp_obuf;
3114 HASHNODE *save_defined;
3115 int value;
3117 save_defined = install (U"defined", -1, T_SPEC_DEFINED, -1);
3118 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0);
3119 delete_macro (save_defined); /* clean up special symbol */
3121 value = parse_c_expression ((char *)temp_obuf.buf);
3123 free (temp_obuf.buf);
3125 return value;
3129 * routine to handle ifdef/ifndef. Try to look up the symbol,
3130 * then do or don't skip to the #endif/#else/#elif depending
3131 * on what directive is actually being processed.
3133 void
3134 do_xifdef (buf, limit, op, keyword)
3135 U_CHAR *buf, *limit;
3136 FILE_BUF *op ATTRIBUTE_UNUSED;
3137 struct directive *keyword;
3139 int skip;
3140 FILE_BUF *ip = &instack[indepth];
3141 U_CHAR *end;
3143 /* Discard leading and trailing whitespace. */
3144 SKIP_WHITE_SPACE (buf);
3145 while (limit != buf && is_hor_space[limit[-1]]) limit--;
3147 /* Find the end of the identifier at the beginning. */
3148 for (end = buf; is_idchar[*end]; end++);
3150 if (end == buf) {
3151 skip = (keyword->type == T_IFDEF);
3152 } else {
3153 skip = (lookup (buf, end-buf, -1) == NULL) ^ (keyword->type == T_IFNDEF);
3156 conditional_skip (ip, skip, T_IF);
3160 * push TYPE on stack; then, if SKIP is nonzero, skip ahead.
3162 void
3163 conditional_skip (ip, skip, type)
3164 FILE_BUF *ip;
3165 int skip;
3166 enum node_type type;
3168 IF_STACK_FRAME *temp;
3170 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
3171 temp->fname = ip->fname;
3172 temp->lineno = ip->lineno;
3173 temp->next = if_stack;
3174 if_stack = temp;
3176 if_stack->type = type;
3178 if (skip != 0) {
3179 skip_if_group (ip, 0);
3180 return;
3181 } else {
3182 ++if_stack->if_succeeded;
3183 output_line_command (ip, &outbuf, 1, same_file);
3188 * skip to #endif, #else, or #elif. adjust line numbers, etc.
3189 * leaves input ptr at the sharp sign found.
3190 * If ANY is nonzero, return at next directive of any sort.
3192 void
3193 skip_if_group (ip, any)
3194 FILE_BUF *ip;
3195 int any;
3197 register U_CHAR *bp = ip->bufp, *cp;
3198 register U_CHAR *endb = ip->buf + ip->length;
3199 struct directive *kt;
3200 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
3201 U_CHAR *beg_of_line = bp;
3203 while (bp < endb) {
3204 switch (*bp++) {
3205 case '/': /* possible comment */
3206 if (*bp == '\\' && bp[1] == '\n')
3207 newline_fix (bp);
3208 if (*bp == '*') {
3209 ip->bufp = ++bp;
3210 bp = skip_to_end_of_comment (ip, &ip->lineno);
3212 break;
3213 case '\"':
3214 case '\'':
3215 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno, 0, 0);
3216 break;
3217 case '\\':
3218 /* Char after backslash loses its special meaning. */
3219 if (bp < endb) {
3220 if (*bp == '\n')
3221 ++ip->lineno; /* But do update the line-count. */
3222 bp++;
3224 break;
3225 case '\n':
3226 ++ip->lineno;
3227 beg_of_line = bp;
3228 break;
3229 case '#':
3230 ip->bufp = bp - 1;
3232 /* # keyword: a # must be first nonblank char on the line */
3233 if (beg_of_line == 0)
3234 break;
3235 /* Scan from start of line, skipping whitespace, comments
3236 and backslash-newlines, and see if we reach this #.
3237 If not, this # is not special. */
3238 bp = beg_of_line;
3239 while (1) {
3240 if (is_hor_space[*bp])
3241 bp++;
3242 else if (*bp == '\\' && bp[1] == '\n')
3243 bp += 2;
3244 else if (*bp == '/' && bp[1] == '*') {
3245 bp += 2;
3246 while (!(*bp == '*' && bp[1] == '/')) {
3247 if (*bp == '\n')
3248 ip->lineno++;
3249 bp++;
3251 bp += 2;
3253 else break;
3255 if (bp != ip->bufp) {
3256 bp = ip->bufp + 1; /* Reset bp to after the #. */
3257 break;
3260 bp = ip->bufp + 1; /* Point after '#'. */
3262 /* Skip whitespace and \-newline. */
3263 while (1) {
3264 if (is_hor_space[*bp])
3265 bp++;
3266 else if (*bp == '\\' && bp[1] == '\n')
3267 bp += 2;
3268 else if (*bp == '/' && bp[1] == '*') {
3269 bp += 2;
3270 while (!(*bp == '*' && bp[1] == '/'))
3271 bp++;
3272 bp += 2;
3274 else break;
3277 cp = bp;
3279 /* Now find end of directive name.
3280 If we encounter a backslash-newline, exchange it with any following
3281 symbol-constituents so that we end up with a contiguous name. */
3283 while (1) {
3284 if (is_idchar[*bp])
3285 bp++;
3286 else {
3287 if (*bp == '\\' && bp[1] == '\n')
3288 name_newline_fix (bp);
3289 if (is_idchar[*bp])
3290 bp++;
3291 else break;
3295 for (kt = directive_table; kt->length >= 0; kt++) {
3296 IF_STACK_FRAME *temp;
3297 if (strncmp ((char *)cp, kt->name, kt->length) == 0
3298 && !is_idchar[cp[kt->length]]) {
3300 /* If we are asked to return on next directive,
3301 do so now. */
3302 if (any)
3303 return;
3305 switch (kt->type) {
3306 case T_IF:
3307 case T_IFDEF:
3308 case T_IFNDEF:
3309 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
3310 temp->next = if_stack;
3311 if_stack = temp;
3312 temp->lineno = ip->lineno;
3313 temp->fname = ip->fname;
3314 temp->type = kt->type;
3315 break;
3316 case T_ELSE:
3317 case T_ENDIF:
3318 case T_ELIF:
3319 if (if_stack == instack[indepth].if_stack) {
3320 error ("#%s not within a conditional", kt->name);
3321 break;
3323 else if (if_stack == save_if_stack)
3324 return; /* found what we came for */
3326 if (kt->type != T_ENDIF) {
3327 if (if_stack->type == T_ELSE)
3328 error ("#else or #elif after #else");
3329 if_stack->type = kt->type;
3330 break;
3333 temp = if_stack;
3334 if_stack = if_stack->next;
3335 free (temp);
3336 break;
3338 default:
3339 /* Anything else is ignored. */
3340 break;
3342 break;
3347 ip->bufp = bp;
3348 /* after this returns, rescan will exit because ip->bufp
3349 now points to the end of the buffer.
3350 rescan is responsible for the error message also. */
3354 * handle a #else directive. Do this by just continuing processing
3355 * without changing if_stack ; this is so that the error message
3356 * for missing #endif's etc. will point to the original #if. It
3357 * is possible that something different would be better.
3359 void
3360 do_else (buf, limit, op, keyword)
3361 U_CHAR *buf ATTRIBUTE_UNUSED;
3362 U_CHAR *limit ATTRIBUTE_UNUSED;
3363 FILE_BUF *op;
3364 struct directive *keyword ATTRIBUTE_UNUSED;
3366 FILE_BUF *ip = &instack[indepth];
3368 if (if_stack == instack[indepth].if_stack) {
3369 error ("#else not within a conditional");
3370 return;
3371 } else {
3372 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
3373 error ("#else after #else");
3374 fprintf (stderr, " (matches line %d", if_stack->lineno);
3375 if (strcmp (if_stack->fname, ip->fname) != 0)
3376 fprintf (stderr, ", file %s", if_stack->fname);
3377 fprintf (stderr, ")\n");
3379 if_stack->type = T_ELSE;
3382 if (if_stack->if_succeeded)
3383 skip_if_group (ip, 0);
3384 else {
3385 ++if_stack->if_succeeded; /* continue processing input */
3386 output_line_command (ip, op, 1, same_file);
3391 * unstack after #endif command
3393 void
3394 do_endif (buf, limit, op, keyword)
3395 U_CHAR *buf ATTRIBUTE_UNUSED;
3396 U_CHAR *limit ATTRIBUTE_UNUSED;
3397 FILE_BUF *op;
3398 struct directive *keyword ATTRIBUTE_UNUSED;
3400 if (if_stack == instack[indepth].if_stack)
3401 error ("unbalanced #endif");
3402 else {
3403 IF_STACK_FRAME *temp = if_stack;
3404 if_stack = if_stack->next;
3405 free (temp);
3406 output_line_command (&instack[indepth], op, 1, same_file);
3411 * Skip a comment, assuming the input ptr immediately follows the
3412 * initial slash-star. Bump line counter as necessary.
3413 * (The canonical line counter is &ip->lineno).
3414 * Don't use this routine (or the next one) if bumping the line
3415 * counter is not sufficient to deal with newlines in the string.
3417 U_CHAR *
3418 skip_to_end_of_comment (ip, line_counter)
3419 register FILE_BUF *ip;
3420 int *line_counter; /* place to remember newlines, or NULL */
3422 register U_CHAR *limit = ip->buf + ip->length;
3423 register U_CHAR *bp = ip->bufp;
3424 FILE_BUF *op = &outbuf; /* JF */
3425 int output = put_out_comments && !line_counter;
3427 /* JF this line_counter stuff is a crock to make sure the
3428 comment is only put out once, no matter how many times
3429 the comment is skipped. It almost works */
3430 if (output) {
3431 *op->bufp++ = '/';
3432 *op->bufp++ = '*';
3434 while (bp < limit) {
3435 if (output)
3436 *op->bufp++ = *bp;
3437 switch (*bp++) {
3438 case '/':
3439 if (warn_comments && bp < limit && *bp == '*')
3440 warning("`/*' within comment");
3441 break;
3442 case '\n':
3443 if (line_counter != NULL)
3444 ++*line_counter;
3445 if (output)
3446 ++op->lineno;
3447 break;
3448 case '*':
3449 if (*bp == '\\' && bp[1] == '\n')
3450 newline_fix (bp);
3451 if (*bp == '/') {
3452 if (output)
3453 *op->bufp++ = '/';
3454 ip->bufp = ++bp;
3455 return bp;
3457 break;
3460 ip->bufp = bp;
3461 return bp;
3465 * Skip over a quoted string. BP points to the opening quote.
3466 * Returns a pointer after the closing quote. Don't go past LIMIT.
3467 * START_LINE is the line number of the starting point (but it need
3468 * not be valid if the starting point is inside a macro expansion).
3470 * The input stack state is not changed.
3472 * If COUNT_NEWLINES is nonzero, it points to an int to increment
3473 * for each newline passed.
3475 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
3476 * if we pass a backslash-newline.
3478 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
3480 U_CHAR *
3481 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
3482 register U_CHAR *bp;
3483 register U_CHAR *limit;
3484 int start_line;
3485 int *count_newlines;
3486 int *backslash_newlines_p;
3487 int *eofp;
3489 register U_CHAR c, match;
3491 match = *bp++;
3492 while (1) {
3493 if (bp >= limit) {
3494 error_with_line (line_for_error (start_line),
3495 "unterminated string or character constant");
3496 if (eofp)
3497 *eofp = 1;
3498 break;
3500 c = *bp++;
3501 if (c == '\\') {
3502 while (*bp == '\\' && bp[1] == '\n') {
3503 if (backslash_newlines_p)
3504 *backslash_newlines_p = 1;
3505 if (count_newlines)
3506 ++*count_newlines;
3507 bp += 2;
3509 if (*bp == '\n' && count_newlines) {
3510 if (backslash_newlines_p)
3511 *backslash_newlines_p = 1;
3512 ++*count_newlines;
3514 bp++;
3515 } else if (c == '\n') {
3516 /* Unterminated strings and character constants are 'legal'. */
3517 bp--; /* Don't consume the newline. */
3518 if (eofp)
3519 *eofp = 1;
3520 break;
3521 } else if (c == match)
3522 break;
3524 return bp;
3528 * write out a #line command, for instance, after an #include file.
3529 * If CONDITIONAL is nonzero, we can omit the #line if it would
3530 * appear to be a no-op, and we can output a few newlines instead
3531 * if we want to increase the line number by a small amount.
3532 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
3535 void
3536 output_line_command (ip, op, conditional, file_change)
3537 FILE_BUF *ip, *op;
3538 int conditional;
3539 enum file_change_code file_change;
3541 int len;
3542 char line_cmd_buf[500];
3544 if (no_line_commands
3545 || ip->fname == NULL
3546 || no_output) {
3547 op->lineno = ip->lineno;
3548 return;
3551 if (conditional) {
3552 if (ip->lineno == op->lineno)
3553 return;
3555 /* If the inherited line number is a little too small,
3556 output some newlines instead of a #line command. */
3557 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
3558 check_expand (op, 10);
3559 while (ip->lineno > op->lineno) {
3560 *op->bufp++ = '\n';
3561 op->lineno++;
3563 return;
3567 sprintf (line_cmd_buf, "# %d \"%s\"", ip->lineno, ip->fname);
3568 if (file_change != same_file)
3569 strcat (line_cmd_buf, file_change == enter_file ? " 1" : " 2");
3570 len = strlen (line_cmd_buf);
3571 line_cmd_buf[len++] = '\n';
3572 check_expand (op, len + 1);
3573 if (op->bufp > op->buf && op->bufp[-1] != '\n')
3574 *op->bufp++ = '\n';
3575 memcpy (op->bufp, line_cmd_buf, len);
3576 op->bufp += len;
3577 op->lineno = ip->lineno;
3581 /* Expand a macro call.
3582 HP points to the symbol that is the macro being called.
3583 Put the result of expansion onto the input stack
3584 so that subsequent input by our caller will use it.
3586 If macro wants arguments, caller has already verified that
3587 an argument list follows; arguments come from the input stack. */
3589 void
3590 macroexpand (hp, op)
3591 HASHNODE *hp;
3592 FILE_BUF *op;
3594 int nargs;
3595 DEFINITION *defn = hp->value.defn;
3596 register U_CHAR *xbuf;
3597 int xbuf_len;
3598 int start_line = instack[indepth].lineno;
3600 CHECK_DEPTH (return;);
3602 /* it might not actually be a macro. */
3603 if (hp->type != T_MACRO) {
3604 special_symbol (hp, op);
3605 return;
3608 nargs = defn->nargs;
3610 if (nargs >= 0) {
3611 register int i;
3612 struct argdata *args;
3613 const char *parse_error = 0;
3615 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
3617 for (i = 0; i < nargs; i++) {
3618 args[i].raw = args[i].expanded = (U_CHAR *) "";
3619 args[i].raw_length = args[i].expand_length
3620 = args[i].stringified_length = 0;
3621 args[i].free1 = args[i].free2 = 0;
3624 /* Parse all the macro args that are supplied. I counts them.
3625 The first NARGS args are stored in ARGS.
3626 The rest are discarded. */
3627 i = 0;
3628 do {
3629 /* Discard the open-parenthesis or comma before the next arg. */
3630 ++instack[indepth].bufp;
3631 parse_error
3632 = macarg ((i < nargs || (nargs == 0 && i == 0)) ? &args[i] : 0);
3633 if (parse_error)
3635 error_with_line (line_for_error (start_line), parse_error);
3636 break;
3638 i++;
3639 } while (*instack[indepth].bufp != ')');
3641 /* If we got one arg but it was just whitespace, call that 0 args. */
3642 if (i == 1) {
3643 register U_CHAR *bp = args[0].raw;
3644 register U_CHAR *lim = bp + args[0].raw_length;
3645 while (bp != lim && is_space[*bp]) bp++;
3646 if (bp == lim)
3647 i = 0;
3650 if (nargs == 0 && i > 0)
3651 error ("arguments given to macro `%s'", hp->name);
3652 else if (i < nargs) {
3653 /* traditional C allows foo() if foo wants one argument. */
3654 if (nargs == 1 && i == 0)
3656 else if (i == 0)
3657 error ("no args to macro `%s'", hp->name);
3658 else if (i == 1)
3659 error ("only 1 arg to macro `%s'", hp->name);
3660 else
3661 error ("only %d args to macro `%s'", i, hp->name);
3662 } else if (i > nargs)
3663 error ("too many (%d) args to macro `%s'", i, hp->name);
3665 /* Swallow the closeparen. */
3666 ++instack[indepth].bufp;
3668 /* If macro wants zero args, we parsed the arglist for checking only.
3669 Read directly from the macro definition. */
3670 if (nargs == 0) {
3671 xbuf = defn->expansion;
3672 xbuf_len = defn->length;
3673 } else {
3674 register U_CHAR *exp = defn->expansion;
3675 register int offset; /* offset in expansion,
3676 copied a piece at a time */
3677 register int totlen; /* total amount of exp buffer filled so far */
3679 register struct reflist *ap;
3681 /* Macro really takes args. Compute the expansion of this call. */
3683 /* Compute length in characters of the macro's expansion. */
3684 xbuf_len = defn->length;
3685 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
3686 if (ap->stringify)
3687 xbuf_len += args[ap->argno].stringified_length;
3688 else
3689 xbuf_len += args[ap->argno].raw_length;
3692 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
3694 /* Generate in XBUF the complete expansion
3695 with arguments substituted in.
3696 TOTLEN is the total size generated so far.
3697 OFFSET is the index in the definition
3698 of where we are copying from. */
3699 offset = totlen = 0;
3700 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
3701 register struct argdata *arg = &args[ap->argno];
3703 for (i = 0; i < ap->nchars; i++)
3704 xbuf[totlen++] = exp[offset++];
3706 if (ap->stringify != 0) {
3707 int arglen = arg->raw_length;
3708 int escaped = 0;
3709 int in_string = 0;
3710 int c;
3711 i = 0;
3712 while (i < arglen
3713 && (c = arg->raw[i], is_space[c]))
3714 i++;
3715 while (i < arglen
3716 && (c = arg->raw[arglen - 1], is_space[c]))
3717 arglen--;
3718 for (; i < arglen; i++) {
3719 c = arg->raw[i];
3721 /* Special markers Newline Space
3722 generate nothing for a stringified argument. */
3723 if (c == '\n' && arg->raw[i+1] != '\n') {
3724 i++;
3725 continue;
3728 /* Internal sequences of whitespace are replaced by one space
3729 except within an string or char token. */
3730 if (! in_string
3731 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
3732 while (1) {
3733 /* Note that Newline Space does occur within whitespace
3734 sequences; consider it part of the sequence. */
3735 if (c == '\n' && is_space[arg->raw[i+1]])
3736 i += 2;
3737 else if (c != '\n' && is_space[c])
3738 i++;
3739 else break;
3740 c = arg->raw[i];
3742 i--;
3743 c = ' ';
3746 if (escaped)
3747 escaped = 0;
3748 else {
3749 if (c == '\\')
3750 escaped = 1;
3751 if (in_string) {
3752 if (c == in_string)
3753 in_string = 0;
3754 } else if (c == '\"' || c == '\'')
3755 in_string = c;
3758 /* Escape these chars */
3759 if (c == '\"' || (in_string && c == '\\'))
3760 xbuf[totlen++] = '\\';
3761 if (isprint (c))
3762 xbuf[totlen++] = c;
3763 else {
3764 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
3765 totlen += 4;
3768 } else {
3769 U_CHAR *p1 = arg->raw;
3770 U_CHAR *l1 = p1 + arg->raw_length;
3772 if (ap->raw_before) {
3773 while (p1 != l1 && is_space[*p1]) p1++;
3774 while (p1 != l1 && is_idchar[*p1])
3775 xbuf[totlen++] = *p1++;
3776 /* Delete any no-reexpansion marker that follows
3777 an identifier at the beginning of the argument
3778 if the argument is concatenated with what precedes it. */
3779 if (p1[0] == '\n' && p1[1] == '-')
3780 p1 += 2;
3782 if (ap->raw_after) {
3783 /* Arg is concatenated after: delete trailing whitespace,
3784 whitespace markers, and no-reexpansion markers. */
3785 while (p1 != l1) {
3786 if (is_space[l1[-1]]) l1--;
3787 else if (l1[-1] == '-') {
3788 U_CHAR *p2 = l1 - 1;
3789 /* If a `-' is preceded by an odd number of newlines then it
3790 and the last newline are a no-reexpansion marker. */
3791 while (p2 != p1 && p2[-1] == '\n') p2--;
3792 if ((l1 - 1 - p2) & 1) {
3793 l1 -= 2;
3795 else break;
3797 else break;
3800 memmove (xbuf + totlen, p1, l1 - p1);
3801 totlen += l1 - p1;
3804 if (totlen > xbuf_len)
3805 abort ();
3808 /* if there is anything left of the definition
3809 after handling the arg list, copy that in too. */
3811 for (i = offset; i < defn->length; i++)
3812 xbuf[totlen++] = exp[i];
3814 xbuf[totlen] = 0;
3815 xbuf_len = totlen;
3817 for (i = 0; i < nargs; i++) {
3818 if (args[i].free1 != 0)
3819 free (args[i].free1);
3820 if (args[i].free2 != 0)
3821 free (args[i].free2);
3824 } else {
3825 xbuf = defn->expansion;
3826 xbuf_len = defn->length;
3829 /* Now put the expansion on the input stack
3830 so our caller will commence reading from it. */
3832 register FILE_BUF *ip2;
3834 ip2 = &instack[++indepth];
3836 ip2->fname = 0;
3837 ip2->lineno = 0;
3838 ip2->buf = xbuf;
3839 ip2->length = xbuf_len;
3840 ip2->bufp = xbuf;
3841 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
3842 ip2->macro = hp;
3843 ip2->if_stack = if_stack;
3848 * Parse a macro argument and store the info on it into *ARGPTR.
3849 * Return nonzero to indicate a syntax error.
3852 const char *
3853 macarg (argptr)
3854 register struct argdata *argptr;
3856 FILE_BUF *ip = &instack[indepth];
3857 int paren = 0;
3858 int newlines = 0;
3859 int comments = 0;
3861 /* Try to parse as much of the argument as exists at this
3862 input stack level. */
3863 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
3864 &paren, &newlines, &comments);
3866 /* If we find the end of the argument at this level,
3867 set up *ARGPTR to point at it in the input stack. */
3868 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
3869 && bp != ip->buf + ip->length) {
3870 if (argptr != 0) {
3871 argptr->raw = ip->bufp;
3872 argptr->raw_length = bp - ip->bufp;
3874 ip->bufp = bp;
3875 } else {
3876 /* This input stack level ends before the macro argument does.
3877 We must pop levels and keep parsing.
3878 Therefore, we must allocate a temporary buffer and copy
3879 the macro argument into it. */
3880 int bufsize = bp - ip->bufp;
3881 int extra = newlines;
3882 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
3883 int final_start = 0;
3885 memcpy (buffer, ip->bufp, bufsize);
3886 ip->bufp = bp;
3887 ip->lineno += newlines;
3889 while (bp == ip->buf + ip->length) {
3890 if (instack[indepth].macro == 0) {
3891 free (buffer);
3892 return "unterminated macro call";
3894 ip->macro->type = T_MACRO;
3895 if (ip->free_ptr)
3896 free (ip->free_ptr);
3897 ip = &instack[--indepth];
3898 newlines = 0;
3899 comments = 0;
3900 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
3901 &newlines, &comments);
3902 final_start = bufsize;
3903 bufsize += bp - ip->bufp;
3904 extra += newlines;
3905 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
3906 memcpy (buffer + bufsize - (bp - ip->bufp), ip->bufp, bp - ip->bufp);
3907 ip->bufp = bp;
3908 ip->lineno += newlines;
3911 /* Now, if arg is actually wanted, record its raw form,
3912 discarding comments and duplicating newlines in whatever
3913 part of it did not come from a macro expansion.
3914 EXTRA space has been preallocated for duplicating the newlines.
3915 FINAL_START is the index of the start of that part. */
3916 if (argptr != 0) {
3917 argptr->raw = buffer;
3918 argptr->raw_length = bufsize;
3919 argptr->free1 = buffer;
3920 argptr->newlines = newlines;
3921 argptr->comments = comments;
3922 if ((newlines || comments) && ip->fname != 0)
3923 argptr->raw_length
3924 = final_start +
3925 discard_comments (argptr->raw + final_start,
3926 argptr->raw_length - final_start,
3927 newlines);
3928 argptr->raw[argptr->raw_length] = 0;
3929 if (argptr->raw_length > bufsize + extra)
3930 abort ();
3934 /* If we are not discarding this argument,
3935 macroexpand it and compute its length as stringified.
3936 All this info goes into *ARGPTR. */
3938 if (argptr != 0) {
3939 FILE_BUF obuf;
3940 register U_CHAR *buf, *lim;
3941 register int totlen;
3943 obuf = expand_to_temp_buffer (argptr->raw,
3944 argptr->raw + argptr->raw_length,
3947 argptr->expanded = obuf.buf;
3948 argptr->expand_length = obuf.length;
3949 argptr->free2 = obuf.buf;
3951 buf = argptr->raw;
3952 lim = buf + argptr->raw_length;
3954 totlen = 0;
3955 while (buf != lim) {
3956 register U_CHAR c = *buf++;
3957 totlen++;
3958 /* Internal sequences of whitespace are replaced by one space
3959 in most cases, but not always. So count all the whitespace
3960 in case we need to keep it all. */
3961 if (c == '\"' || c == '\\') /* escape these chars */
3962 totlen++;
3963 else if (!isprint (c))
3964 totlen += 3;
3966 argptr->stringified_length = totlen;
3968 return 0;
3971 /* Scan text from START (inclusive) up to LIMIT (exclusive),
3972 counting parens in *DEPTHPTR,
3973 and return if reach LIMIT
3974 or before a `)' that would make *DEPTHPTR negative
3975 or before a comma when *DEPTHPTR is zero.
3976 Single and double quotes are matched and termination
3977 is inhibited within them. Comments also inhibit it.
3978 Value returned is pointer to stopping place.
3980 Increment *NEWLINES each time a newline is passed.
3981 Set *COMMENTS to 1 if a comment is seen. */
3983 U_CHAR *
3984 macarg1 (start, limit, depthptr, newlines, comments)
3985 U_CHAR *start;
3986 register U_CHAR *limit;
3987 int *depthptr, *newlines, *comments;
3989 register U_CHAR *bp = start;
3991 while (bp < limit) {
3992 switch (*bp) {
3993 case '(':
3994 (*depthptr)++;
3995 break;
3996 case ')':
3997 if (--(*depthptr) < 0)
3998 return bp;
3999 break;
4000 case '\\':
4001 /* Traditionally, backslash makes following char not special. */
4002 if (bp + 1 < limit)
4004 bp++;
4005 /* But count source lines anyway. */
4006 if (*bp == '\n')
4007 ++*newlines;
4009 break;
4010 case '\n':
4011 ++*newlines;
4012 break;
4013 case '/':
4014 if (bp[1] == '\\' && bp[2] == '\n')
4015 newline_fix (bp + 1);
4016 if (bp[1] != '*' || bp + 1 >= limit)
4017 break;
4018 *comments = 1;
4019 bp += 2;
4020 while (bp + 1 < limit) {
4021 if (bp[0] == '*'
4022 && bp[1] == '\\' && bp[2] == '\n')
4023 newline_fix (bp + 1);
4024 if (bp[0] == '*' && bp[1] == '/')
4025 break;
4026 if (*bp == '\n') ++*newlines;
4027 bp++;
4029 bp += 1;
4030 break;
4031 case '\'':
4032 case '\"':
4034 int quotec;
4035 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
4036 if (*bp == '\\') {
4037 bp++;
4038 if (*bp == '\n')
4039 ++*newlines;
4040 while (*bp == '\\' && bp[1] == '\n') {
4041 bp += 2;
4043 } else if (*bp == '\n') {
4044 ++*newlines;
4045 if (quotec == '\'')
4046 break;
4050 break;
4051 case ',':
4052 if ((*depthptr) == 0)
4053 return bp;
4054 break;
4056 bp++;
4059 return bp;
4062 /* Discard comments and duplicate newlines
4063 in the string of length LENGTH at START,
4064 except inside of string constants.
4065 The string is copied into itself with its beginning staying fixed.
4067 NEWLINES is the number of newlines that must be duplicated.
4068 We assume that that much extra space is available past the end
4069 of the string. */
4072 discard_comments (start, length, newlines)
4073 U_CHAR *start;
4074 int length;
4075 int newlines;
4077 register U_CHAR *ibp;
4078 register U_CHAR *obp;
4079 register U_CHAR *limit;
4080 register int c;
4082 /* If we have newlines to duplicate, copy everything
4083 that many characters up. Then, in the second part,
4084 we will have room to insert the newlines
4085 while copying down.
4086 NEWLINES may actually be too large, because it counts
4087 newlines in string constants, and we don't duplicate those.
4088 But that does no harm. */
4089 if (newlines > 0) {
4090 ibp = start + length;
4091 obp = ibp + newlines;
4092 limit = start;
4093 while (limit != ibp)
4094 *--obp = *--ibp;
4097 ibp = start + newlines;
4098 limit = start + length + newlines;
4099 obp = start;
4101 while (ibp < limit) {
4102 *obp++ = c = *ibp++;
4103 switch (c) {
4104 case '\n':
4105 /* Duplicate the newline. */
4106 *obp++ = '\n';
4107 break;
4109 case '\\':
4110 if (*ibp == '\n') {
4111 obp--;
4112 ibp++;
4114 break;
4116 case '/':
4117 if (*ibp == '\\' && ibp[1] == '\n')
4118 newline_fix (ibp);
4119 /* Delete any comment. */
4120 if (ibp[0] != '*' || ibp + 1 >= limit)
4121 break;
4122 obp--;
4123 ibp++;
4124 while (ibp + 1 < limit) {
4125 if (ibp[0] == '*'
4126 && ibp[1] == '\\' && ibp[2] == '\n')
4127 newline_fix (ibp + 1);
4128 if (ibp[0] == '*' && ibp[1] == '/')
4129 break;
4130 ibp++;
4132 ibp += 2;
4133 break;
4135 case '\'':
4136 case '\"':
4137 /* Notice and skip strings, so that we don't
4138 think that comments start inside them,
4139 and so we don't duplicate newlines in them. */
4141 int quotec = c;
4142 while (ibp < limit) {
4143 *obp++ = c = *ibp++;
4144 if (c == quotec)
4145 break;
4146 if (c == '\n' && quotec == '\'')
4147 break;
4148 if (c == '\\' && ibp < limit) {
4149 while (*ibp == '\\' && ibp[1] == '\n')
4150 ibp += 2;
4151 *obp++ = *ibp++;
4155 break;
4159 return obp - start;
4163 /* Core error handling routine. */
4164 void
4165 v_message (mtype, line, msgid, ap)
4166 enum msgtype mtype;
4167 int line;
4168 const char *msgid;
4169 va_list ap;
4171 const char *fname = 0;
4172 int i;
4174 if (mtype == WARNING && inhibit_warnings)
4175 return;
4177 for (i = indepth; i >= 0; i--)
4178 if (instack[i].fname != NULL) {
4179 if (line == 0)
4180 line = instack[i].lineno;
4181 fname = instack[i].fname;
4182 break;
4185 if (fname)
4186 fprintf (stderr, "%s:%d: ", fname, line);
4187 else
4188 fprintf (stderr, "%s: ", progname);
4190 if (mtype == WARNING)
4191 fputs ("warning: ", stderr);
4193 vfprintf (stderr, msgid, ap);
4194 putc ('\n', stderr);
4196 if (mtype == ERROR)
4197 errors++;
4201 * error - print error message and increment count of errors.
4203 void
4204 error VPARAMS ((const char *msgid, ...))
4206 #ifndef ANSI_PROTOTYPES
4207 const char *msgid;
4208 #endif
4209 va_list ap;
4211 VA_START(ap, msgid);
4213 #ifndef ANSI_PROTOTYPES
4214 msgid = va_arg (ap, const char *);
4215 #endif
4217 v_message (ERROR, 0, msgid, ap);
4220 void
4221 error_with_line VPARAMS ((int line, const char *msgid, ...))
4223 #ifndef ANSI_PROTOTYPES
4224 int line;
4225 const char *msgid;
4226 #endif
4227 va_list ap;
4229 VA_START(ap, msgid);
4231 #ifndef ANSI_PROTOTYPES
4232 line = va_arg (ap, int);
4233 msgid = va_arg (ap, const char *);
4234 #endif
4236 v_message (ERROR, line, msgid, ap);
4239 /* Error including a message from `errno'. */
4240 void
4241 error_from_errno (name)
4242 const char *name;
4244 error ("%s: %s", name, strerror (errno));
4247 /* Print error message but don't count it. */
4248 void
4249 warning VPARAMS ((const char *msgid, ...))
4251 #ifndef ANSI_PROTOTYPES
4252 const char *msgid;
4253 #endif
4254 va_list ap;
4256 VA_START(ap, msgid);
4258 #ifndef ANSI_PROTOTYPES
4259 msgid = va_arg (ap, const char *);
4260 #endif
4262 v_message (WARNING, 0, msgid, ap);
4265 void
4266 fatal VPARAMS ((const char *msgid, ...))
4268 #ifndef ANSI_PROTOTYPES
4269 const char *msgid;
4270 #endif
4271 va_list ap;
4273 VA_START(ap, msgid);
4275 #ifndef ANSI_PROTOTYPES
4276 msgid = va_arg (ap, const char *);
4277 #endif
4279 v_message (FATAL, 0, msgid, ap);
4280 exit (FATAL_EXIT_CODE);
4283 /* More 'friendly' abort that prints the location at which we died. */
4284 void
4285 fancy_abort (line, func)
4286 int line;
4287 const char *func;
4289 if (!func)
4290 func = "?";
4292 fatal ("Internal error in \"%s\", at tradcpp.c:%d\n\
4293 Please submit a full bug report.\n\
4294 See %s for instructions.", func, line, GCCBUGURL);
4297 void
4298 perror_with_name (name)
4299 const char *name;
4301 fprintf (stderr, "%s: %s: %s\n", progname, name, strerror (errno));
4302 errors++;
4305 void
4306 pfatal_with_name (name)
4307 const char *name;
4309 perror_with_name (name);
4310 exit (FATAL_EXIT_CODE);
4313 /* Return the line at which an error occurred.
4314 The error is not necessarily associated with the current spot
4315 in the input stack, so LINE says where. LINE will have been
4316 copied from ip->lineno for the current input level.
4317 If the current level is for a file, we return LINE.
4318 But if the current level is not for a file, LINE is meaningless.
4319 In that case, we return the lineno of the innermost file. */
4321 line_for_error (line)
4322 int line;
4324 int i;
4325 int line1 = line;
4327 for (i = indepth; i >= 0; ) {
4328 if (instack[i].fname != 0)
4329 return line1;
4330 i--;
4331 if (i < 0)
4332 return 0;
4333 line1 = instack[i].lineno;
4335 return 0;
4339 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
4341 * As things stand, nothing is ever placed in the output buffer to be
4342 * removed again except when it's KNOWN to be part of an identifier,
4343 * so flushing and moving down everything left, instead of expanding,
4344 * should work ok.
4347 void
4348 grow_outbuf (obuf, needed)
4349 register FILE_BUF *obuf;
4350 register int needed;
4352 register U_CHAR *p;
4353 int minsize;
4355 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
4356 return;
4358 /* Make it at least twice as big as it is now. */
4359 obuf->length *= 2;
4360 /* Make it have at least 150% of the free space we will need. */
4361 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
4362 if (minsize > obuf->length)
4363 obuf->length = minsize;
4365 p = (U_CHAR *) xrealloc (obuf->buf, obuf->length);
4366 obuf->bufp = p + (obuf->bufp - obuf->buf);
4367 obuf->buf = p;
4370 /* Symbol table for macro names and special symbols */
4373 * install a name in the main hash table, even if it is already there.
4374 * name stops with first non alphanumeric, except leading '#'.
4375 * caller must check against redefinition if that is desired.
4376 * delete_macro () removes things installed by install () in fifo order.
4377 * this is important because of the `defined' special symbol used
4378 * in #if, and also if pushdef/popdef directives are ever implemented.
4380 * If LEN is >= 0, it is the length of the name.
4381 * Otherwise, compute the length by scanning the entire name.
4383 * If HASH is >= 0, it is the precomputed hash code.
4384 * Otherwise, compute the hash code.
4386 * caller must set the value, if any is desired.
4388 HASHNODE *
4389 install (name, len, type, hash)
4390 const U_CHAR *name;
4391 int len;
4392 enum node_type type;
4393 int hash;
4394 /* watch out here if sizeof (U_CHAR *) != sizeof (int) */
4396 register HASHNODE *hp;
4397 register int bucket;
4398 register const U_CHAR *p;
4399 U_CHAR *q;
4401 if (len < 0) {
4402 p = name;
4403 while (is_idchar[*p])
4404 p++;
4405 len = p - name;
4408 if (hash < 0)
4409 hash = hashf (name, len, HASHSIZE);
4411 hp = (HASHNODE *) xmalloc (sizeof (HASHNODE) + len + 1);
4412 bucket = hash;
4413 hp->bucket_hdr = &hashtab[bucket];
4414 hp->next = hashtab[bucket];
4415 hashtab[bucket] = hp;
4416 hp->prev = NULL;
4417 if (hp->next != NULL)
4418 hp->next->prev = hp;
4419 hp->type = type;
4420 hp->length = len;
4421 hp->name = q = ((U_CHAR *) hp) + sizeof (HASHNODE);
4422 memcpy (q, name, len);
4423 q[len] = 0;
4424 return hp;
4428 * find the most recent hash node for name name (ending with first
4429 * non-identifier char) installed by install
4431 * If LEN is >= 0, it is the length of the name.
4432 * Otherwise, compute the length by scanning the entire name.
4434 * If HASH is >= 0, it is the precomputed hash code.
4435 * Otherwise, compute the hash code.
4437 HASHNODE *
4438 lookup (name, len, hash)
4439 const U_CHAR *name;
4440 int len;
4441 int hash;
4443 register const U_CHAR *bp;
4444 register HASHNODE *bucket;
4446 if (len < 0) {
4447 for (bp = name; is_idchar[*bp]; bp++) ;
4448 len = bp - name;
4451 if (hash < 0)
4452 hash = hashf (name, len, HASHSIZE);
4454 bucket = hashtab[hash];
4455 while (bucket) {
4456 if (bucket->length == len
4457 && strncmp ((char *)bucket->name, (char *)name, len) == 0)
4458 return bucket;
4459 bucket = bucket->next;
4461 return NULL;
4465 * Delete a hash node. Some weirdness to free junk from macros.
4466 * More such weirdness will have to be added if you define more hash
4467 * types that need it.
4470 /* Note that the DEFINITION of a macro is removed from the hash table
4471 but its storage is not freed. This would be a storage leak
4472 except that it is not reasonable to keep undefining and redefining
4473 large numbers of macros many times.
4474 In any case, this is necessary, because a macro can be #undef'd
4475 in the middle of reading the arguments to a call to it.
4476 If #undef freed the DEFINITION, that would crash. */
4477 void
4478 delete_macro (hp)
4479 HASHNODE *hp;
4482 if (hp->prev != NULL)
4483 hp->prev->next = hp->next;
4484 if (hp->next != NULL)
4485 hp->next->prev = hp->prev;
4487 /* make sure that the bucket chain header that
4488 the deleted guy was on points to the right thing afterwards. */
4489 if (hp == *hp->bucket_hdr)
4490 *hp->bucket_hdr = hp->next;
4492 free (hp);
4496 * return hash function on name. must be compatible with the one
4497 * computed a step at a time, elsewhere
4500 hashf (name, len, hashsize)
4501 register const U_CHAR *name;
4502 register int len;
4503 int hashsize;
4505 register int r = 0;
4507 while (len--)
4508 r = HASHSTEP (r, *name++);
4510 return MAKE_POS (r) % hashsize;
4513 /* Dump all macro definitions as #defines to stdout. */
4515 void
4516 dump_all_macros ()
4518 int bucket;
4520 for (bucket = 0; bucket < HASHSIZE; bucket++) {
4521 register HASHNODE *hp;
4523 for (hp = hashtab[bucket]; hp; hp= hp->next) {
4524 if (hp->type == T_MACRO) {
4525 register DEFINITION *defn = hp->value.defn;
4526 struct reflist *ap;
4527 int offset;
4528 int concat;
4531 /* Print the definition of the macro HP. */
4533 printf ("#define %s", hp->name);
4534 if (defn->nargs >= 0) {
4535 int i;
4537 printf ("(");
4538 for (i = 0; i < defn->nargs; i++) {
4539 dump_arg_n (defn, i);
4540 if (i + 1 < defn->nargs)
4541 printf (", ");
4543 printf (")");
4546 printf (" ");
4548 offset = 0;
4549 concat = 0;
4550 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
4551 dump_defn_1 (defn->expansion, offset, ap->nchars);
4552 if (ap->nchars != 0)
4553 concat = 0;
4554 offset += ap->nchars;
4555 if (ap->stringify)
4556 printf (" #");
4557 if (ap->raw_before && !concat)
4558 printf (" ## ");
4559 concat = 0;
4560 dump_arg_n (defn, ap->argno);
4561 if (ap->raw_after) {
4562 printf (" ## ");
4563 concat = 1;
4566 dump_defn_1 (defn->expansion, offset, defn->length - offset);
4567 printf ("\n");
4573 /* Output to stdout a substring of a macro definition.
4574 BASE is the beginning of the definition.
4575 Output characters START thru LENGTH.
4576 Discard newlines outside of strings, thus
4577 converting funny-space markers to ordinary spaces. */
4578 void
4579 dump_defn_1 (base, start, length)
4580 U_CHAR *base;
4581 int start;
4582 int length;
4584 U_CHAR *p = base + start;
4585 U_CHAR *limit = base + start + length;
4587 while (p < limit) {
4588 if (*p != '\n')
4589 putchar (*p);
4590 else if (*p == '\"' || *p =='\'') {
4591 U_CHAR *p1 = skip_quoted_string (p, limit, 0, 0, 0, 0);
4592 fwrite (p, p1 - p, 1, stdout);
4593 p = p1 - 1;
4595 p++;
4599 /* Print the name of argument number ARGNUM of macro definition DEFN.
4600 Recall that DEFN->argnames contains all the arg names
4601 concatenated in reverse order with comma-space in between. */
4602 void
4603 dump_arg_n (defn, argnum)
4604 DEFINITION *defn;
4605 int argnum;
4607 register U_CHAR *p = defn->argnames;
4608 while (argnum + 1 < defn->nargs) {
4609 p = (U_CHAR *) strchr ((char *)p, ' ') + 1;
4610 argnum++;
4613 while (*p && *p != ',') {
4614 putchar (*p);
4615 p++;
4619 /* Initialize syntactic classifications of characters. */
4620 void
4621 initialize_char_syntax ()
4623 register int i;
4626 * Set up is_idchar and is_idstart tables. These should be
4627 * faster than saying (is_alpha (c) || c == '_'), etc.
4628 * Must do set up these things before calling any routines tthat
4629 * refer to them.
4631 for (i = 'a'; i <= 'z'; i++) {
4632 is_idchar[i - 'a' + 'A'] = 1;
4633 is_idchar[i] = 1;
4634 is_idstart[i - 'a' + 'A'] = 1;
4635 is_idstart[i] = 1;
4637 for (i = '0'; i <= '9'; i++)
4638 is_idchar[i] = 1;
4639 is_idchar['_'] = 1;
4640 is_idstart['_'] = 1;
4642 /* horizontal space table */
4643 is_hor_space[' '] = 1;
4644 is_hor_space['\t'] = 1;
4645 is_hor_space['\v'] = 1;
4646 is_hor_space['\f'] = 1;
4647 is_hor_space['\r'] = 1;
4649 is_space[' '] = 1;
4650 is_space['\t'] = 1;
4651 is_space['\v'] = 1;
4652 is_space['\f'] = 1;
4653 is_space['\n'] = 1;
4654 is_space['\r'] = 1;
4657 /* Initialize the built-in macros. */
4658 #define DSC(x) U x, sizeof x - 1
4659 #define install_spec(name, type) \
4660 install(DSC(name), type, -1);
4661 #define install_value(name, val) \
4662 hp = install(DSC(name), T_CONST, -1); hp->value.cpval = val;
4663 void
4664 initialize_builtins ()
4666 HASHNODE *hp;
4668 install_spec ("__BASE_FILE__", T_BASE_FILE);
4669 install_spec ("__DATE__", T_DATE);
4670 install_spec ("__FILE__", T_FILE);
4671 install_spec ("__TIME__", T_TIME);
4672 install_spec ("__VERSION__", T_VERSION);
4673 install_spec ("__INCLUDE_LEVEL__", T_INCLUDE_LEVEL);
4674 install_spec ("__LINE__", T_SPECLINE);
4676 install_value ("__SIZE_TYPE__", SIZE_TYPE);
4677 install_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE);
4678 install_value ("__WCHAR_TYPE__", WCHAR_TYPE);
4679 install_value ("__REGISTER_PREFIX__", REGISTER_PREFIX);
4680 install_value ("__USER_LABEL_PREFIX__", user_label_prefix);
4682 #undef DSC
4683 #undef install_spec
4684 #undef install_value
4687 * process a given definition string, for initialization
4688 * If STR is just an identifier, define it with value 1.
4689 * If STR has anything after the identifier, then it should
4690 * be identifier-space-definition.
4692 void
4693 make_definition (str)
4694 U_CHAR *str;
4696 FILE_BUF *ip;
4697 struct directive *kt;
4698 U_CHAR *buf, *p;
4700 buf = str;
4701 p = str;
4702 while (is_idchar[*p]) p++;
4703 if (p == str) {
4704 error ("malformed option `-D %s'", str);
4705 return;
4707 if (*p == 0) {
4708 buf = (U_CHAR *) alloca (p - buf + 4);
4709 strcpy ((char *)buf, (char *)str);
4710 strcat ((char *)buf, " 1");
4711 } else if (*p != ' ') {
4712 error ("malformed option `-D %s'", str);
4713 return;
4714 } else {
4715 U_CHAR *q;
4716 /* Copy the entire option so we can modify it. */
4717 buf = (U_CHAR *) alloca (2 * strlen ((char *)str) + 1);
4718 strncpy ((char *)buf, (char *)str, p - str);
4719 /* Change the = to a space. */
4720 buf[p - str] = ' ';
4721 /* Scan for any backslash-newline and remove it. */
4722 p++;
4723 q = &buf[p - str];
4724 while (*p) {
4725 if (*p == '\\' && p[1] == '\n')
4726 p += 2;
4727 /* Change newline chars into newline-markers. */
4728 else if (*p == '\n')
4730 *q++ = '\n';
4731 *q++ = '\n';
4732 p++;
4734 else
4735 *q++ = *p++;
4737 *q = 0;
4740 ip = &instack[++indepth];
4741 ip->fname = "*Initialization*";
4743 ip->buf = ip->bufp = buf;
4744 ip->length = strlen ((char *)buf);
4745 ip->lineno = 1;
4746 ip->macro = 0;
4747 ip->free_ptr = 0;
4748 ip->if_stack = if_stack;
4750 for (kt = directive_table; kt->type != T_DEFINE; kt++)
4753 /* pass NULL as output ptr to do_define since we KNOW it never
4754 does any output.... */
4755 do_define (buf, buf + ip->length, NULL, kt);
4756 --indepth;
4759 /* JF, this does the work for the -U option */
4760 void
4761 make_undef (str)
4762 U_CHAR *str;
4764 FILE_BUF *ip;
4765 struct directive *kt;
4767 ip = &instack[++indepth];
4768 ip->fname = "*undef*";
4770 ip->buf = ip->bufp = str;
4771 ip->length = strlen ((char *)str);
4772 ip->lineno = 1;
4773 ip->macro = 0;
4774 ip->free_ptr = 0;
4775 ip->if_stack = if_stack;
4777 for (kt = directive_table; kt->type != T_UNDEF; kt++)
4780 do_undef (str, str + ip->length, NULL, kt);
4781 --indepth;
4784 /* Add output to `deps_buffer' for the -M switch.
4785 STRING points to the text to be output.
4786 SIZE is the number of bytes, or 0 meaning output until a null.
4787 If SIZE is nonzero, we break the line first, if it is long enough. */
4788 void
4789 deps_output (string, size)
4790 const char *string;
4791 int size;
4793 #ifndef MAX_OUTPUT_COLUMNS
4794 #define MAX_OUTPUT_COLUMNS 75
4795 #endif
4796 if (size != 0 && deps_column != 0
4797 && size + deps_column > MAX_OUTPUT_COLUMNS) {
4798 deps_output ("\\\n ", 0);
4799 deps_column = 0;
4802 if (size == 0)
4803 size = strlen (string);
4805 if (deps_size + size + 1 > deps_allocated_size) {
4806 deps_allocated_size = deps_size + size + 50;
4807 deps_allocated_size *= 2;
4808 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
4810 memcpy (&deps_buffer[deps_size], string, size);
4811 deps_size += size;
4812 deps_column += size;
4813 deps_buffer[deps_size] = 0;
4816 /* Get the file-mode and data size of the file open on FD
4817 and store them in *MODE_POINTER and *SIZE_POINTER. */
4820 file_size_and_mode (fd, mode_pointer, size_pointer)
4821 int fd;
4822 int *mode_pointer;
4823 long *size_pointer;
4825 struct stat sbuf;
4827 if (fstat (fd, &sbuf) < 0) return -1;
4828 if (mode_pointer) *mode_pointer = sbuf.st_mode;
4829 if (size_pointer) *size_pointer = sbuf.st_size;
4830 return 0;