H
[official-gcc.git] / gcc / cpplib.c
blobb56790ec32b554d29ef58a21ef6e051c0684b79b
1 /* CPP Library.
2 Copyright (C) 1986, 87, 89, 92-97, 1998 Free Software Foundation, Inc.
3 Contributed by Per Bothner, 1994-95.
4 Based on CCCP program by Paul Rubin, June 1986
5 Adapted to ANSI C, Richard Stallman, Jan 1987
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
21 #include "config.h"
22 #include "system.h"
24 #ifndef STDC_VALUE
25 #define STDC_VALUE 1
26 #endif
28 #include <signal.h>
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
32 #endif
34 #ifdef HAVE_SYS_RESOURCE_H
35 # include <sys/resource.h>
36 #endif
38 #include "gansidecl.h"
39 #include "cpplib.h"
40 #include "cpphash.h"
42 #ifndef GET_ENV_PATH_LIST
43 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
44 #endif
46 extern char *update_path PARAMS ((char *, char *));
48 #undef MIN
49 #undef MAX
50 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
51 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
53 /* Find the largest host integer type and set its size and type.
54 Watch out: on some crazy hosts `long' is shorter than `int'. */
56 #ifndef HOST_WIDE_INT
57 # if HAVE_INTTYPES_H
58 # include <inttypes.h>
59 # define HOST_WIDE_INT intmax_t
60 # else
61 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT \
62 && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
63 # define HOST_WIDE_INT int
64 # else
65 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG \
66 || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
67 # define HOST_WIDE_INT long
68 # else
69 # define HOST_WIDE_INT long long
70 # endif
71 # endif
72 # endif
73 #endif
75 #ifndef S_ISREG
76 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
77 #endif
79 #ifndef S_ISDIR
80 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
81 #endif
83 /* By default, colon separates directories in a path. */
84 #ifndef PATH_SEPARATOR
85 #define PATH_SEPARATOR ':'
86 #endif
88 #ifndef STANDARD_INCLUDE_DIR
89 #define STANDARD_INCLUDE_DIR "/usr/include"
90 #endif
91 #ifndef INCLUDE_LEN_FUDGE
92 #define INCLUDE_LEN_FUDGE 0
93 #endif
95 /* Symbols to predefine. */
97 #ifdef CPP_PREDEFINES
98 static char *predefs = CPP_PREDEFINES;
99 #else
100 static char *predefs = "";
101 #endif
103 /* We let tm.h override the types used here, to handle trivial differences
104 such as the choice of unsigned int or long unsigned int for size_t.
105 When machines start needing nontrivial differences in the size type,
106 it would be best to do something here to figure out automatically
107 from other information what type to use. */
109 /* The string value for __SIZE_TYPE__. */
111 #ifndef SIZE_TYPE
112 #define SIZE_TYPE "long unsigned int"
113 #endif
115 /* The string value for __PTRDIFF_TYPE__. */
117 #ifndef PTRDIFF_TYPE
118 #define PTRDIFF_TYPE "long int"
119 #endif
121 /* The string value for __WCHAR_TYPE__. */
123 #ifndef WCHAR_TYPE
124 #define WCHAR_TYPE "int"
125 #endif
126 #define CPP_WCHAR_TYPE(PFILE) \
127 (CPP_OPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
129 /* The string value for __USER_LABEL_PREFIX__ */
131 #ifndef USER_LABEL_PREFIX
132 #define USER_LABEL_PREFIX ""
133 #endif
135 /* The string value for __REGISTER_PREFIX__ */
137 #ifndef REGISTER_PREFIX
138 #define REGISTER_PREFIX ""
139 #endif
141 /* In the definition of a #assert name, this structure forms
142 a list of the individual values asserted.
143 Each value is itself a list of "tokens".
144 These are strings that are compared by name. */
146 struct tokenlist_list {
147 struct tokenlist_list *next;
148 struct arglist *tokens;
151 struct assertion_hashnode {
152 struct assertion_hashnode *next; /* double links for easy deletion */
153 struct assertion_hashnode *prev;
154 /* also, a back pointer to this node's hash
155 chain is kept, in case the node is the head
156 of the chain and gets deleted. */
157 struct assertion_hashnode **bucket_hdr;
158 int length; /* length of token, for quick comparison */
159 U_CHAR *name; /* the actual name */
160 /* List of token-sequences. */
161 struct tokenlist_list *value;
164 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
165 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
167 #define PEEKN(N) (CPP_BUFFER (pfile)->rlimit - CPP_BUFFER (pfile)->cur >= (N) ? CPP_BUFFER (pfile)->cur[N] : EOF)
168 #define FORWARD(N) CPP_FORWARD (CPP_BUFFER (pfile), (N))
169 #define GETC() CPP_BUF_GET (CPP_BUFFER (pfile))
170 #define PEEKC() CPP_BUF_PEEK (CPP_BUFFER (pfile))
171 /* CPP_IS_MACRO_BUFFER is true if the buffer contains macro expansion.
172 (Note that it is false while we're expanding marco *arguments*.) */
173 #define CPP_IS_MACRO_BUFFER(PBUF) ((PBUF)->cleanup == macro_cleanup)
175 /* Move all backslash-newline pairs out of embarrassing places.
176 Exchange all such pairs following BP
177 with any potentially-embarrassing characters that follow them.
178 Potentially-embarrassing characters are / and *
179 (because a backslash-newline inside a comment delimiter
180 would cause it not to be recognized). */
182 #define NEWLINE_FIX \
183 do {while (PEEKC() == '\\' && PEEKN(1) == '\n') FORWARD(2); } while(0)
185 /* Same, but assume we've already read the potential '\\' into C. */
186 #define NEWLINE_FIX1(C) do { \
187 while ((C) == '\\' && PEEKC() == '\n') { FORWARD(1); (C) = GETC(); }\
188 } while(0)
190 struct cpp_pending {
191 struct cpp_pending *next;
192 char *cmd;
193 char *arg;
196 /* Forward declarations. */
198 char *xmalloc ();
199 extern void cpp_hash_cleanup PARAMS ((cpp_reader *));
201 static char *my_strerror PROTO ((int));
202 static void add_import PROTO ((cpp_reader *, int, char *));
203 static void append_include_chain PROTO ((cpp_reader *,
204 struct file_name_list *,
205 struct file_name_list *));
206 static void make_assertion PROTO ((cpp_reader *, char *, U_CHAR *));
207 static void path_include PROTO ((cpp_reader *, char *));
208 static void initialize_builtins PROTO ((cpp_reader *));
209 static void initialize_char_syntax PROTO ((struct cpp_options *));
210 #if 0
211 static void trigraph_pcp ();
212 #endif
213 static int finclude PROTO ((cpp_reader *, int, char *,
214 int, struct file_name_list *));
215 static void validate_else PROTO ((cpp_reader *, char *));
216 static int comp_def_part PROTO ((int, U_CHAR *, int, U_CHAR *,
217 int, int));
218 #ifdef abort
219 extern void fancy_abort ();
220 #endif
221 static int lookup_import PROTO ((cpp_reader *, char *,
222 struct file_name_list *));
223 static int redundant_include_p PROTO ((cpp_reader *, char *));
224 static int is_system_include PROTO ((cpp_reader *, char *));
225 static struct file_name_map *read_name_map PROTO ((cpp_reader *, char *));
226 static char *read_filename_string PROTO ((int, FILE *));
227 static int open_include_file PROTO ((cpp_reader *, char *,
228 struct file_name_list *));
229 static int check_macro_name PROTO ((cpp_reader *, U_CHAR *, char *));
230 static int compare_defs PROTO ((cpp_reader *,
231 DEFINITION *, DEFINITION *));
232 static int compare_token_lists PROTO ((struct arglist *,
233 struct arglist *));
234 static HOST_WIDE_INT eval_if_expression PROTO ((cpp_reader *, U_CHAR *, int));
235 static int change_newlines PROTO ((U_CHAR *, int));
236 static struct arglist *read_token_list PROTO ((cpp_reader *, int *));
237 static void free_token_list PROTO ((struct arglist *));
238 static int safe_read PROTO ((int, char *, int));
239 static void push_macro_expansion PARAMS ((cpp_reader *,
240 U_CHAR *, int, HASHNODE *));
241 static struct cpp_pending *nreverse_pending PARAMS ((struct cpp_pending *));
242 extern char *xrealloc ();
243 static char *xcalloc PROTO ((unsigned, unsigned));
244 static char *savestring PROTO ((char *));
246 static void conditional_skip PROTO ((cpp_reader *, int,
247 enum node_type, U_CHAR *));
248 static void skip_if_group PROTO ((cpp_reader *, int));
249 static int parse_name PARAMS ((cpp_reader *, int));
250 static void print_help PROTO ((void));
252 /* Last arg to output_line_command. */
253 enum file_change_code {same_file, enter_file, leave_file};
255 /* External declarations. */
257 extern HOST_WIDE_INT cpp_parse_expr PARAMS ((cpp_reader *));
259 extern char *version_string;
260 extern struct tm *localtime ();
262 struct file_name_list
264 struct file_name_list *next;
265 char *fname;
266 /* If the following is nonzero, it is a macro name.
267 Don't include the file again if that macro is defined. */
268 U_CHAR *control_macro;
269 /* If the following is nonzero, it is a C-language system include
270 directory. */
271 int c_system_include_path;
272 /* Mapping of file names for this directory. */
273 struct file_name_map *name_map;
274 /* Non-zero if name_map is valid. */
275 int got_name_map;
278 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
279 via the same directory as the file that #included it. */
280 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
282 /* #include "file" looks in source file dir, then stack. */
283 /* #include <file> just looks in the stack. */
284 /* -I directories are added to the end, then the defaults are added. */
285 /* The */
286 static struct default_include {
287 char *fname; /* The name of the directory. */
288 char *component; /* The component containing the directory */
289 int cplusplus; /* Only look here if we're compiling C++. */
290 int cxx_aware; /* Includes in this directory don't need to
291 be wrapped in extern "C" when compiling
292 C++. */
293 } include_defaults_array[]
294 #ifdef INCLUDE_DEFAULTS
295 = INCLUDE_DEFAULTS;
296 #else
298 /* Pick up GNU C++ specific include files. */
299 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
300 #ifdef CROSS_COMPILE
301 /* This is the dir for fixincludes. Put it just before
302 the files that we fix. */
303 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
304 /* For cross-compilation, this dir name is generated
305 automatically in Makefile.in. */
306 { CROSS_INCLUDE_DIR, "GCC",0, 0 },
307 #ifdef TOOL_INCLUDE_DIR
308 /* This is another place that the target system's headers might be. */
309 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 1 },
310 #endif
311 #else /* not CROSS_COMPILE */
312 #ifdef LOCAL_INCLUDE_DIR
313 /* This should be /usr/local/include and should come before
314 the fixincludes-fixed header files. */
315 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
316 #endif
317 #ifdef TOOL_INCLUDE_DIR
318 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
319 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
320 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 1 },
321 #endif
322 /* This is the dir for fixincludes. Put it just before
323 the files that we fix. */
324 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
325 /* Some systems have an extra dir of include files. */
326 #ifdef SYSTEM_INCLUDE_DIR
327 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
328 #endif
329 #ifndef STANDARD_INCLUDE_COMPONENT
330 #define STANDARD_INCLUDE_COMPONENT 0
331 #endif
332 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
333 #endif /* not CROSS_COMPILE */
334 { 0, 0, 0, 0 }
336 #endif /* no INCLUDE_DEFAULTS */
338 /* `struct directive' defines one #-directive, including how to handle it. */
340 struct directive {
341 int length; /* Length of name */
342 int (*func) /* Function to handle directive */
343 PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
344 char *name; /* Name of directive */
345 enum node_type type; /* Code which describes which directive. */
346 char command_reads_line; /* One if rest of line is read by func. */
349 /* These functions are declared to return int instead of void since they
350 are going to be placed in a table and some old compilers have trouble with
351 pointers to functions returning void. */
353 static int do_define PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
354 static int do_line PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
355 static int do_include PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
356 static int do_undef PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
357 static int do_error PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
358 static int do_pragma PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
359 static int do_ident PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
360 static int do_if PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
361 static int do_xifdef PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
362 static int do_else PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
363 static int do_elif PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
364 static int do_endif PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
365 #ifdef SCCS_DIRECTIVE
366 static int do_sccs PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
367 #endif
368 static int do_once PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
369 static int do_assert PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
370 static int do_unassert PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
371 static int do_warning PARAMS ((cpp_reader *, struct directive *, U_CHAR *, U_CHAR *));
373 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
374 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
376 /* Here is the actual list of #-directives, most-often-used first.
377 The initialize_builtins function assumes #define is the very first. */
379 static struct directive directive_table[] = {
380 { 6, do_define, "define", T_DEFINE},
381 { 5, do_xifdef, "ifdef", T_IFDEF, 1},
382 { 6, do_xifdef, "ifndef", T_IFNDEF, 1},
383 { 7, do_include, "include", T_INCLUDE, 1},
384 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
385 { 6, do_include, "import", T_IMPORT, 1},
386 { 5, do_endif, "endif", T_ENDIF, 1},
387 { 4, do_else, "else", T_ELSE, 1},
388 { 2, do_if, "if", T_IF, 1},
389 { 4, do_elif, "elif", T_ELIF, 1},
390 { 5, do_undef, "undef", T_UNDEF},
391 { 5, do_error, "error", T_ERROR},
392 { 7, do_warning, "warning", T_WARNING},
393 { 6, do_pragma, "pragma", T_PRAGMA},
394 { 4, do_line, "line", T_LINE, 1},
395 { 5, do_ident, "ident", T_IDENT, 1},
396 #ifdef SCCS_DIRECTIVE
397 { 4, do_sccs, "sccs", T_SCCS},
398 #endif
399 { 6, do_assert, "assert", T_ASSERT, 1},
400 { 8, do_unassert, "unassert", T_UNASSERT, 1},
401 { -1, 0, "", T_UNUSED},
404 /* table to tell if char can be part of a C identifier. */
405 U_CHAR is_idchar[256];
406 /* table to tell if char can be first char of a c identifier. */
407 U_CHAR is_idstart[256];
408 /* table to tell if c is horizontal space. */
409 U_CHAR is_hor_space[256];
410 /* table to tell if c is horizontal or vertical space. */
411 static U_CHAR is_space[256];
413 /* Initialize syntactic classifications of characters. */
415 static void
416 initialize_char_syntax (opts)
417 struct cpp_options *opts;
419 register int i;
422 * Set up is_idchar and is_idstart tables. These should be
423 * faster than saying (is_alpha (c) || c == '_'), etc.
424 * Set up these things before calling any routines tthat
425 * refer to them.
427 for (i = 'a'; i <= 'z'; i++) {
428 is_idchar[i - 'a' + 'A'] = 1;
429 is_idchar[i] = 1;
430 is_idstart[i - 'a' + 'A'] = 1;
431 is_idstart[i] = 1;
433 for (i = '0'; i <= '9'; i++)
434 is_idchar[i] = 1;
435 is_idchar['_'] = 1;
436 is_idstart['_'] = 1;
437 is_idchar['$'] = opts->dollars_in_ident;
438 is_idstart['$'] = opts->dollars_in_ident;
440 /* horizontal space table */
441 is_hor_space[' '] = 1;
442 is_hor_space['\t'] = 1;
443 is_hor_space['\v'] = 1;
444 is_hor_space['\f'] = 1;
445 is_hor_space['\r'] = 1;
447 is_space[' '] = 1;
448 is_space['\t'] = 1;
449 is_space['\v'] = 1;
450 is_space['\f'] = 1;
451 is_space['\n'] = 1;
452 is_space['\r'] = 1;
456 /* Place into PFILE a quoted string representing the string SRC.
457 Caller must reserve enough space in pfile->token_buffer. */
459 static void
460 quote_string (pfile, src)
461 cpp_reader *pfile;
462 char *src;
464 U_CHAR c;
466 CPP_PUTC_Q (pfile, '\"');
467 for (;;)
468 switch ((c = *src++))
470 default:
471 if (ISPRINT (c))
472 CPP_PUTC_Q (pfile, c);
473 else
475 sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o", c);
476 CPP_ADJUST_WRITTEN (pfile, 4);
478 break;
480 case '\"':
481 case '\\':
482 CPP_PUTC_Q (pfile, '\\');
483 CPP_PUTC_Q (pfile, c);
484 break;
486 case '\0':
487 CPP_PUTC_Q (pfile, '\"');
488 CPP_NUL_TERMINATE_Q (pfile);
489 return;
493 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars. */
495 void
496 cpp_grow_buffer (pfile, n)
497 cpp_reader *pfile;
498 long n;
500 long old_written = CPP_WRITTEN (pfile);
501 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
502 pfile->token_buffer = (U_CHAR *)
503 xrealloc(pfile->token_buffer, pfile->token_buffer_size);
504 CPP_SET_WRITTEN (pfile, old_written);
509 * process a given definition string, for initialization
510 * If STR is just an identifier, define it with value 1.
511 * If STR has anything after the identifier, then it should
512 * be identifier=definition.
515 void
516 cpp_define (pfile, str)
517 cpp_reader *pfile;
518 U_CHAR *str;
520 U_CHAR *buf, *p;
522 buf = str;
523 p = str;
524 if (!is_idstart[*p])
526 cpp_error (pfile, "malformed option `-D %s'", str);
527 return;
529 while (is_idchar[*++p])
531 if (*p == '(') {
532 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
534 if (*p++ != ')')
535 p = (U_CHAR *) str; /* Error */
537 if (*p == 0)
539 buf = (U_CHAR *) alloca (p - buf + 4);
540 strcpy ((char *)buf, str);
541 strcat ((char *)buf, " 1");
543 else if (*p != '=')
545 cpp_error (pfile, "malformed option `-D %s'", str);
546 return;
548 else
550 U_CHAR *q;
551 /* Copy the entire option so we can modify it. */
552 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
553 strncpy (buf, str, p - str);
554 /* Change the = to a space. */
555 buf[p - str] = ' ';
556 /* Scan for any backslash-newline and remove it. */
557 p++;
558 q = &buf[p - str];
559 while (*p)
561 if (*p == '\\' && p[1] == '\n')
562 p += 2;
563 else
564 *q++ = *p++;
566 *q = 0;
569 do_define (pfile, NULL, buf, buf + strlen (buf));
572 /* Process the string STR as if it appeared as the body of a #assert.
573 OPTION is the option name for which STR was the argument. */
575 static void
576 make_assertion (pfile, option, str)
577 cpp_reader *pfile;
578 char *option;
579 U_CHAR *str;
581 U_CHAR *buf, *p, *q;
583 /* Copy the entire option so we can modify it. */
584 buf = (U_CHAR *) alloca (strlen (str) + 1);
585 strcpy ((char *) buf, str);
586 /* Scan for any backslash-newline and remove it. */
587 p = q = buf;
588 while (*p) {
589 #if 0
590 if (*p == '\\' && p[1] == '\n')
591 p += 2;
592 else
593 #endif
594 *q++ = *p++;
596 *q = 0;
598 p = buf;
599 if (!is_idstart[*p]) {
600 cpp_error (pfile, "malformed option `%s %s'", option, str);
601 return;
603 while (is_idchar[*++p])
605 while (*p == ' ' || *p == '\t') p++;
606 if (! (*p == 0 || *p == '(')) {
607 cpp_error (pfile, "malformed option `%s %s'", option, str);
608 return;
611 if (cpp_push_buffer (pfile, buf, strlen (buf)) != NULL)
613 do_assert (pfile, NULL, NULL, NULL);
614 cpp_pop_buffer (pfile);
618 /* Append a chain of `struct file_name_list's
619 to the end of the main include chain.
620 FIRST is the beginning of the chain to append, and LAST is the end. */
622 static void
623 append_include_chain (pfile, first, last)
624 cpp_reader *pfile;
625 struct file_name_list *first, *last;
627 struct cpp_options *opts = CPP_OPTIONS (pfile);
628 struct file_name_list *dir;
630 if (!first || !last)
631 return;
633 if (opts->include == 0)
634 opts->include = first;
635 else
636 opts->last_include->next = first;
638 if (opts->first_bracket_include == 0)
639 opts->first_bracket_include = first;
641 for (dir = first; ; dir = dir->next) {
642 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
643 if (len > pfile->max_include_len)
644 pfile->max_include_len = len;
645 if (dir == last)
646 break;
649 last->next = NULL;
650 opts->last_include = last;
653 /* Add output to `deps_buffer' for the -M switch.
654 STRING points to the text to be output.
655 SPACER is ':' for targets, ' ' for dependencies, zero for text
656 to be inserted literally. */
658 static void
659 deps_output (pfile, string, spacer)
660 cpp_reader *pfile;
661 char *string;
662 int spacer;
664 int size = strlen (string);
666 if (size == 0)
667 return;
669 #ifndef MAX_OUTPUT_COLUMNS
670 #define MAX_OUTPUT_COLUMNS 72
671 #endif
672 if (spacer
673 && pfile->deps_column > 0
674 && (pfile->deps_column + size) > MAX_OUTPUT_COLUMNS)
676 deps_output (pfile, " \\\n ", 0);
677 pfile->deps_column = 0;
680 if (pfile->deps_size + size + 8 > pfile->deps_allocated_size)
682 pfile->deps_allocated_size = (pfile->deps_size + size + 50) * 2;
683 pfile->deps_buffer = (char *) xrealloc (pfile->deps_buffer,
684 pfile->deps_allocated_size);
686 if (spacer == ' ' && pfile->deps_column > 0)
687 pfile->deps_buffer[pfile->deps_size++] = ' ';
688 bcopy (string, &pfile->deps_buffer[pfile->deps_size], size);
689 pfile->deps_size += size;
690 pfile->deps_column += size;
691 if (spacer == ':')
692 pfile->deps_buffer[pfile->deps_size++] = ':';
693 pfile->deps_buffer[pfile->deps_size] = 0;
696 /* Given a colon-separated list of file names PATH,
697 add all the names to the search path for include files. */
699 static void
700 path_include (pfile, path)
701 cpp_reader *pfile;
702 char *path;
704 char *p;
706 p = path;
708 if (*p)
709 while (1) {
710 char *q = p;
711 char *name;
712 struct file_name_list *dirtmp;
714 /* Find the end of this name. */
715 while (*q != 0 && *q != PATH_SEPARATOR) q++;
716 if (p == q) {
717 /* An empty name in the path stands for the current directory. */
718 name = (char *) xmalloc (2);
719 name[0] = '.';
720 name[1] = 0;
721 } else {
722 /* Otherwise use the directory that is named. */
723 name = (char *) xmalloc (q - p + 1);
724 bcopy (p, name, q - p);
725 name[q - p] = 0;
728 dirtmp = (struct file_name_list *)
729 xmalloc (sizeof (struct file_name_list));
730 dirtmp->next = 0; /* New one goes on the end */
731 dirtmp->control_macro = 0;
732 dirtmp->c_system_include_path = 0;
733 dirtmp->fname = name;
734 dirtmp->got_name_map = 0;
735 append_include_chain (pfile, dirtmp, dirtmp);
737 /* Advance past this name. */
738 p = q;
739 if (*p == 0)
740 break;
741 /* Skip the colon. */
742 p++;
746 void
747 cpp_options_init (opts)
748 cpp_options *opts;
750 bzero ((char *) opts, sizeof *opts);
751 opts->in_fname = NULL;
752 opts->out_fname = NULL;
754 /* Initialize is_idchar to allow $. */
755 opts->dollars_in_ident = 1;
756 initialize_char_syntax (opts);
758 opts->no_line_commands = 0;
759 opts->no_trigraphs = 1;
760 opts->put_out_comments = 0;
761 opts->print_include_names = 0;
762 opts->dump_macros = dump_none;
763 opts->no_output = 0;
764 opts->remap = 0;
765 opts->cplusplus = 0;
766 opts->cplusplus_comments = 1;
768 opts->verbose = 0;
769 opts->objc = 0;
770 opts->lang_asm = 0;
771 opts->for_lint = 0;
772 opts->chill = 0;
773 opts->pedantic_errors = 0;
774 opts->inhibit_warnings = 0;
775 opts->warn_comments = 0;
776 opts->warn_import = 1;
777 opts->warnings_are_errors = 0;
780 enum cpp_token
781 null_underflow (pfile)
782 cpp_reader *pfile ATTRIBUTE_UNUSED;
784 return CPP_EOF;
788 null_cleanup (pbuf, pfile)
789 cpp_buffer *pbuf ATTRIBUTE_UNUSED;
790 cpp_reader *pfile ATTRIBUTE_UNUSED;
792 return 0;
796 macro_cleanup (pbuf, pfile)
797 cpp_buffer *pbuf;
798 cpp_reader *pfile ATTRIBUTE_UNUSED;
800 HASHNODE *macro = (HASHNODE *) pbuf->data;
801 if (macro->type == T_DISABLED)
802 macro->type = T_MACRO;
803 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
804 free (pbuf->buf);
805 return 0;
809 file_cleanup (pbuf, pfile)
810 cpp_buffer *pbuf;
811 cpp_reader *pfile ATTRIBUTE_UNUSED;
813 if (pbuf->buf)
815 free (pbuf->buf);
816 pbuf->buf = 0;
818 return 0;
821 /* Assuming we have read '/'.
822 If this is the start of a comment (followed by '*' or '/'),
823 skip to the end of the comment, and return ' '.
824 Return EOF if we reached the end of file before the end of the comment.
825 If not the start of a comment, return '/'. */
827 static int
828 skip_comment (pfile, linep)
829 cpp_reader *pfile;
830 long *linep;
832 int c = 0;
833 while (PEEKC() == '\\' && PEEKN(1) == '\n')
835 if (linep)
836 (*linep)++;
837 FORWARD(2);
839 if (PEEKC() == '*')
841 FORWARD(1);
842 for (;;)
844 int prev_c = c;
845 c = GETC ();
846 if (c == EOF)
847 return EOF;
848 while (c == '\\' && PEEKC() == '\n')
850 if (linep)
851 (*linep)++;
852 FORWARD(1), c = GETC();
854 if (prev_c == '*' && c == '/')
855 return ' ';
856 if (c == '\n' && linep)
857 (*linep)++;
860 else if (PEEKC() == '/' && CPP_OPTIONS (pfile)->cplusplus_comments)
862 FORWARD(1);
863 for (;;)
865 c = GETC ();
866 if (c == EOF)
867 return ' '; /* Allow // to be terminated by EOF. */
868 while (c == '\\' && PEEKC() == '\n')
870 FORWARD(1);
871 c = GETC();
872 if (linep)
873 (*linep)++;
875 if (c == '\n')
877 /* Don't consider final '\n' to be part of comment. */
878 FORWARD(-1);
879 return ' ';
883 else
884 return '/';
887 /* Skip whitespace \-newline and comments. Does not macro-expand. */
889 void
890 cpp_skip_hspace (pfile)
891 cpp_reader *pfile;
893 while (1)
895 int c = PEEKC();
896 if (c == EOF)
897 return; /* FIXME */
898 if (is_hor_space[c])
900 if ((c == '\f' || c == '\v') && CPP_PEDANTIC (pfile))
901 cpp_pedwarn (pfile, "%s in preprocessing directive",
902 c == '\f' ? "formfeed" : "vertical tab");
903 FORWARD(1);
905 else if (c == '/')
907 FORWARD (1);
908 c = skip_comment (pfile, NULL);
909 if (c == '/')
910 FORWARD(-1);
911 if (c == EOF || c == '/')
912 return;
914 else if (c == '\\' && PEEKN(1) == '\n') {
915 FORWARD(2);
917 else if (c == '@' && CPP_BUFFER (pfile)->has_escapes
918 && is_hor_space[PEEKN(1)])
919 FORWARD(2);
920 else return;
924 /* Read the rest of the current line.
925 The line is appended to PFILE's output buffer. */
927 static void
928 copy_rest_of_line (pfile)
929 cpp_reader *pfile;
931 struct cpp_options *opts = CPP_OPTIONS (pfile);
932 for (;;)
934 int c = GETC();
935 int nextc;
936 switch (c)
938 case EOF:
939 goto end_directive;
940 case '\\':
941 if (PEEKC() == '\n')
943 FORWARD (1);
944 continue;
946 case '\'':
947 case '\"':
948 goto scan_directive_token;
949 break;
950 case '/':
951 nextc = PEEKC();
952 if (nextc == '*' || (opts->cplusplus_comments && nextc == '/'))
953 goto scan_directive_token;
954 break;
955 case '\f':
956 case '\v':
957 if (CPP_PEDANTIC (pfile))
958 cpp_pedwarn (pfile, "%s in preprocessing directive",
959 c == '\f' ? "formfeed" : "vertical tab");
960 break;
962 case '\n':
963 FORWARD(-1);
964 goto end_directive;
965 scan_directive_token:
966 FORWARD(-1);
967 cpp_get_token (pfile);
968 continue;
970 CPP_PUTC (pfile, c);
972 end_directive: ;
973 CPP_NUL_TERMINATE (pfile);
976 void
977 skip_rest_of_line (pfile)
978 cpp_reader *pfile;
980 long old = CPP_WRITTEN (pfile);
981 copy_rest_of_line (pfile);
982 CPP_SET_WRITTEN (pfile, old);
985 /* Handle a possible # directive.
986 '#' has already been read. */
989 handle_directive (pfile)
990 cpp_reader *pfile;
991 { int c;
992 register struct directive *kt;
993 int ident_length;
994 long after_ident;
995 U_CHAR *ident, *line_end;
996 long old_written = CPP_WRITTEN (pfile);
998 cpp_skip_hspace (pfile);
1000 c = PEEKC ();
1001 if (c >= '0' && c <= '9')
1003 /* Handle # followed by a line number. */
1004 if (CPP_PEDANTIC (pfile))
1005 cpp_pedwarn (pfile, "`#' followed by integer");
1006 do_line (pfile, NULL, NULL, NULL);
1007 goto done_a_directive;
1010 /* Now find the directive name. */
1011 CPP_PUTC (pfile, '#');
1012 parse_name (pfile, GETC());
1013 ident = pfile->token_buffer + old_written + 1;
1014 ident_length = CPP_PWRITTEN (pfile) - ident;
1015 if (ident_length == 0 && PEEKC() == '\n')
1017 /* A line of just `#' becomes blank. */
1018 goto done_a_directive;
1021 #if 0
1022 if (ident_length == 0 || !is_idstart[*ident]) {
1023 U_CHAR *p = ident;
1024 while (is_idchar[*p]) {
1025 if (*p < '0' || *p > '9')
1026 break;
1027 p++;
1029 /* Avoid error for `###' and similar cases unless -pedantic. */
1030 if (p == ident) {
1031 while (*p == '#' || is_hor_space[*p]) p++;
1032 if (*p == '\n') {
1033 if (pedantic && !lang_asm)
1034 cpp_warning (pfile, "invalid preprocessor directive");
1035 return 0;
1039 if (!lang_asm)
1040 cpp_error (pfile, "invalid preprocessor directive name");
1042 return 0;
1044 #endif
1046 * Decode the keyword and call the appropriate expansion
1047 * routine, after moving the input pointer up to the next line.
1049 for (kt = directive_table; ; kt++) {
1050 if (kt->length <= 0)
1051 goto not_a_directive;
1052 if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length))
1053 break;
1056 if (kt->command_reads_line)
1057 after_ident = 0;
1058 else
1060 /* Nonzero means do not delete comments within the directive.
1061 #define needs this when -traditional. */
1062 int comments = CPP_TRADITIONAL (pfile) && kt->type == T_DEFINE;
1063 int save_put_out_comments = CPP_OPTIONS (pfile)->put_out_comments;
1064 CPP_OPTIONS (pfile)->put_out_comments = comments;
1065 after_ident = CPP_WRITTEN (pfile);
1066 copy_rest_of_line (pfile);
1067 CPP_OPTIONS (pfile)->put_out_comments = save_put_out_comments;
1070 /* We may want to pass through #define, #pragma, and #include.
1071 Other directives may create output, but we don't want the directive
1072 itself out, so we pop it now. For example conditionals may emit
1073 #failed ... #endfailed stuff. But note that popping the buffer
1074 means the parameters to kt->func may point after pfile->limit
1075 so these parameters are invalid as soon as something gets appended
1076 to the token_buffer. */
1078 line_end = CPP_PWRITTEN (pfile);
1079 if (! (kt->type == T_DEFINE
1080 || kt->type == T_PRAGMA
1081 || (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)
1082 && CPP_OPTIONS (pfile)->dump_includes)))
1083 CPP_SET_WRITTEN (pfile, old_written);
1085 (*kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1087 if (kt->type == T_DEFINE)
1089 if (CPP_OPTIONS (pfile)->dump_macros == dump_names)
1091 /* Skip "#define". */
1092 U_CHAR *p = pfile->token_buffer + old_written + 7;
1094 SKIP_WHITE_SPACE (p);
1095 while (is_idchar[*p]) p++;
1096 pfile->limit = p;
1097 CPP_PUTC (pfile, '\n');
1099 else if (CPP_OPTIONS (pfile)->dump_macros != dump_definitions)
1100 CPP_SET_WRITTEN (pfile, old_written);
1103 done_a_directive:
1104 return 1;
1106 not_a_directive:
1107 return 0;
1110 /* Pass a directive through to the output file.
1111 BUF points to the contents of the directive, as a contiguous string.
1112 LIMIT points to the first character past the end of the directive.
1113 KEYWORD is the keyword-table entry for the directive. */
1115 static void
1116 pass_thru_directive (buf, limit, pfile, keyword)
1117 U_CHAR *buf, *limit;
1118 cpp_reader *pfile;
1119 struct directive *keyword;
1121 register unsigned keyword_length = keyword->length;
1123 CPP_RESERVE (pfile, 1 + keyword_length + (limit - buf));
1124 CPP_PUTC_Q (pfile, '#');
1125 CPP_PUTS_Q (pfile, keyword->name, keyword_length);
1126 if (limit != buf && buf[0] != ' ')
1127 CPP_PUTC_Q (pfile, ' ');
1128 CPP_PUTS_Q (pfile, buf, limit - buf);
1129 #if 0
1130 CPP_PUTS_Q (pfile, '\n');
1131 /* Count the line we have just made in the output,
1132 to get in sync properly. */
1133 pfile->lineno++;
1134 #endif
1137 /* The arglist structure is built by do_define to tell
1138 collect_definition where the argument names begin. That
1139 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
1140 would contain pointers to the strings x, y, and z.
1141 Collect_definition would then build a DEFINITION node,
1142 with reflist nodes pointing to the places x, y, and z had
1143 appeared. So the arglist is just convenience data passed
1144 between these two routines. It is not kept around after
1145 the current #define has been processed and entered into the
1146 hash table. */
1148 struct arglist {
1149 struct arglist *next;
1150 U_CHAR *name;
1151 int length;
1152 int argno;
1153 char rest_args;
1156 /* Read a replacement list for a macro with parameters.
1157 Build the DEFINITION structure.
1158 Reads characters of text starting at BUF until END.
1159 ARGLIST specifies the formal parameters to look for
1160 in the text of the definition; NARGS is the number of args
1161 in that list, or -1 for a macro name that wants no argument list.
1162 MACRONAME is the macro name itself (so we can avoid recursive expansion)
1163 and NAMELEN is its length in characters.
1165 Note that comments, backslash-newlines, and leading white space
1166 have already been deleted from the argument. */
1168 static DEFINITION *
1169 collect_expansion (pfile, buf, limit, nargs, arglist)
1170 cpp_reader *pfile;
1171 U_CHAR *buf, *limit;
1172 int nargs;
1173 struct arglist *arglist;
1175 DEFINITION *defn;
1176 register U_CHAR *p, *lastp, *exp_p;
1177 struct reflist *endpat = NULL;
1178 /* Pointer to first nonspace after last ## seen. */
1179 U_CHAR *concat = 0;
1180 /* Pointer to first nonspace after last single-# seen. */
1181 U_CHAR *stringify = 0;
1182 int maxsize;
1183 int expected_delimiter = '\0';
1185 /* Scan thru the replacement list, ignoring comments and quoted
1186 strings, picking up on the macro calls. It does a linear search
1187 thru the arg list on every potential symbol. Profiling might say
1188 that something smarter should happen. */
1190 if (limit < buf)
1191 abort ();
1193 /* Find the beginning of the trailing whitespace. */
1194 p = buf;
1195 while (p < limit && is_space[limit[-1]]) limit--;
1197 /* Allocate space for the text in the macro definition.
1198 Leading and trailing whitespace chars need 2 bytes each.
1199 Each other input char may or may not need 1 byte,
1200 so this is an upper bound. The extra 5 are for invented
1201 leading and trailing newline-marker and final null. */
1202 maxsize = (sizeof (DEFINITION)
1203 + (limit - p) + 5);
1204 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1205 while (p < limit)
1206 if (*p++ == '@')
1207 maxsize++;
1208 defn = (DEFINITION *) xcalloc (1, maxsize);
1210 defn->nargs = nargs;
1211 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
1212 lastp = exp_p;
1214 p = buf;
1216 /* Add one initial space escape-marker to prevent accidental
1217 token-pasting (often removed by macroexpand). */
1218 *exp_p++ = '@';
1219 *exp_p++ = ' ';
1221 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1222 cpp_error (pfile, "`##' at start of macro definition");
1223 p += 2;
1226 /* Process the main body of the definition. */
1227 while (p < limit) {
1228 int skipped_arg = 0;
1229 register U_CHAR c = *p++;
1231 *exp_p++ = c;
1233 if (!CPP_TRADITIONAL (pfile)) {
1234 switch (c) {
1235 case '\'':
1236 case '\"':
1237 if (expected_delimiter != '\0') {
1238 if (c == expected_delimiter)
1239 expected_delimiter = '\0';
1240 } else
1241 expected_delimiter = c;
1242 break;
1244 case '\\':
1245 if (p < limit && expected_delimiter) {
1246 /* In a string, backslash goes through
1247 and makes next char ordinary. */
1248 *exp_p++ = *p++;
1250 break;
1252 case '@':
1253 /* An '@' in a string or character constant stands for itself,
1254 and does not need to be escaped. */
1255 if (!expected_delimiter)
1256 *exp_p++ = c;
1257 break;
1259 case '#':
1260 /* # is ordinary inside a string. */
1261 if (expected_delimiter)
1262 break;
1263 if (p < limit && *p == '#') {
1264 /* ##: concatenate preceding and following tokens. */
1265 /* Take out the first #, discard preceding whitespace. */
1266 exp_p--;
1267 while (exp_p > lastp && is_hor_space[exp_p[-1]])
1268 --exp_p;
1269 /* Skip the second #. */
1270 p++;
1271 /* Discard following whitespace. */
1272 SKIP_WHITE_SPACE (p);
1273 concat = p;
1274 if (p == limit)
1275 cpp_error (pfile, "`##' at end of macro definition");
1276 } else if (nargs >= 0) {
1277 /* Single #: stringify following argument ref.
1278 Don't leave the # in the expansion. */
1279 exp_p--;
1280 SKIP_WHITE_SPACE (p);
1281 if (p == limit || ! is_idstart[*p]
1282 || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '"')))
1283 cpp_error (pfile,
1284 "`#' operator is not followed by a macro argument name");
1285 else
1286 stringify = p;
1288 break;
1290 } else {
1291 /* In -traditional mode, recognize arguments inside strings and
1292 character constants, and ignore special properties of #.
1293 Arguments inside strings are considered "stringified", but no
1294 extra quote marks are supplied. */
1295 switch (c) {
1296 case '\'':
1297 case '\"':
1298 if (expected_delimiter != '\0') {
1299 if (c == expected_delimiter)
1300 expected_delimiter = '\0';
1301 } else
1302 expected_delimiter = c;
1303 break;
1305 case '\\':
1306 /* Backslash quotes delimiters and itself, but not macro args. */
1307 if (expected_delimiter != 0 && p < limit
1308 && (*p == expected_delimiter || *p == '\\')) {
1309 *exp_p++ = *p++;
1310 continue;
1312 break;
1314 case '/':
1315 if (expected_delimiter != '\0') /* No comments inside strings. */
1316 break;
1317 if (*p == '*') {
1318 /* If we find a comment that wasn't removed by handle_directive,
1319 this must be -traditional. So replace the comment with
1320 nothing at all. */
1321 exp_p--;
1322 p += 1;
1323 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1324 p++;
1325 #if 0
1326 /* Mark this as a concatenation-point, as if it had been ##. */
1327 concat = p;
1328 #endif
1330 break;
1334 /* Handle the start of a symbol. */
1335 if (is_idchar[c] && nargs > 0) {
1336 U_CHAR *id_beg = p - 1;
1337 int id_len;
1339 --exp_p;
1340 while (p != limit && is_idchar[*p]) p++;
1341 id_len = p - id_beg;
1343 if (is_idstart[c]
1344 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
1345 register struct arglist *arg;
1347 for (arg = arglist; arg != NULL; arg = arg->next) {
1348 struct reflist *tpat;
1350 if (arg->name[0] == c
1351 && arg->length == id_len
1352 && strncmp (arg->name, id_beg, id_len) == 0) {
1353 if (expected_delimiter && CPP_OPTIONS (pfile)->warn_stringify) {
1354 if (CPP_TRADITIONAL (pfile)) {
1355 cpp_warning (pfile, "macro argument `%.*s' is stringified.",
1356 id_len, arg->name);
1357 } else {
1358 cpp_warning (pfile,
1359 "macro arg `%.*s' would be stringified with -traditional.",
1360 id_len, arg->name);
1363 /* If ANSI, don't actually substitute inside a string. */
1364 if (!CPP_TRADITIONAL (pfile) && expected_delimiter)
1365 break;
1366 /* make a pat node for this arg and append it to the end of
1367 the pat list */
1368 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
1369 tpat->next = NULL;
1370 tpat->raw_before = concat == id_beg;
1371 tpat->raw_after = 0;
1372 tpat->rest_args = arg->rest_args;
1373 tpat->stringify = (CPP_TRADITIONAL (pfile)
1374 ? expected_delimiter != '\0'
1375 : stringify == id_beg);
1377 if (endpat == NULL)
1378 defn->pattern = tpat;
1379 else
1380 endpat->next = tpat;
1381 endpat = tpat;
1383 tpat->argno = arg->argno;
1384 tpat->nchars = exp_p - lastp;
1386 register U_CHAR *p1 = p;
1387 SKIP_WHITE_SPACE (p1);
1388 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1389 tpat->raw_after = 1;
1391 lastp = exp_p; /* place to start copying from next time */
1392 skipped_arg = 1;
1393 break;
1398 /* If this was not a macro arg, copy it into the expansion. */
1399 if (! skipped_arg) {
1400 register U_CHAR *lim1 = p;
1401 p = id_beg;
1402 while (p != lim1)
1403 *exp_p++ = *p++;
1404 if (stringify == id_beg)
1405 cpp_error (pfile,
1406 "`#' operator should be followed by a macro argument name");
1411 if (!CPP_TRADITIONAL (pfile) && expected_delimiter == 0)
1413 /* If ANSI, put in a "@ " marker to prevent token pasting.
1414 But not if "inside a string" (which in ANSI mode
1415 happens only for -D option). */
1416 *exp_p++ = '@';
1417 *exp_p++ = ' ';
1420 *exp_p = '\0';
1422 defn->length = exp_p - defn->expansion;
1424 /* Crash now if we overrun the allocated size. */
1425 if (defn->length + 1 > maxsize)
1426 abort ();
1428 #if 0
1429 /* This isn't worth the time it takes. */
1430 /* give back excess storage */
1431 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
1432 #endif
1434 return defn;
1438 * special extension string that can be added to the last macro argument to
1439 * allow it to absorb the "rest" of the arguments when expanded. Ex:
1440 * #define wow(a, b...) process (b, a, b)
1441 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
1442 * { wow (one, two); } -> { process (two, one, two); }
1443 * if this "rest_arg" is used with the concat token '##' and if it is not
1444 * supplied then the token attached to with ## will not be outputted. Ex:
1445 * #define wow (a, b...) process (b ## , a, ## b)
1446 * { wow (1, 2); } -> { process (2, 1, 2); }
1447 * { wow (one); } -> { process (one); {
1449 static char rest_extension[] = "...";
1450 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
1452 /* Create a DEFINITION node from a #define directive. Arguments are
1453 as for do_define. */
1455 static MACRODEF
1456 create_definition (buf, limit, pfile, predefinition)
1457 U_CHAR *buf, *limit;
1458 cpp_reader *pfile;
1459 int predefinition;
1461 U_CHAR *bp; /* temp ptr into input buffer */
1462 U_CHAR *symname; /* remember where symbol name starts */
1463 int sym_length; /* and how long it is */
1464 int rest_args = 0;
1465 long line, col;
1466 char *file = CPP_BUFFER (pfile) ? CPP_BUFFER (pfile)->nominal_fname : "";
1467 DEFINITION *defn;
1468 int arglengths = 0; /* Accumulate lengths of arg names
1469 plus number of args. */
1470 MACRODEF mdef;
1471 cpp_buf_line_and_col (CPP_BUFFER (pfile), &line, &col);
1473 bp = buf;
1475 while (is_hor_space[*bp])
1476 bp++;
1478 symname = bp; /* remember where it starts */
1480 sym_length = check_macro_name (pfile, bp, "macro");
1481 bp += sym_length;
1483 /* Lossage will occur if identifiers or control keywords are broken
1484 across lines using backslash. This is not the right place to take
1485 care of that. */
1487 if (*bp == '(') {
1488 struct arglist *arg_ptrs = NULL;
1489 int argno = 0;
1491 bp++; /* skip '(' */
1492 SKIP_WHITE_SPACE (bp);
1494 /* Loop over macro argument names. */
1495 while (*bp != ')') {
1496 struct arglist *temp;
1498 temp = (struct arglist *) alloca (sizeof (struct arglist));
1499 temp->name = bp;
1500 temp->next = arg_ptrs;
1501 temp->argno = argno++;
1502 temp->rest_args = 0;
1503 arg_ptrs = temp;
1505 if (rest_args)
1506 cpp_pedwarn (pfile, "another parameter follows `%s'", rest_extension);
1508 if (!is_idstart[*bp])
1509 cpp_pedwarn (pfile, "invalid character in macro parameter name");
1511 /* Find the end of the arg name. */
1512 while (is_idchar[*bp]) {
1513 bp++;
1514 /* do we have a "special" rest-args extension here? */
1515 if ((size_t)(limit - bp) > REST_EXTENSION_LENGTH
1516 && strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
1517 rest_args = 1;
1518 temp->rest_args = 1;
1519 break;
1522 temp->length = bp - temp->name;
1523 if (rest_args == 1)
1524 bp += REST_EXTENSION_LENGTH;
1525 arglengths += temp->length + 2;
1526 SKIP_WHITE_SPACE (bp);
1527 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
1528 cpp_error (pfile, "badly punctuated parameter list in `#define'");
1529 goto nope;
1531 if (*bp == ',') {
1532 bp++;
1533 SKIP_WHITE_SPACE (bp);
1535 if (bp >= limit) {
1536 cpp_error (pfile, "unterminated parameter list in `#define'");
1537 goto nope;
1540 struct arglist *otemp;
1542 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1543 if (temp->length == otemp->length
1544 && strncmp (temp->name, otemp->name, temp->length) == 0) {
1545 U_CHAR *name;
1547 name = (U_CHAR *) alloca (temp->length + 1);
1548 (void) strncpy (name, temp->name, temp->length);
1549 name[temp->length] = '\0';
1550 cpp_error (pfile,
1551 "duplicate argument name `%s' in `#define'", name);
1552 goto nope;
1557 ++bp; /* skip paren */
1558 SKIP_WHITE_SPACE (bp);
1559 /* now everything from bp before limit is the definition. */
1560 defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
1561 defn->rest_args = rest_args;
1563 /* Now set defn->args.argnames to the result of concatenating
1564 the argument names in reverse order
1565 with comma-space between them. */
1566 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
1568 struct arglist *temp;
1569 int i = 0;
1570 for (temp = arg_ptrs; temp; temp = temp->next) {
1571 bcopy (temp->name, &defn->args.argnames[i], temp->length);
1572 i += temp->length;
1573 if (temp->next != 0) {
1574 defn->args.argnames[i++] = ',';
1575 defn->args.argnames[i++] = ' ';
1578 defn->args.argnames[i] = 0;
1580 } else {
1581 /* Simple expansion or empty definition. */
1583 if (bp < limit)
1585 if (is_hor_space[*bp]) {
1586 bp++;
1587 SKIP_WHITE_SPACE (bp);
1588 } else {
1589 switch (*bp) {
1590 case '!': case '"': case '#': case '%': case '&': case '\'':
1591 case ')': case '*': case '+': case ',': case '-': case '.':
1592 case '/': case ':': case ';': case '<': case '=': case '>':
1593 case '?': case '[': case '\\': case ']': case '^': case '{':
1594 case '|': case '}': case '~':
1595 cpp_warning (pfile, "missing white space after `#define %.*s'",
1596 sym_length, symname);
1597 break;
1599 default:
1600 cpp_pedwarn (pfile, "missing white space after `#define %.*s'",
1601 sym_length, symname);
1602 break;
1606 /* now everything from bp before limit is the definition. */
1607 defn = collect_expansion (pfile, bp, limit, -1, NULL_PTR);
1608 defn->args.argnames = (U_CHAR *) "";
1611 defn->line = line;
1612 defn->file = file;
1614 /* OP is null if this is a predefinition */
1615 defn->predefined = predefinition;
1616 mdef.defn = defn;
1617 mdef.symnam = symname;
1618 mdef.symlen = sym_length;
1620 return mdef;
1622 nope:
1623 mdef.defn = 0;
1624 return mdef;
1627 /* Check a purported macro name SYMNAME, and yield its length.
1628 USAGE is the kind of name this is intended for. */
1630 static int
1631 check_macro_name (pfile, symname, usage)
1632 cpp_reader *pfile;
1633 U_CHAR *symname;
1634 char *usage;
1636 U_CHAR *p;
1637 int sym_length;
1639 for (p = symname; is_idchar[*p]; p++)
1641 sym_length = p - symname;
1642 if (sym_length == 0
1643 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
1644 cpp_error (pfile, "invalid %s name", usage);
1645 else if (!is_idstart[*symname]) {
1646 U_CHAR *msg; /* what pain... */
1647 msg = (U_CHAR *) alloca (sym_length + 1);
1648 bcopy (symname, msg, sym_length);
1649 msg[sym_length] = 0;
1650 cpp_error (pfile, "invalid %s name `%s'", usage, msg);
1651 } else {
1652 if (! strncmp (symname, "defined", 7) && sym_length == 7)
1653 cpp_error (pfile, "invalid %s name `defined'", usage);
1655 return sym_length;
1658 /* Return zero if two DEFINITIONs are isomorphic. */
1660 static int
1661 compare_defs (pfile, d1, d2)
1662 cpp_reader *pfile;
1663 DEFINITION *d1, *d2;
1665 register struct reflist *a1, *a2;
1666 register U_CHAR *p1 = d1->expansion;
1667 register U_CHAR *p2 = d2->expansion;
1668 int first = 1;
1670 if (d1->nargs != d2->nargs)
1671 return 1;
1672 if (CPP_PEDANTIC (pfile)
1673 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
1674 return 1;
1675 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1676 a1 = a1->next, a2 = a2->next) {
1677 if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
1678 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
1679 || a1->argno != a2->argno
1680 || a1->stringify != a2->stringify
1681 || a1->raw_before != a2->raw_before
1682 || a1->raw_after != a2->raw_after)
1683 return 1;
1684 first = 0;
1685 p1 += a1->nchars;
1686 p2 += a2->nchars;
1688 if (a1 != a2)
1689 return 1;
1690 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
1691 p2, d2->length - (p2 - d2->expansion), 1))
1692 return 1;
1693 return 0;
1696 /* Return 1 if two parts of two macro definitions are effectively different.
1697 One of the parts starts at BEG1 and has LEN1 chars;
1698 the other has LEN2 chars at BEG2.
1699 Any sequence of whitespace matches any other sequence of whitespace.
1700 FIRST means these parts are the first of a macro definition;
1701 so ignore leading whitespace entirely.
1702 LAST means these parts are the last of a macro definition;
1703 so ignore trailing whitespace entirely. */
1705 static int
1706 comp_def_part (first, beg1, len1, beg2, len2, last)
1707 int first;
1708 U_CHAR *beg1, *beg2;
1709 int len1, len2;
1710 int last;
1712 register U_CHAR *end1 = beg1 + len1;
1713 register U_CHAR *end2 = beg2 + len2;
1714 if (first) {
1715 while (beg1 != end1 && is_space[*beg1]) beg1++;
1716 while (beg2 != end2 && is_space[*beg2]) beg2++;
1718 if (last) {
1719 while (beg1 != end1 && is_space[end1[-1]]) end1--;
1720 while (beg2 != end2 && is_space[end2[-1]]) end2--;
1722 while (beg1 != end1 && beg2 != end2) {
1723 if (is_space[*beg1] && is_space[*beg2]) {
1724 while (beg1 != end1 && is_space[*beg1]) beg1++;
1725 while (beg2 != end2 && is_space[*beg2]) beg2++;
1726 } else if (*beg1 == *beg2) {
1727 beg1++; beg2++;
1728 } else break;
1730 return (beg1 != end1) || (beg2 != end2);
1733 /* Process a #define command.
1734 BUF points to the contents of the #define command, as a contiguous string.
1735 LIMIT points to the first character past the end of the definition.
1736 KEYWORD is the keyword-table entry for #define,
1737 or NULL for a "predefined" macro. */
1739 static int
1740 do_define (pfile, keyword, buf, limit)
1741 cpp_reader *pfile;
1742 struct directive *keyword;
1743 U_CHAR *buf, *limit;
1745 int hashcode;
1746 MACRODEF mdef;
1747 HASHNODE *hp;
1749 #if 0
1750 /* If this is a precompiler run (with -pcp) pass thru #define commands. */
1751 if (pcp_outfile && keyword)
1752 pass_thru_directive (buf, limit, pfile, keyword);
1753 #endif
1755 mdef = create_definition (buf, limit, pfile, keyword == NULL);
1756 if (mdef.defn == 0)
1757 goto nope;
1759 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
1761 if ((hp = cpp_lookup (pfile, mdef.symnam, mdef.symlen, hashcode)) != NULL)
1763 int ok = 0;
1764 /* Redefining a precompiled key is ok. */
1765 if (hp->type == T_PCSTRING)
1766 ok = 1;
1767 /* Redefining a macro is ok if the definitions are the same. */
1768 else if (hp->type == T_MACRO)
1769 ok = ! compare_defs (pfile, mdef.defn, hp->value.defn);
1770 /* Redefining a constant is ok with -D. */
1771 else if (hp->type == T_CONST)
1772 ok = ! CPP_OPTIONS (pfile)->done_initializing;
1773 /* Print the warning if it's not ok. */
1774 if (!ok)
1776 U_CHAR *msg; /* what pain... */
1778 /* If we are passing through #define and #undef directives, do
1779 that for this re-definition now. */
1780 if (CPP_OPTIONS (pfile)->debug_output && keyword)
1781 pass_thru_directive (buf, limit, pfile, keyword);
1783 msg = (U_CHAR *) alloca (mdef.symlen + 22);
1784 *msg = '`';
1785 bcopy (mdef.symnam, msg + 1, mdef.symlen);
1786 strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
1787 cpp_pedwarn (pfile, msg);
1788 if (hp->type == T_MACRO)
1789 cpp_pedwarn_with_file_and_line (pfile, hp->value.defn->file, hp->value.defn->line,
1790 "this is the location of the previous definition");
1792 /* Replace the old definition. */
1793 hp->type = T_MACRO;
1794 hp->value.defn = mdef.defn;
1796 else
1798 /* If we are passing through #define and #undef directives, do
1799 that for this new definition now. */
1800 if (CPP_OPTIONS (pfile)->debug_output && keyword)
1801 pass_thru_directive (buf, limit, pfile, keyword);
1802 install (mdef.symnam, mdef.symlen, T_MACRO, 0,
1803 (char *) mdef.defn, hashcode);
1806 return 0;
1808 nope:
1810 return 1;
1813 /* This structure represents one parsed argument in a macro call.
1814 `raw' points to the argument text as written (`raw_length' is its length).
1815 `expanded' points to the argument's macro-expansion
1816 (its length is `expand_length').
1817 `stringified_length' is the length the argument would have
1818 if stringified.
1819 `use_count' is the number of times this macro arg is substituted
1820 into the macro. If the actual use count exceeds 10,
1821 the value stored is 10. */
1823 /* raw and expanded are relative to ARG_BASE */
1824 #define ARG_BASE ((pfile)->token_buffer)
1826 struct argdata {
1827 /* Strings relative to pfile->token_buffer */
1828 long raw, expanded, stringified;
1829 int raw_length, expand_length;
1830 int stringified_length;
1831 char newlines;
1832 char use_count;
1835 /* Allocate a new cpp_buffer for PFILE, and push it on the input buffer stack.
1836 If BUFFER != NULL, then use the LENGTH characters in BUFFER
1837 as the new input buffer.
1838 Return the new buffer, or NULL on failure. */
1840 cpp_buffer *
1841 cpp_push_buffer (pfile, buffer, length)
1842 cpp_reader *pfile;
1843 U_CHAR *buffer;
1844 long length;
1846 register cpp_buffer *buf = CPP_BUFFER (pfile);
1847 if (buf == pfile->buffer_stack)
1849 cpp_fatal (pfile, "%s: macro or `#include' recursion too deep",
1850 buf->fname);
1851 return NULL;
1853 buf--;
1854 bzero ((char *) buf, sizeof (cpp_buffer));
1855 CPP_BUFFER (pfile) = buf;
1856 buf->if_stack = pfile->if_stack;
1857 buf->cleanup = null_cleanup;
1858 buf->underflow = null_underflow;
1859 buf->buf = buf->cur = buffer;
1860 buf->alimit = buf->rlimit = buffer + length;
1862 return buf;
1865 cpp_buffer *
1866 cpp_pop_buffer (pfile)
1867 cpp_reader *pfile;
1869 cpp_buffer *buf = CPP_BUFFER (pfile);
1870 (*buf->cleanup) (buf, pfile);
1871 return ++CPP_BUFFER (pfile);
1874 /* Scan until CPP_BUFFER (PFILE) is exhausted into PFILE->token_buffer.
1875 Pop the buffer when done. */
1877 void
1878 cpp_scan_buffer (pfile)
1879 cpp_reader *pfile;
1881 cpp_buffer *buffer = CPP_BUFFER (pfile);
1882 for (;;)
1884 enum cpp_token token = cpp_get_token (pfile);
1885 if (token == CPP_EOF) /* Should not happen ... */
1886 break;
1887 if (token == CPP_POP && CPP_BUFFER (pfile) == buffer)
1889 cpp_pop_buffer (pfile);
1890 break;
1896 * Rescan a string (which may have escape marks) into pfile's buffer.
1897 * Place the result in pfile->token_buffer.
1899 * The input is copied before it is scanned, so it is safe to pass
1900 * it something from the token_buffer that will get overwritten
1901 * (because it follows CPP_WRITTEN). This is used by do_include.
1904 static void
1905 cpp_expand_to_buffer (pfile, buf, length)
1906 cpp_reader *pfile;
1907 U_CHAR *buf;
1908 int length;
1910 register cpp_buffer *ip;
1911 #if 0
1912 cpp_buffer obuf;
1913 #endif
1914 U_CHAR *limit = buf + length;
1915 U_CHAR *buf1;
1916 #if 0
1917 int odepth = indepth;
1918 #endif
1920 if (length < 0)
1921 abort ();
1923 /* Set up the input on the input stack. */
1925 buf1 = (U_CHAR *) alloca (length + 1);
1927 register U_CHAR *p1 = buf;
1928 register U_CHAR *p2 = buf1;
1930 while (p1 != limit)
1931 *p2++ = *p1++;
1933 buf1[length] = 0;
1935 ip = cpp_push_buffer (pfile, buf1, length);
1936 if (ip == NULL)
1937 return;
1938 ip->has_escapes = 1;
1939 #if 0
1940 ip->lineno = obuf.lineno = 1;
1941 #endif
1943 /* Scan the input, create the output. */
1944 cpp_scan_buffer (pfile);
1946 #if 0
1947 if (indepth != odepth)
1948 abort ();
1949 #endif
1951 CPP_NUL_TERMINATE (pfile);
1955 static void
1956 adjust_position (buf, limit, linep, colp)
1957 U_CHAR *buf;
1958 U_CHAR *limit;
1959 long *linep;
1960 long *colp;
1962 while (buf < limit)
1964 U_CHAR ch = *buf++;
1965 if (ch == '\n')
1966 (*linep)++, (*colp) = 1;
1967 else
1968 (*colp)++;
1972 /* Move line_base forward, updating lineno and colno. */
1974 static void
1975 update_position (pbuf)
1976 register cpp_buffer *pbuf;
1978 unsigned char *old_pos = pbuf->buf + pbuf->line_base;
1979 unsigned char *new_pos = pbuf->cur;
1980 register struct parse_marker *mark;
1981 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
1983 if (pbuf->buf + mark->position < new_pos)
1984 new_pos = pbuf->buf + mark->position;
1986 pbuf->line_base += new_pos - old_pos;
1987 adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
1990 void
1991 cpp_buf_line_and_col (pbuf, linep, colp)
1992 register cpp_buffer *pbuf;
1993 long *linep, *colp;
1995 long dummy;
1996 if (colp == NULL)
1997 colp = &dummy;
1998 if (pbuf)
2000 *linep = pbuf->lineno;
2001 *colp = pbuf->colno;
2002 adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2004 else
2006 *linep = 0;
2007 *colp = 0;
2011 /* Return the cpp_buffer that corresponds to a file (not a macro). */
2013 cpp_buffer *
2014 cpp_file_buffer (pfile)
2015 cpp_reader *pfile;
2017 cpp_buffer *ip = CPP_BUFFER (pfile);
2019 for ( ; ip != CPP_NULL_BUFFER (pfile); ip = CPP_PREV_BUFFER (ip))
2020 if (ip->fname != NULL)
2021 return ip;
2022 return NULL;
2025 static long
2026 count_newlines (buf, limit)
2027 register U_CHAR *buf;
2028 register U_CHAR *limit;
2030 register long count = 0;
2031 while (buf < limit)
2033 U_CHAR ch = *buf++;
2034 if (ch == '\n')
2035 count++;
2037 return count;
2041 * write out a #line command, for instance, after an #include file.
2042 * If CONDITIONAL is nonzero, we can omit the #line if it would
2043 * appear to be a no-op, and we can output a few newlines instead
2044 * if we want to increase the line number by a small amount.
2045 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2048 static void
2049 output_line_command (pfile, conditional, file_change)
2050 cpp_reader *pfile;
2051 int conditional;
2052 enum file_change_code file_change;
2054 long line, col;
2055 cpp_buffer *ip = CPP_BUFFER (pfile);
2057 if (ip->fname == NULL)
2058 return;
2060 update_position (ip);
2062 if (CPP_OPTIONS (pfile)->no_line_commands
2063 || CPP_OPTIONS (pfile)->no_output)
2064 return;
2066 line = CPP_BUFFER (pfile)->lineno;
2067 col = CPP_BUFFER (pfile)->colno;
2068 adjust_position (CPP_LINE_BASE (ip), ip->cur, &line, &col);
2070 if (CPP_OPTIONS (pfile)->no_line_commands)
2071 return;
2073 if (conditional) {
2074 if (line == pfile->lineno)
2075 return;
2077 /* If the inherited line number is a little too small,
2078 output some newlines instead of a #line command. */
2079 if (line > pfile->lineno && line < pfile->lineno + 8) {
2080 CPP_RESERVE (pfile, 20);
2081 while (line > pfile->lineno) {
2082 CPP_PUTC_Q (pfile, '\n');
2083 pfile->lineno++;
2085 return;
2089 #if 0
2090 /* Don't output a line number of 0 if we can help it. */
2091 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
2092 && *ip->bufp == '\n') {
2093 ip->lineno++;
2094 ip->bufp++;
2096 #endif
2098 CPP_RESERVE (pfile, 4 * strlen (ip->nominal_fname) + 50);
2100 #ifdef OUTPUT_LINE_COMMANDS
2101 static char sharp_line[] = "#line ";
2102 #else
2103 static char sharp_line[] = "# ";
2104 #endif
2105 CPP_PUTS_Q (pfile, sharp_line, sizeof(sharp_line)-1);
2108 sprintf ((char *) CPP_PWRITTEN (pfile), "%ld ", line);
2109 CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
2111 quote_string (pfile, ip->nominal_fname);
2112 if (file_change != same_file) {
2113 CPP_PUTC_Q (pfile, ' ');
2114 CPP_PUTC_Q (pfile, file_change == enter_file ? '1' : '2');
2116 /* Tell cc1 if following text comes from a system header file. */
2117 if (ip->system_header_p) {
2118 CPP_PUTC_Q (pfile, ' ');
2119 CPP_PUTC_Q (pfile, '3');
2121 #ifndef NO_IMPLICIT_EXTERN_C
2122 /* Tell cc1plus if following text should be treated as C. */
2123 if (ip->system_header_p == 2 && CPP_OPTIONS (pfile)->cplusplus) {
2124 CPP_PUTC_Q (pfile, ' ');
2125 CPP_PUTC_Q (pfile, '4');
2127 #endif
2128 CPP_PUTC_Q (pfile, '\n');
2129 pfile->lineno = line;
2133 * Parse a macro argument and append the info on PFILE's token_buffer.
2134 * REST_ARGS means to absorb the rest of the args.
2135 * Return nonzero to indicate a syntax error.
2138 static enum cpp_token
2139 macarg (pfile, rest_args)
2140 cpp_reader *pfile;
2141 int rest_args;
2143 int paren = 0;
2144 enum cpp_token token;
2145 char save_put_out_comments = CPP_OPTIONS (pfile)->put_out_comments;
2146 CPP_OPTIONS (pfile)->put_out_comments = 0;
2148 /* Try to parse as much of the argument as exists at this
2149 input stack level. */
2150 pfile->no_macro_expand++;
2151 for (;;)
2153 token = cpp_get_token (pfile);
2154 switch (token)
2156 case CPP_EOF:
2157 goto done;
2158 case CPP_POP:
2159 /* If we've hit end of file, it's an error (reported by caller).
2160 Ditto if it's the end of cpp_expand_to_buffer text.
2161 If we've hit end of macro, just continue. */
2162 if (! CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
2163 goto done;
2164 break;
2165 case CPP_LPAREN:
2166 paren++;
2167 break;
2168 case CPP_RPAREN:
2169 if (--paren < 0)
2170 goto found;
2171 break;
2172 case CPP_COMMA:
2173 /* if we've returned to lowest level and
2174 we aren't absorbing all args */
2175 if (paren == 0 && rest_args == 0)
2176 goto found;
2177 break;
2178 found:
2179 /* Remove ',' or ')' from argument buffer. */
2180 CPP_ADJUST_WRITTEN (pfile, -1);
2181 goto done;
2182 default: ;
2186 done:
2187 CPP_OPTIONS (pfile)->put_out_comments = save_put_out_comments;
2188 pfile->no_macro_expand--;
2190 return token;
2193 /* Turn newlines to spaces in the string of length LENGTH at START,
2194 except inside of string constants.
2195 The string is copied into itself with its beginning staying fixed. */
2197 static int
2198 change_newlines (start, length)
2199 U_CHAR *start;
2200 int length;
2202 register U_CHAR *ibp;
2203 register U_CHAR *obp;
2204 register U_CHAR *limit;
2205 register int c;
2207 ibp = start;
2208 limit = start + length;
2209 obp = start;
2211 while (ibp < limit) {
2212 *obp++ = c = *ibp++;
2213 switch (c) {
2215 case '\'':
2216 case '\"':
2217 /* Notice and skip strings, so that we don't delete newlines in them. */
2219 int quotec = c;
2220 while (ibp < limit) {
2221 *obp++ = c = *ibp++;
2222 if (c == quotec)
2223 break;
2224 if (c == '\n' && quotec == '\'')
2225 break;
2228 break;
2232 return obp - start;
2236 static struct tm *
2237 timestamp (pfile)
2238 cpp_reader *pfile;
2240 if (!pfile->timebuf) {
2241 time_t t = time ((time_t *) 0);
2242 pfile->timebuf = localtime (&t);
2244 return pfile->timebuf;
2247 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2248 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2252 * expand things like __FILE__. Place the expansion into the output
2253 * buffer *without* rescanning.
2256 static void
2257 special_symbol (hp, pfile)
2258 HASHNODE *hp;
2259 cpp_reader *pfile;
2261 char *buf;
2262 int len;
2263 int true_indepth;
2264 cpp_buffer *ip = NULL;
2265 struct tm *timebuf;
2267 int paren = 0; /* For special `defined' keyword */
2269 #if 0
2270 if (pcp_outfile && pcp_inside_if
2271 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
2272 cpp_error (pfile,
2273 "Predefined macro `%s' used inside `#if' during precompilation",
2274 hp->name);
2275 #endif
2277 for (ip = CPP_BUFFER (pfile); ; ip = CPP_PREV_BUFFER (ip))
2279 if (ip == CPP_NULL_BUFFER (pfile))
2281 cpp_error (pfile, "cccp error: not in any file?!");
2282 return; /* the show must go on */
2284 if (ip->fname != NULL)
2285 break;
2288 switch (hp->type)
2290 case T_FILE:
2291 case T_BASE_FILE:
2293 char *string;
2294 if (hp->type == T_BASE_FILE)
2296 while (CPP_PREV_BUFFER (ip) != CPP_NULL_BUFFER (pfile))
2297 ip = CPP_PREV_BUFFER (ip);
2299 string = ip->nominal_fname;
2301 if (!string)
2302 string = "";
2303 CPP_RESERVE (pfile, 3 + 4 * strlen (string));
2304 quote_string (pfile, string);
2305 return;
2308 case T_INCLUDE_LEVEL:
2309 true_indepth = 0;
2310 ip = CPP_BUFFER (pfile);
2311 for (; ip != CPP_NULL_BUFFER (pfile); ip = CPP_PREV_BUFFER (ip))
2312 if (ip->fname != NULL)
2313 true_indepth++;
2315 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
2316 sprintf (buf, "%d", true_indepth - 1);
2317 break;
2319 case T_VERSION:
2320 buf = (char *) alloca (3 + strlen (version_string));
2321 sprintf (buf, "\"%s\"", version_string);
2322 break;
2324 #ifndef NO_BUILTIN_SIZE_TYPE
2325 case T_SIZE_TYPE:
2326 buf = SIZE_TYPE;
2327 break;
2328 #endif
2330 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2331 case T_PTRDIFF_TYPE:
2332 buf = PTRDIFF_TYPE;
2333 break;
2334 #endif
2336 case T_WCHAR_TYPE:
2337 buf = CPP_WCHAR_TYPE (pfile);
2338 break;
2340 case T_USER_LABEL_PREFIX_TYPE:
2341 buf = USER_LABEL_PREFIX;
2342 break;
2344 case T_REGISTER_PREFIX_TYPE:
2345 buf = REGISTER_PREFIX;
2346 break;
2348 case T_CONST:
2349 buf = (char *) alloca (4 * sizeof (int));
2350 sprintf (buf, "%d", hp->value.ival);
2351 #ifdef STDC_0_IN_SYSTEM_HEADERS
2352 if (ip->system_header_p
2353 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
2354 && ! cpp_lookup (pfile, (U_CHAR *) "__STRICT_ANSI__", -1, -1))
2355 strcpy (buf, "0");
2356 #endif
2357 #if 0
2358 if (pcp_inside_if && pcp_outfile)
2359 /* Output a precondition for this macro use */
2360 fprintf (pcp_outfile, "#define %s %d\n", hp->name, hp->value.ival);
2361 #endif
2362 break;
2364 case T_SPECLINE:
2366 long line = ip->lineno;
2367 long col = ip->colno;
2368 adjust_position (CPP_LINE_BASE (ip), ip->cur, &line, &col);
2370 buf = (char *) alloca (10);
2371 sprintf (buf, "%ld", line);
2373 break;
2375 case T_DATE:
2376 case T_TIME:
2377 buf = (char *) alloca (20);
2378 timebuf = timestamp (pfile);
2379 if (hp->type == T_DATE)
2380 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2381 timebuf->tm_mday, timebuf->tm_year + 1900);
2382 else
2383 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2384 timebuf->tm_sec);
2385 break;
2387 case T_SPEC_DEFINED:
2388 buf = " 0 "; /* Assume symbol is not defined */
2389 ip = CPP_BUFFER (pfile);
2390 SKIP_WHITE_SPACE (ip->cur);
2391 if (*ip->cur == '(')
2393 paren++;
2394 ip->cur++; /* Skip over the paren */
2395 SKIP_WHITE_SPACE (ip->cur);
2398 if (!is_idstart[*ip->cur])
2399 goto oops;
2400 if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '"'))
2401 goto oops;
2402 if ((hp = cpp_lookup (pfile, ip->cur, -1, -1)))
2404 #if 0
2405 if (pcp_outfile && pcp_inside_if
2406 && (hp->type == T_CONST
2407 || (hp->type == T_MACRO && hp->value.defn->predefined)))
2408 /* Output a precondition for this macro use. */
2409 fprintf (pcp_outfile, "#define %s\n", hp->name);
2410 #endif
2411 buf = " 1 ";
2413 #if 0
2414 else
2415 if (pcp_outfile && pcp_inside_if)
2417 /* Output a precondition for this macro use */
2418 U_CHAR *cp = ip->bufp;
2419 fprintf (pcp_outfile, "#undef ");
2420 while (is_idchar[*cp]) /* Ick! */
2421 fputc (*cp++, pcp_outfile);
2422 putc ('\n', pcp_outfile);
2424 #endif
2425 while (is_idchar[*ip->cur])
2426 ++ip->cur;
2427 SKIP_WHITE_SPACE (ip->cur);
2428 if (paren)
2430 if (*ip->cur != ')')
2431 goto oops;
2432 ++ip->cur;
2434 break;
2436 oops:
2438 cpp_error (pfile, "`defined' without an identifier");
2439 break;
2441 default:
2442 cpp_error (pfile, "cccp error: invalid special hash type"); /* time for gdb */
2443 abort ();
2445 len = strlen (buf);
2446 CPP_RESERVE (pfile, len + 1);
2447 CPP_PUTS_Q (pfile, buf, len);
2448 CPP_NUL_TERMINATE_Q (pfile);
2450 return;
2453 /* Write out a #define command for the special named MACRO_NAME
2454 to PFILE's token_buffer. */
2456 static void
2457 dump_special_to_buffer (pfile, macro_name)
2458 cpp_reader *pfile;
2459 char *macro_name;
2461 static char define_directive[] = "#define ";
2462 int macro_name_length = strlen (macro_name);
2463 output_line_command (pfile, 0, same_file);
2464 CPP_RESERVE (pfile, sizeof(define_directive) + macro_name_length);
2465 CPP_PUTS_Q (pfile, define_directive, sizeof(define_directive)-1);
2466 CPP_PUTS_Q (pfile, macro_name, macro_name_length);
2467 CPP_PUTC_Q (pfile, ' ');
2468 cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
2469 CPP_PUTC (pfile, '\n');
2472 /* Initialize the built-in macros. */
2474 static void
2475 initialize_builtins (pfile)
2476 cpp_reader *pfile;
2478 install ((U_CHAR *)"__LINE__", -1, T_SPECLINE, 0, 0, -1);
2479 install ((U_CHAR *)"__DATE__", -1, T_DATE, 0, 0, -1);
2480 install ((U_CHAR *)"__FILE__", -1, T_FILE, 0, 0, -1);
2481 install ((U_CHAR *)"__BASE_FILE__", -1, T_BASE_FILE, 0, 0, -1);
2482 install ((U_CHAR *)"__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, 0, -1);
2483 install ((U_CHAR *)"__VERSION__", -1, T_VERSION, 0, 0, -1);
2484 #ifndef NO_BUILTIN_SIZE_TYPE
2485 install ((U_CHAR *)"__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, 0, -1);
2486 #endif
2487 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2488 install ((U_CHAR *)"__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, 0, -1);
2489 #endif
2490 install ((U_CHAR *)"__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, 0, -1);
2491 install ((U_CHAR *)"__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE, 0, 0, -1);
2492 install ((U_CHAR *)"__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, 0, -1);
2493 install ((U_CHAR *)"__TIME__", -1, T_TIME, 0, 0, -1);
2494 if (!CPP_TRADITIONAL (pfile))
2495 install ((U_CHAR *)"__STDC__", -1, T_CONST, STDC_VALUE, 0, -1);
2496 if (CPP_OPTIONS (pfile)->objc)
2497 install ((U_CHAR *)"__OBJC__", -1, T_CONST, 1, 0, -1);
2498 /* This is supplied using a -D by the compiler driver
2499 so that it is present only when truly compiling with GNU C. */
2500 /* install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
2502 if (CPP_OPTIONS (pfile)->debug_output)
2504 dump_special_to_buffer (pfile, "__BASE_FILE__");
2505 dump_special_to_buffer (pfile, "__VERSION__");
2506 #ifndef NO_BUILTIN_SIZE_TYPE
2507 dump_special_to_buffer (pfile, "__SIZE_TYPE__");
2508 #endif
2509 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2510 dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
2511 #endif
2512 dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
2513 dump_special_to_buffer (pfile, "__DATE__");
2514 dump_special_to_buffer (pfile, "__TIME__");
2515 if (!CPP_TRADITIONAL (pfile))
2516 dump_special_to_buffer (pfile, "__STDC__");
2517 if (CPP_OPTIONS (pfile)->objc)
2518 dump_special_to_buffer (pfile, "__OBJC__");
2522 /* Return 1 iff a token ending in C1 followed directly by a token C2
2523 could cause mis-tokenization. */
2525 static int
2526 unsafe_chars (c1, c2)
2527 int c1, c2;
2529 switch (c1)
2531 case '+': case '-':
2532 if (c2 == c1 || c2 == '=')
2533 return 1;
2534 goto letter;
2535 case '.':
2536 case '0': case '1': case '2': case '3': case '4':
2537 case '5': case '6': case '7': case '8': case '9':
2538 case 'e': case 'E': case 'p': case 'P':
2539 if (c2 == '-' || c2 == '+')
2540 return 1; /* could extend a pre-processing number */
2541 goto letter;
2542 case 'L':
2543 if (c2 == '\'' || c2 == '\"')
2544 return 1; /* Could turn into L"xxx" or L'xxx'. */
2545 goto letter;
2546 letter:
2547 case '_':
2548 case 'a': case 'b': case 'c': case 'd': case 'f':
2549 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2550 case 'm': case 'n': case 'o': case 'q': case 'r':
2551 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2552 case 'y': case 'z':
2553 case 'A': case 'B': case 'C': case 'D': case 'F':
2554 case 'G': case 'H': case 'I': case 'J': case 'K':
2555 case 'M': case 'N': case 'O': case 'Q': case 'R':
2556 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2557 case 'Y': case 'Z':
2558 /* We're in the middle of either a name or a pre-processing number. */
2559 return (is_idchar[c2] || c2 == '.');
2560 case '<': case '>': case '!': case '%': case '#': case ':':
2561 case '^': case '&': case '|': case '*': case '/': case '=':
2562 return (c2 == c1 || c2 == '=');
2564 return 0;
2567 /* Expand a macro call.
2568 HP points to the symbol that is the macro being called.
2569 Put the result of expansion onto the input stack
2570 so that subsequent input by our caller will use it.
2572 If macro wants arguments, caller has already verified that
2573 an argument list follows; arguments come from the input stack. */
2575 static void
2576 macroexpand (pfile, hp)
2577 cpp_reader *pfile;
2578 HASHNODE *hp;
2580 int nargs;
2581 DEFINITION *defn = hp->value.defn;
2582 register U_CHAR *xbuf;
2583 long start_line, start_column;
2584 int xbuf_len;
2585 struct argdata *args;
2586 long old_written = CPP_WRITTEN (pfile);
2587 #if 0
2588 int start_line = instack[indepth].lineno;
2589 #endif
2590 int rest_args, rest_zero;
2591 register int i;
2593 #if 0
2594 CHECK_DEPTH (return;);
2595 #endif
2597 #if 0
2598 /* This macro is being used inside a #if, which means it must be */
2599 /* recorded as a precondition. */
2600 if (pcp_inside_if && pcp_outfile && defn->predefined)
2601 dump_single_macro (hp, pcp_outfile);
2602 #endif
2604 pfile->output_escapes++;
2605 cpp_buf_line_and_col (cpp_file_buffer (pfile), &start_line, &start_column);
2607 nargs = defn->nargs;
2609 if (nargs >= 0)
2611 enum cpp_token token;
2613 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
2615 for (i = 0; i < nargs; i++)
2617 args[i].raw = args[i].expanded = 0;
2618 args[i].raw_length = 0;
2619 args[i].expand_length = args[i].stringified_length = -1;
2620 args[i].use_count = 0;
2623 /* Parse all the macro args that are supplied. I counts them.
2624 The first NARGS args are stored in ARGS.
2625 The rest are discarded. If rest_args is set then we assume
2626 macarg absorbed the rest of the args. */
2627 i = 0;
2628 rest_args = 0;
2629 rest_args = 0;
2630 FORWARD(1); /* Discard the open-parenthesis before the first arg. */
2633 if (rest_args)
2634 continue;
2635 if (i < nargs || (nargs == 0 && i == 0))
2637 /* if we are working on last arg which absorbs rest of args... */
2638 if (i == nargs - 1 && defn->rest_args)
2639 rest_args = 1;
2640 args[i].raw = CPP_WRITTEN (pfile);
2641 token = macarg (pfile, rest_args);
2642 args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
2643 args[i].newlines = 0; /* FIXME */
2645 else
2646 token = macarg (pfile, 0);
2647 if (token == CPP_EOF || token == CPP_POP)
2649 cpp_error_with_line (pfile, start_line, start_column,
2650 "unterminated macro call");
2651 return;
2653 i++;
2654 } while (token == CPP_COMMA);
2656 /* If we got one arg but it was just whitespace, call that 0 args. */
2657 if (i == 1)
2659 register U_CHAR *bp = ARG_BASE + args[0].raw;
2660 register U_CHAR *lim = bp + args[0].raw_length;
2661 /* cpp.texi says for foo ( ) we provide one argument.
2662 However, if foo wants just 0 arguments, treat this as 0. */
2663 if (nargs == 0)
2664 while (bp != lim && is_space[*bp]) bp++;
2665 if (bp == lim)
2666 i = 0;
2669 /* Don't output an error message if we have already output one for
2670 a parse error above. */
2671 rest_zero = 0;
2672 if (nargs == 0 && i > 0)
2674 cpp_error (pfile, "arguments given to macro `%s'", hp->name);
2676 else if (i < nargs)
2678 /* traditional C allows foo() if foo wants one argument. */
2679 if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
2681 /* the rest args token is allowed to absorb 0 tokens */
2682 else if (i == nargs - 1 && defn->rest_args)
2683 rest_zero = 1;
2684 else if (i == 0)
2685 cpp_error (pfile, "macro `%s' used without args", hp->name);
2686 else if (i == 1)
2687 cpp_error (pfile, "macro `%s' used with just one arg", hp->name);
2688 else
2689 cpp_error (pfile, "macro `%s' used with only %d args",
2690 hp->name, i);
2692 else if (i > nargs)
2694 cpp_error (pfile,
2695 "macro `%s' used with too many (%d) args", hp->name, i);
2699 /* If macro wants zero args, we parsed the arglist for checking only.
2700 Read directly from the macro definition. */
2701 if (nargs <= 0)
2703 xbuf = defn->expansion;
2704 xbuf_len = defn->length;
2706 else
2708 register U_CHAR *exp = defn->expansion;
2709 register int offset; /* offset in expansion,
2710 copied a piece at a time */
2711 register int totlen; /* total amount of exp buffer filled so far */
2713 register struct reflist *ap, *last_ap;
2715 /* Macro really takes args. Compute the expansion of this call. */
2717 /* Compute length in characters of the macro's expansion.
2718 Also count number of times each arg is used. */
2719 xbuf_len = defn->length;
2720 for (ap = defn->pattern; ap != NULL; ap = ap->next)
2722 if (ap->stringify)
2724 register struct argdata *arg = &args[ap->argno];
2725 /* Stringify if it hasn't already been */
2726 if (arg->stringified_length < 0)
2728 int arglen = arg->raw_length;
2729 int escaped = 0;
2730 int in_string = 0;
2731 int c;
2732 /* Initially need_space is -1. Otherwise, 1 means the
2733 previous character was a space, but we suppressed it;
2734 0 means the previous character was a non-space. */
2735 int need_space = -1;
2736 i = 0;
2737 arg->stringified = CPP_WRITTEN (pfile);
2738 if (!CPP_TRADITIONAL (pfile))
2739 CPP_PUTC (pfile, '\"'); /* insert beginning quote */
2740 for (; i < arglen; i++)
2742 c = (ARG_BASE + arg->raw)[i];
2744 if (! in_string)
2746 /* Internal sequences of whitespace are replaced by
2747 one space except within an string or char token.*/
2748 if (is_space[c])
2750 if (CPP_WRITTEN (pfile) > (unsigned)arg->stringified
2751 && (CPP_PWRITTEN (pfile))[-1] == '@')
2753 /* "@ " escape markers are removed */
2754 CPP_ADJUST_WRITTEN (pfile, -1);
2755 continue;
2757 if (need_space == 0)
2758 need_space = 1;
2759 continue;
2761 else if (need_space > 0)
2762 CPP_PUTC (pfile, ' ');
2763 need_space = 0;
2766 if (escaped)
2767 escaped = 0;
2768 else
2770 if (c == '\\')
2771 escaped = 1;
2772 if (in_string)
2774 if (c == in_string)
2775 in_string = 0;
2777 else if (c == '\"' || c == '\'')
2778 in_string = c;
2781 /* Escape these chars */
2782 if (c == '\"' || (in_string && c == '\\'))
2783 CPP_PUTC (pfile, '\\');
2784 if (ISPRINT (c))
2785 CPP_PUTC (pfile, c);
2786 else
2788 CPP_RESERVE (pfile, 4);
2789 sprintf ((char *)CPP_PWRITTEN (pfile), "\\%03o",
2790 (unsigned int) c);
2791 CPP_ADJUST_WRITTEN (pfile, 4);
2794 if (!CPP_TRADITIONAL (pfile))
2795 CPP_PUTC (pfile, '\"'); /* insert ending quote */
2796 arg->stringified_length
2797 = CPP_WRITTEN (pfile) - arg->stringified;
2799 xbuf_len += args[ap->argno].stringified_length;
2801 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
2802 /* Add 4 for two newline-space markers to prevent
2803 token concatenation. */
2804 xbuf_len += args[ap->argno].raw_length + 4;
2805 else
2807 /* We have an ordinary (expanded) occurrence of the arg.
2808 So compute its expansion, if we have not already. */
2809 if (args[ap->argno].expand_length < 0)
2811 args[ap->argno].expanded = CPP_WRITTEN (pfile);
2812 cpp_expand_to_buffer (pfile,
2813 ARG_BASE + args[ap->argno].raw,
2814 args[ap->argno].raw_length);
2816 args[ap->argno].expand_length
2817 = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
2820 /* Add 4 for two newline-space markers to prevent
2821 token concatenation. */
2822 xbuf_len += args[ap->argno].expand_length + 4;
2824 if (args[ap->argno].use_count < 10)
2825 args[ap->argno].use_count++;
2828 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
2830 /* Generate in XBUF the complete expansion
2831 with arguments substituted in.
2832 TOTLEN is the total size generated so far.
2833 OFFSET is the index in the definition
2834 of where we are copying from. */
2835 offset = totlen = 0;
2836 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
2837 last_ap = ap, ap = ap->next)
2839 register struct argdata *arg = &args[ap->argno];
2840 int count_before = totlen;
2842 /* Add chars to XBUF. */
2843 for (i = 0; i < ap->nchars; i++, offset++)
2844 xbuf[totlen++] = exp[offset];
2846 /* If followed by an empty rest arg with concatenation,
2847 delete the last run of nonwhite chars. */
2848 if (rest_zero && totlen > count_before
2849 && ((ap->rest_args && ap->raw_before)
2850 || (last_ap != NULL && last_ap->rest_args
2851 && last_ap->raw_after)))
2853 /* Delete final whitespace. */
2854 while (totlen > count_before && is_space[xbuf[totlen - 1]])
2855 totlen--;
2857 /* Delete the nonwhites before them. */
2858 while (totlen > count_before && ! is_space[xbuf[totlen - 1]])
2859 totlen--;
2862 if (ap->stringify != 0)
2864 bcopy (ARG_BASE + arg->stringified,
2865 xbuf + totlen, arg->stringified_length);
2866 totlen += arg->stringified_length;
2868 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
2870 U_CHAR *p1 = ARG_BASE + arg->raw;
2871 U_CHAR *l1 = p1 + arg->raw_length;
2872 if (ap->raw_before)
2874 while (p1 != l1 && is_space[*p1]) p1++;
2875 while (p1 != l1 && is_idchar[*p1])
2876 xbuf[totlen++] = *p1++;
2878 if (ap->raw_after)
2880 /* Arg is concatenated after: delete trailing whitespace,
2881 whitespace markers, and no-reexpansion markers. */
2882 while (p1 != l1)
2884 if (is_space[l1[-1]]) l1--;
2885 else if (l1[-1] == '@')
2887 U_CHAR *p2 = l1 - 1;
2888 /* If whitespace is preceded by an odd number
2889 of `@' signs, the last `@' was a whitespace
2890 marker; drop it too. */
2891 while (p2 != p1 && p2[0] == '@') p2--;
2892 if ((l1 - p2) & 1)
2893 l1--;
2894 break;
2896 else if (l1[-1] == '-')
2898 U_CHAR *p2 = l1 - 1;
2899 /* If a `-' is preceded by an odd number of
2900 `@' signs then it and the last `@' are
2901 a no-reexpansion marker. */
2902 while (p2 != p1 && p2[0] == '@') p2--;
2903 if ((l1 - p2) & 1)
2904 l1 -= 2;
2905 else
2906 break;
2908 else break;
2912 /* Delete any no-reexpansion marker that precedes
2913 an identifier at the beginning of the argument. */
2914 if (p1[0] == '@' && p1[1] == '-')
2915 p1 += 2;
2917 bcopy (p1, xbuf + totlen, l1 - p1);
2918 totlen += l1 - p1;
2920 else
2922 U_CHAR *expanded = ARG_BASE + arg->expanded;
2923 if (!ap->raw_before && totlen > 0 && arg->expand_length
2924 && !CPP_TRADITIONAL(pfile)
2925 && unsafe_chars (xbuf[totlen-1], expanded[0]))
2927 xbuf[totlen++] = '@';
2928 xbuf[totlen++] = ' ';
2931 bcopy (expanded, xbuf + totlen, arg->expand_length);
2932 totlen += arg->expand_length;
2934 if (!ap->raw_after && totlen > 0 && offset < defn->length
2935 && !CPP_TRADITIONAL(pfile)
2936 && unsafe_chars (xbuf[totlen-1], exp[offset]))
2938 xbuf[totlen++] = '@';
2939 xbuf[totlen++] = ' ';
2942 /* If a macro argument with newlines is used multiple times,
2943 then only expand the newlines once. This avoids creating
2944 output lines which don't correspond to any input line,
2945 which confuses gdb and gcov. */
2946 if (arg->use_count > 1 && arg->newlines > 0)
2948 /* Don't bother doing change_newlines for subsequent
2949 uses of arg. */
2950 arg->use_count = 1;
2951 arg->expand_length
2952 = change_newlines (expanded, arg->expand_length);
2956 if (totlen > xbuf_len)
2957 abort ();
2960 /* if there is anything left of the definition
2961 after handling the arg list, copy that in too. */
2963 for (i = offset; i < defn->length; i++)
2965 /* if we've reached the end of the macro */
2966 if (exp[i] == ')')
2967 rest_zero = 0;
2968 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
2969 && last_ap->raw_after))
2970 xbuf[totlen++] = exp[i];
2973 xbuf[totlen] = 0;
2974 xbuf_len = totlen;
2978 pfile->output_escapes--;
2980 /* Now put the expansion on the input stack
2981 so our caller will commence reading from it. */
2982 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
2983 CPP_BUFFER (pfile)->has_escapes = 1;
2985 /* Pop the space we've used in the token_buffer for argument expansion. */
2986 CPP_SET_WRITTEN (pfile, old_written);
2988 /* Recursive macro use sometimes works traditionally.
2989 #define foo(x,y) bar (x (y,0), y)
2990 foo (foo, baz) */
2992 if (!CPP_TRADITIONAL (pfile))
2993 hp->type = T_DISABLED;
2996 static void
2997 push_macro_expansion (pfile, xbuf, xbuf_len, hp)
2998 cpp_reader *pfile;
2999 register U_CHAR *xbuf;
3000 int xbuf_len;
3001 HASHNODE *hp;
3003 register cpp_buffer *mbuf = cpp_push_buffer (pfile, xbuf, xbuf_len);
3004 if (mbuf == NULL)
3005 return;
3006 mbuf->cleanup = macro_cleanup;
3007 mbuf->data = hp;
3009 /* The first chars of the expansion should be a "@ " added by
3010 collect_expansion. This is to prevent accidental token-pasting
3011 between the text preceding the macro invocation, and the macro
3012 expansion text.
3014 We would like to avoid adding unneeded spaces (for the sake of
3015 tools that use cpp, such as imake). In some common cases we can
3016 tell that it is safe to omit the space.
3018 The character before the macro invocation cannot have been an
3019 idchar (or else it would have been pasted with the idchars of
3020 the macro name). Therefore, if the first non-space character
3021 of the expansion is an idchar, we do not need the extra space
3022 to prevent token pasting.
3024 Also, we don't need the extra space if the first char is '(',
3025 or some other (less common) characters. */
3027 if (xbuf[0] == '@' && xbuf[1] == ' '
3028 && (is_idchar[xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3029 || xbuf[2] == '\"'))
3030 mbuf->cur += 2;
3033 /* Like cpp_get_token, except that it does not read past end-of-line.
3034 Also, horizontal space is skipped, and macros are popped. */
3036 static enum cpp_token
3037 get_directive_token (pfile)
3038 cpp_reader *pfile;
3040 for (;;)
3042 long old_written = CPP_WRITTEN (pfile);
3043 enum cpp_token token;
3044 cpp_skip_hspace (pfile);
3045 if (PEEKC () == '\n')
3046 return CPP_VSPACE;
3047 token = cpp_get_token (pfile);
3048 switch (token)
3050 case CPP_POP:
3051 if (! CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
3052 return token;
3053 /* ... else fall though ... */
3054 case CPP_HSPACE: case CPP_COMMENT:
3055 CPP_SET_WRITTEN (pfile, old_written);
3056 break;
3057 default:
3058 return token;
3063 /* Handle #include and #import.
3064 This function expects to see "fname" or <fname> on the input.
3066 The input is normally in part of the output_buffer following
3067 CPP_WRITTEN, and will get overwritten by output_line_command.
3068 I.e. in input file specification has been popped by handle_directive.
3069 This is safe. */
3071 static int
3072 do_include (pfile, keyword, unused1, unused2)
3073 cpp_reader *pfile;
3074 struct directive *keyword;
3075 U_CHAR *unused1 ATTRIBUTE_UNUSED, *unused2 ATTRIBUTE_UNUSED;
3077 int importing = (keyword->type == T_IMPORT);
3078 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3079 char *fname; /* Dynamically allocated fname buffer */
3080 char *pcftry;
3081 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
3082 enum cpp_token token;
3084 /* Chain of dirs to search */
3085 struct file_name_list *search_start = CPP_OPTIONS (pfile)->include;
3086 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3087 struct file_name_list *searchptr = 0;
3088 long old_written = CPP_WRITTEN (pfile);
3090 int flen;
3092 int f; /* file number */
3094 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
3095 char *pcfbuf;
3096 #if 0
3097 int pcf = -1;
3098 char *pcfbuflimit;
3099 #endif
3100 int pcfnum;
3101 f= -1; /* JF we iz paranoid! */
3103 if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
3105 if (importing)
3106 cpp_pedwarn (pfile, "ANSI C does not allow `#import'");
3107 if (skip_dirs)
3108 cpp_pedwarn (pfile, "ANSI C does not allow `#include_next'");
3111 if (importing && CPP_OPTIONS (pfile)->warn_import
3112 && !CPP_OPTIONS (pfile)->inhibit_warnings
3113 && !CPP_BUFFER (pfile)->system_header_p && !pfile->import_warning)
3115 pfile->import_warning = 1;
3116 cpp_warning (pfile, "using `#import' is not recommended");
3117 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
3118 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
3119 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
3120 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
3121 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
3122 fprintf (stderr, " ... <real contents of file> ...\n");
3123 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
3124 fprintf (stderr, "Then users can use `#include' any number of times.\n");
3125 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
3126 fprintf (stderr, "when it is equipped with such a conditional.\n");
3129 pfile->parsing_include_directive++;
3130 token = get_directive_token (pfile);
3131 pfile->parsing_include_directive--;
3133 if (token == CPP_STRING)
3135 /* FIXME - check no trailing garbage */
3136 fbeg = pfile->token_buffer + old_written + 1;
3137 fend = CPP_PWRITTEN (pfile) - 1;
3138 if (fbeg[-1] == '<')
3140 angle_brackets = 1;
3141 /* If -I-, start with the first -I dir after the -I-. */
3142 if (CPP_OPTIONS (pfile)->first_bracket_include)
3143 search_start = CPP_OPTIONS (pfile)->first_bracket_include;
3145 /* If -I- was specified, don't search current dir, only spec'd ones. */
3146 else if (! CPP_OPTIONS (pfile)->ignore_srcdir)
3148 cpp_buffer *fp = CPP_BUFFER (pfile);
3149 /* We have "filename". Figure out directory this source
3150 file is coming from and put it on the front of the list. */
3152 for ( ; fp != CPP_NULL_BUFFER (pfile); fp = CPP_PREV_BUFFER (fp))
3154 int n;
3155 char *ep,*nam;
3157 if ((nam = fp->nominal_fname) != NULL)
3159 /* Found a named file. Figure out dir of the file,
3160 and put it in front of the search list. */
3161 dsp[0].next = search_start;
3162 search_start = dsp;
3163 #ifndef VMS
3164 ep = rindex (nam, '/');
3165 #else /* VMS */
3166 ep = rindex (nam, ']');
3167 if (ep == NULL) ep = rindex (nam, '>');
3168 if (ep == NULL) ep = rindex (nam, ':');
3169 if (ep != NULL) ep++;
3170 #endif /* VMS */
3171 if (ep != NULL)
3173 n = ep - nam;
3174 dsp[0].fname = (char *) alloca (n + 1);
3175 strncpy (dsp[0].fname, nam, n);
3176 dsp[0].fname[n] = '\0';
3177 if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3178 pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3180 else
3182 dsp[0].fname = 0; /* Current directory */
3184 dsp[0].got_name_map = 0;
3185 break;
3190 #ifdef VMS
3191 else if (token == CPP_NAME)
3194 * Support '#include xyz' like VAX-C to allow for easy use of all the
3195 * decwindow include files. It defaults to '#include <xyz.h>' (so the
3196 * code from case '<' is repeated here) and generates a warning.
3198 cpp_warning (pfile,
3199 "VAX-C-style include specification found, use '#include <filename.h>' !");
3200 angle_brackets = 1;
3201 /* If -I-, start with the first -I dir after the -I-. */
3202 if (CPP_OPTIONS (pfile)->first_bracket_include)
3203 search_start = CPP_OPTIONS (pfile)->first_bracket_include;
3204 fbeg = pfile->token_buffer + old_written;
3205 fend = CPP_PWRITTEN (pfile);
3207 #endif
3208 else
3210 cpp_error (pfile,
3211 "`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
3212 CPP_SET_WRITTEN (pfile, old_written);
3213 skip_rest_of_line (pfile);
3214 return 0;
3217 *fend = 0;
3219 token = get_directive_token (pfile);
3220 if (token != CPP_VSPACE)
3222 cpp_error (pfile, "junk at end of `#include'");
3223 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3224 token = get_directive_token (pfile);
3227 /* For #include_next, skip in the search path
3228 past the dir in which the containing file was found. */
3229 if (skip_dirs)
3231 cpp_buffer *fp = CPP_BUFFER (pfile);
3232 for (; fp != CPP_NULL_BUFFER (pfile); fp = CPP_PREV_BUFFER (fp))
3233 if (fp->fname != NULL)
3235 /* fp->dir is null if the containing file was specified with
3236 an absolute file name. In that case, don't skip anything. */
3237 if (fp->dir == SELF_DIR_DUMMY)
3238 search_start = CPP_OPTIONS (pfile)->include;
3239 else if (fp->dir)
3240 search_start = fp->dir->next;
3241 break;
3245 CPP_SET_WRITTEN (pfile, old_written);
3247 flen = fend - fbeg;
3249 if (flen == 0)
3251 cpp_error (pfile, "empty file name in `#%s'", keyword->name);
3252 return 0;
3255 /* Allocate this permanently, because it gets stored in the definitions
3256 of macros. */
3257 fname = (char *) xmalloc (pfile->max_include_len + flen + 4);
3258 /* + 2 above for slash and terminating null. */
3259 /* + 2 added for '.h' on VMS (to support '#include filename') */
3261 /* If specified file name is absolute, just open it. */
3263 if (*fbeg == '/') {
3264 strncpy (fname, fbeg, flen);
3265 fname[flen] = 0;
3266 if (redundant_include_p (pfile, fname))
3267 return 0;
3268 if (importing)
3269 f = lookup_import (pfile, fname, NULL_PTR);
3270 else
3271 f = open_include_file (pfile, fname, NULL_PTR);
3272 if (f == -2)
3273 return 0; /* Already included this file */
3274 } else {
3275 /* Search directory path, trying to open the file.
3276 Copy each filename tried into FNAME. */
3278 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
3279 if (searchptr->fname) {
3280 /* The empty string in a search path is ignored.
3281 This makes it possible to turn off entirely
3282 a standard piece of the list. */
3283 if (searchptr->fname[0] == 0)
3284 continue;
3285 strcpy (fname, searchptr->fname);
3286 strcat (fname, "/");
3287 fname[strlen (fname) + flen] = 0;
3288 } else {
3289 fname[0] = 0;
3291 strncat (fname, fbeg, flen);
3292 #ifdef VMS
3293 /* Change this 1/2 Unix 1/2 VMS file specification into a
3294 full VMS file specification */
3295 if (searchptr->fname && (searchptr->fname[0] != 0)) {
3296 /* Fix up the filename */
3297 hack_vms_include_specification (fname);
3298 } else {
3299 /* This is a normal VMS filespec, so use it unchanged. */
3300 strncpy (fname, fbeg, flen);
3301 fname[flen] = 0;
3302 /* if it's '#include filename', add the missing .h */
3303 if (index(fname,'.')==NULL) {
3304 strcat (fname, ".h");
3307 #endif /* VMS */
3308 /* ??? There are currently 3 separate mechanisms for avoiding processing
3309 of redundant include files: #import, #pragma once, and
3310 redundant_include_p. It would be nice if they were unified. */
3311 if (redundant_include_p (pfile, fname))
3312 return 0;
3313 if (importing)
3314 f = lookup_import (pfile, fname, searchptr);
3315 else
3316 f = open_include_file (pfile, fname, searchptr);
3317 if (f == -2)
3318 return 0; /* Already included this file */
3319 #ifdef EACCES
3320 else if (f == -1 && errno == EACCES)
3321 cpp_warning (pfile, "Header file %s exists, but is not readable",
3322 fname);
3323 #endif
3324 if (f >= 0)
3325 break;
3329 if (f < 0)
3331 /* A file that was not found. */
3332 strncpy (fname, fbeg, flen);
3333 fname[flen] = 0;
3334 /* If generating dependencies and -MG was specified, we assume missing
3335 files are leaf files, living in the same directory as the source file
3336 or other similar place; these missing files may be generated from
3337 other files and may not exist yet (eg: y.tab.h). */
3339 if (CPP_OPTIONS(pfile)->print_deps_missing_files
3340 && CPP_PRINT_DEPS (pfile)
3341 > (angle_brackets || (pfile->system_include_depth > 0)))
3343 /* If it was requested as a system header file,
3344 then assume it belongs in the first place to look for such. */
3345 if (angle_brackets)
3347 for (searchptr = search_start; searchptr;
3348 searchptr = searchptr->next)
3350 if (searchptr->fname)
3352 char *p;
3354 if (searchptr->fname[0] == 0)
3355 continue;
3356 p = (char *) alloca (strlen (searchptr->fname)
3357 + strlen (fname) + 2);
3358 strcpy (p, searchptr->fname);
3359 strcat (p, "/");
3360 strcat (p, fname);
3361 deps_output (pfile, p, ' ');
3362 break;
3366 else
3368 /* Otherwise, omit the directory, as if the file existed
3369 in the directory with the source. */
3370 deps_output (pfile, fname, ' ');
3373 /* If -M was specified, and this header file won't be added to the
3374 dependency list, then don't count this as an error, because we can
3375 still produce correct output. Otherwise, we can't produce correct
3376 output, because there may be dependencies we need inside the missing
3377 file, and we don't know what directory this missing file exists in.*/
3378 else if (CPP_PRINT_DEPS (pfile)
3379 && (CPP_PRINT_DEPS (pfile)
3380 <= (angle_brackets || (pfile->system_include_depth > 0))))
3381 cpp_warning (pfile, "No include path in which to find %s", fname);
3382 else if (search_start)
3383 cpp_error_from_errno (pfile, fname);
3384 else
3385 cpp_error (pfile, "No include path in which to find %s", fname);
3387 else {
3388 /* Check to see if this include file is a once-only include file.
3389 If so, give up. */
3391 struct file_name_list *ptr;
3393 for (ptr = pfile->dont_repeat_files; ptr; ptr = ptr->next) {
3394 if (!strcmp (ptr->fname, fname)) {
3395 close (f);
3396 return 0; /* This file was once'd. */
3400 for (ptr = pfile->all_include_files; ptr; ptr = ptr->next) {
3401 if (!strcmp (ptr->fname, fname))
3402 break; /* This file was included before. */
3405 if (ptr == 0) {
3406 /* This is the first time for this file. */
3407 /* Add it to list of files included. */
3409 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
3410 ptr->control_macro = 0;
3411 ptr->c_system_include_path = 0;
3412 ptr->next = pfile->all_include_files;
3413 pfile->all_include_files = ptr;
3414 ptr->fname = savestring (fname);
3415 ptr->got_name_map = 0;
3417 /* For -M, add this file to the dependencies. */
3418 if (CPP_PRINT_DEPS (pfile)
3419 > (angle_brackets || (pfile->system_include_depth > 0)))
3420 deps_output (pfile, fname, ' ');
3423 /* Handle -H option. */
3424 if (CPP_OPTIONS(pfile)->print_include_names)
3426 cpp_buffer *buf = CPP_BUFFER (pfile);
3427 while ((buf = CPP_PREV_BUFFER (buf)) != CPP_NULL_BUFFER (pfile))
3428 putc ('.', stderr);
3429 fprintf (stderr, "%s\n", fname);
3432 if (angle_brackets)
3433 pfile->system_include_depth++;
3435 /* Actually process the file. */
3437 /* Record file on "seen" list for #import. */
3438 add_import (pfile, f, fname);
3440 pcftry = (char *) alloca (strlen (fname) + 30);
3441 pcfbuf = 0;
3442 pcfnum = 0;
3444 #if 0
3445 if (!no_precomp)
3447 struct stat stat_f;
3449 fstat (f, &stat_f);
3451 do {
3452 sprintf (pcftry, "%s%d", fname, pcfnum++);
3454 pcf = open (pcftry, O_RDONLY, 0666);
3455 if (pcf != -1)
3457 struct stat s;
3459 fstat (pcf, &s);
3460 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
3461 sizeof (s.st_ino))
3462 || stat_f.st_dev != s.st_dev)
3464 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
3465 /* Don't need it any more. */
3466 close (pcf);
3468 else
3470 /* Don't need it at all. */
3471 close (pcf);
3472 break;
3475 } while (pcf != -1 && !pcfbuf);
3477 #endif
3479 /* Actually process the file */
3480 if (cpp_push_buffer (pfile, NULL, 0) == NULL)
3481 return 0;
3482 if (finclude (pfile, f, fname, is_system_include (pfile, fname),
3483 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
3485 output_line_command (pfile, 0, enter_file);
3486 pfile->only_seen_white = 2;
3489 if (angle_brackets)
3490 pfile->system_include_depth--;
3492 return 0;
3495 /* Return nonzero if there is no need to include file NAME
3496 because it has already been included and it contains a conditional
3497 to make a repeated include do nothing. */
3499 static int
3500 redundant_include_p (pfile, name)
3501 cpp_reader *pfile;
3502 char *name;
3504 struct file_name_list *l = pfile->all_include_files;
3505 for (; l; l = l->next)
3506 if (! strcmp (name, l->fname)
3507 && l->control_macro
3508 && cpp_lookup (pfile, l->control_macro, -1, -1))
3509 return 1;
3510 return 0;
3513 /* Return nonzero if the given FILENAME is an absolute pathname which
3514 designates a file within one of the known "system" include file
3515 directories. We assume here that if the given FILENAME looks like
3516 it is the name of a file which resides either directly in a "system"
3517 include file directory, or within any subdirectory thereof, then the
3518 given file must be a "system" include file. This function tells us
3519 if we should suppress pedantic errors/warnings for the given FILENAME.
3521 The value is 2 if the file is a C-language system header file
3522 for which C++ should (on most systems) assume `extern "C"'. */
3524 static int
3525 is_system_include (pfile, filename)
3526 cpp_reader *pfile;
3527 register char *filename;
3529 struct file_name_list *searchptr;
3531 for (searchptr = CPP_OPTIONS (pfile)->first_system_include; searchptr;
3532 searchptr = searchptr->next)
3533 if (searchptr->fname) {
3534 register char *sys_dir = searchptr->fname;
3535 register unsigned length = strlen (sys_dir);
3537 if (! strncmp (sys_dir, filename, length) && filename[length] == '/')
3539 if (searchptr->c_system_include_path)
3540 return 2;
3541 else
3542 return 1;
3545 return 0;
3550 * Install a name in the assertion hash table.
3552 * If LEN is >= 0, it is the length of the name.
3553 * Otherwise, compute the length by scanning the entire name.
3555 * If HASH is >= 0, it is the precomputed hash code.
3556 * Otherwise, compute the hash code.
3559 static ASSERTION_HASHNODE *
3560 assertion_install (pfile, name, len, hash)
3561 cpp_reader *pfile;
3562 U_CHAR *name;
3563 int len;
3564 int hash;
3566 register ASSERTION_HASHNODE *hp;
3567 register int i, bucket;
3568 register U_CHAR *p, *q;
3570 i = sizeof (ASSERTION_HASHNODE) + len + 1;
3571 hp = (ASSERTION_HASHNODE *) xmalloc (i);
3572 bucket = hash;
3573 hp->bucket_hdr = &pfile->assertion_hashtab[bucket];
3574 hp->next = pfile->assertion_hashtab[bucket];
3575 pfile->assertion_hashtab[bucket] = hp;
3576 hp->prev = NULL;
3577 if (hp->next != NULL)
3578 hp->next->prev = hp;
3579 hp->length = len;
3580 hp->value = 0;
3581 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
3582 p = hp->name;
3583 q = name;
3584 for (i = 0; i < len; i++)
3585 *p++ = *q++;
3586 hp->name[len] = 0;
3587 return hp;
3590 * find the most recent hash node for name "name" (ending with first
3591 * non-identifier char) installed by install
3593 * If LEN is >= 0, it is the length of the name.
3594 * Otherwise, compute the length by scanning the entire name.
3596 * If HASH is >= 0, it is the precomputed hash code.
3597 * Otherwise, compute the hash code.
3600 static ASSERTION_HASHNODE *
3601 assertion_lookup (pfile, name, len, hash)
3602 cpp_reader *pfile;
3603 U_CHAR *name;
3604 int len;
3605 int hash;
3607 register ASSERTION_HASHNODE *bucket;
3609 bucket = pfile->assertion_hashtab[hash];
3610 while (bucket) {
3611 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
3612 return bucket;
3613 bucket = bucket->next;
3615 return NULL;
3618 static void
3619 delete_assertion (hp)
3620 ASSERTION_HASHNODE *hp;
3622 struct tokenlist_list *tail;
3623 if (hp->prev != NULL)
3624 hp->prev->next = hp->next;
3625 if (hp->next != NULL)
3626 hp->next->prev = hp->prev;
3628 for (tail = hp->value; tail; )
3630 struct tokenlist_list *next = tail->next;
3631 free_token_list (tail->tokens);
3632 free (tail);
3633 tail = next;
3636 /* Make sure that the bucket chain header that
3637 the deleted guy was on points to the right thing afterwards. */
3638 if (hp == *hp->bucket_hdr)
3639 *hp->bucket_hdr = hp->next;
3641 free (hp);
3644 /* Convert a character string literal into a nul-terminated string.
3645 The input string is [IN ... LIMIT).
3646 The result is placed in RESULT. RESULT can be the same as IN.
3647 The value returned in the end of the string written to RESULT,
3648 or NULL on error. */
3650 static U_CHAR *
3651 convert_string (pfile, result, in, limit, handle_escapes)
3652 cpp_reader *pfile;
3653 register U_CHAR *result, *in, *limit;
3654 int handle_escapes;
3656 U_CHAR c;
3657 c = *in++;
3658 if (c != '\"')
3659 return NULL;
3660 while (in < limit)
3662 U_CHAR c = *in++;
3663 switch (c)
3665 case '\0':
3666 return NULL;
3667 case '\"':
3668 limit = in;
3669 break;
3670 case '\\':
3671 if (handle_escapes)
3673 char *bpc = (char *) in;
3674 int i = (U_CHAR) cpp_parse_escape (pfile, &bpc);
3675 in = (U_CHAR *) bpc;
3676 if (i >= 0)
3677 *result++ = (U_CHAR)c;
3678 break;
3680 /* else fall through */
3681 default:
3682 *result++ = c;
3685 *result = 0;
3686 return result;
3690 * interpret #line command. Remembers previously seen fnames
3691 * in its very own hash table.
3693 #define FNAME_HASHSIZE 37
3695 static int
3696 do_line (pfile, keyword, unused1, unused2)
3697 cpp_reader *pfile;
3698 struct directive *keyword ATTRIBUTE_UNUSED;
3699 U_CHAR *unused1 ATTRIBUTE_UNUSED, *unused2 ATTRIBUTE_UNUSED;
3701 cpp_buffer *ip = CPP_BUFFER (pfile);
3702 int new_lineno;
3703 long old_written = CPP_WRITTEN (pfile);
3704 enum file_change_code file_change = same_file;
3705 enum cpp_token token;
3707 token = get_directive_token (pfile);
3709 if (token != CPP_NUMBER
3710 || !ISDIGIT(pfile->token_buffer[old_written]))
3712 cpp_error (pfile, "invalid format `#line' command");
3713 goto bad_line_directive;
3716 /* The Newline at the end of this line remains to be processed.
3717 To put the next line at the specified line number,
3718 we must store a line number now that is one less. */
3719 new_lineno = atoi ((char *)(pfile->token_buffer + old_written)) - 1;
3720 CPP_SET_WRITTEN (pfile, old_written);
3722 /* NEW_LINENO is one less than the actual line number here. */
3723 if (CPP_PEDANTIC (pfile) && new_lineno < 0)
3724 cpp_pedwarn (pfile, "line number out of range in `#line' command");
3726 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
3727 if (PEEKC() && !is_space[PEEKC()]) {
3728 cpp_error (pfile, "invalid format `#line' command");
3729 goto bad_line_directive;
3731 #endif
3733 token = get_directive_token (pfile);
3735 if (token == CPP_STRING) {
3736 U_CHAR *fname = pfile->token_buffer + old_written;
3737 U_CHAR *end_name;
3738 static HASHNODE *fname_table[FNAME_HASHSIZE];
3739 HASHNODE *hp, **hash_bucket;
3740 U_CHAR *p;
3741 long num_start;
3742 int fname_length;
3744 /* Turn the file name, which is a character string literal,
3745 into a null-terminated string. Do this in place. */
3746 end_name = convert_string (pfile, fname, fname, CPP_PWRITTEN (pfile), 1);
3747 if (end_name == NULL)
3749 cpp_error (pfile, "invalid format `#line' command");
3750 goto bad_line_directive;
3753 fname_length = end_name - fname;
3755 num_start = CPP_WRITTEN (pfile);
3756 token = get_directive_token (pfile);
3757 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
3758 p = pfile->token_buffer + num_start;
3759 if (CPP_PEDANTIC (pfile))
3760 cpp_pedwarn (pfile, "garbage at end of `#line' command");
3762 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
3764 cpp_error (pfile, "invalid format `#line' command");
3765 goto bad_line_directive;
3767 if (*p == '1')
3768 file_change = enter_file;
3769 else if (*p == '2')
3770 file_change = leave_file;
3771 else if (*p == '3')
3772 ip->system_header_p = 1;
3773 else /* if (*p == '4') */
3774 ip->system_header_p = 2;
3776 CPP_SET_WRITTEN (pfile, num_start);
3777 token = get_directive_token (pfile);
3778 p = pfile->token_buffer + num_start;
3779 if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
3780 ip->system_header_p = *p == '3' ? 1 : 2;
3781 token = get_directive_token (pfile);
3783 if (token != CPP_VSPACE) {
3784 cpp_error (pfile, "invalid format `#line' command");
3785 goto bad_line_directive;
3789 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
3790 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
3791 if (hp->length == fname_length
3792 && strncmp (hp->value.cpval, fname, fname_length) == 0) {
3793 ip->nominal_fname = hp->value.cpval;
3794 break;
3796 if (hp == 0) {
3797 /* Didn't find it; cons up a new one. */
3798 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
3799 hp->next = *hash_bucket;
3800 *hash_bucket = hp;
3802 hp->length = fname_length;
3803 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
3804 bcopy (fname, hp->value.cpval, fname_length);
3807 else if (token != CPP_VSPACE && token != CPP_EOF) {
3808 cpp_error (pfile, "invalid format `#line' command");
3809 goto bad_line_directive;
3812 ip->lineno = new_lineno;
3813 bad_line_directive:
3814 skip_rest_of_line (pfile);
3815 CPP_SET_WRITTEN (pfile, old_written);
3816 output_line_command (pfile, 0, file_change);
3817 return 0;
3821 * remove the definition of a symbol from the symbol table.
3822 * according to un*x /lib/cpp, it is not an error to undef
3823 * something that has no definitions, so it isn't one here either.
3826 static int
3827 do_undef (pfile, keyword, buf, limit)
3828 cpp_reader *pfile;
3829 struct directive *keyword;
3830 U_CHAR *buf, *limit;
3832 int sym_length;
3833 HASHNODE *hp;
3834 U_CHAR *orig_buf = buf;
3836 #if 0
3837 /* If this is a precompiler run (with -pcp) pass thru #undef commands. */
3838 if (pcp_outfile && keyword)
3839 pass_thru_directive (buf, limit, pfile, keyword);
3840 #endif
3842 SKIP_WHITE_SPACE (buf);
3843 sym_length = check_macro_name (pfile, buf, "macro");
3845 while ((hp = cpp_lookup (pfile, buf, sym_length, -1)) != NULL)
3847 /* If we are generating additional info for debugging (with -g) we
3848 need to pass through all effective #undef commands. */
3849 if (CPP_OPTIONS (pfile)->debug_output && keyword)
3850 pass_thru_directive (orig_buf, limit, pfile, keyword);
3851 if (hp->type != T_MACRO)
3852 cpp_warning (pfile, "undefining `%s'", hp->name);
3853 delete_macro (hp);
3856 if (CPP_PEDANTIC (pfile)) {
3857 buf += sym_length;
3858 SKIP_WHITE_SPACE (buf);
3859 if (buf != limit)
3860 cpp_pedwarn (pfile, "garbage after `#undef' directive");
3862 return 0;
3866 * Report an error detected by the program we are processing.
3867 * Use the text of the line in the error message.
3868 * (We use error because it prints the filename & line#.)
3871 static int
3872 do_error (pfile, keyword, buf, limit)
3873 cpp_reader *pfile;
3874 struct directive *keyword ATTRIBUTE_UNUSED;
3875 U_CHAR *buf, *limit;
3877 int length = limit - buf;
3878 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
3879 bcopy (buf, copy, length);
3880 copy[length] = 0;
3881 SKIP_WHITE_SPACE (copy);
3882 cpp_error (pfile, "#error %s", copy);
3883 return 0;
3887 * Report a warning detected by the program we are processing.
3888 * Use the text of the line in the warning message, then continue.
3889 * (We use error because it prints the filename & line#.)
3892 static int
3893 do_warning (pfile, keyword, buf, limit)
3894 cpp_reader *pfile;
3895 struct directive *keyword ATTRIBUTE_UNUSED;
3896 U_CHAR *buf, *limit;
3898 int length = limit - buf;
3899 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
3900 bcopy (buf, copy, length);
3901 copy[length] = 0;
3902 SKIP_WHITE_SPACE (copy);
3904 if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
3905 cpp_pedwarn (pfile, "ANSI C does not allow `#warning'");
3907 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
3908 if -pedantic-errors is given, #warning should cause an error. */
3909 cpp_pedwarn (pfile, "#warning %s", copy);
3910 return 0;
3913 /* Remember the name of the current file being read from so that we can
3914 avoid ever including it again. */
3916 static int
3917 do_once (pfile, keyword, unused1, unused2)
3918 cpp_reader *pfile;
3919 struct directive *keyword ATTRIBUTE_UNUSED;
3920 U_CHAR *unused1 ATTRIBUTE_UNUSED, *unused2 ATTRIBUTE_UNUSED;
3922 cpp_buffer *ip = NULL;
3923 struct file_name_list *new;
3925 for (ip = CPP_BUFFER (pfile); ; ip = CPP_PREV_BUFFER (ip))
3927 if (ip == CPP_NULL_BUFFER (pfile))
3928 return 0;
3929 if (ip->fname != NULL)
3930 break;
3934 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
3935 new->next = pfile->dont_repeat_files;
3936 pfile->dont_repeat_files = new;
3937 new->fname = savestring (ip->fname);
3938 new->control_macro = 0;
3939 new->got_name_map = 0;
3940 new->c_system_include_path = 0;
3942 return 0;
3945 /* Report program identification. */
3947 static int
3948 do_ident (pfile, keyword, buf, limit)
3949 cpp_reader *pfile;
3950 struct directive *keyword ATTRIBUTE_UNUSED;
3951 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
3953 /* long old_written = CPP_WRITTEN (pfile);*/
3955 /* Allow #ident in system headers, since that's not user's fault. */
3956 if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
3957 cpp_pedwarn (pfile, "ANSI C does not allow `#ident'");
3959 /* Leave rest of line to be read by later calls to cpp_get_token. */
3961 return 0;
3964 /* #pragma and its argument line have already been copied to the output file.
3965 Just check for some recognized pragmas that need validation here. */
3967 static int
3968 do_pragma (pfile, keyword, buf, limit)
3969 cpp_reader *pfile;
3970 struct directive *keyword ATTRIBUTE_UNUSED;
3971 U_CHAR *buf, *limit ATTRIBUTE_UNUSED;
3973 while (*buf == ' ' || *buf == '\t')
3974 buf++;
3975 if (!strncmp (buf, "once", 4)) {
3976 /* Allow #pragma once in system headers, since that's not the user's
3977 fault. */
3978 if (!CPP_BUFFER (pfile)->system_header_p)
3979 cpp_warning (pfile, "`#pragma once' is obsolete");
3980 do_once (pfile, NULL, NULL, NULL);
3983 if (!strncmp (buf, "implementation", 14)) {
3984 /* Be quiet about `#pragma implementation' for a file only if it hasn't
3985 been included yet. */
3986 struct file_name_list *ptr;
3987 U_CHAR *p = buf + 14, *fname, *inc_fname;
3988 int fname_len;
3989 SKIP_WHITE_SPACE (p);
3990 if (*p == '\n' || *p != '\"')
3991 return 0;
3993 fname = p + 1;
3994 p = (U_CHAR *) index (fname, '\"');
3995 fname_len = p != NULL ? p - fname : strlen (fname);
3997 for (ptr = pfile->all_include_files; ptr; ptr = ptr->next) {
3998 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
3999 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
4000 if (inc_fname && !strncmp (inc_fname, fname, fname_len))
4001 cpp_warning (pfile,
4002 "`#pragma implementation' for `%s' appears after file is included",
4003 fname);
4007 return 0;
4010 #if 0
4011 /* This was a fun hack, but #pragma seems to start to be useful.
4012 By failing to recognize it, we pass it through unchanged to cc1. */
4015 * the behavior of the #pragma directive is implementation defined.
4016 * this implementation defines it as follows.
4019 static int
4020 do_pragma ()
4022 close (0);
4023 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
4024 goto nope;
4025 close (1);
4026 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
4027 goto nope;
4028 execl ("/usr/games/hack", "#pragma", 0);
4029 execl ("/usr/games/rogue", "#pragma", 0);
4030 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
4031 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
4032 nope:
4033 fatal ("You are in a maze of twisty compiler features, all different");
4035 #endif
4037 #ifdef SCCS_DIRECTIVE
4038 /* Just ignore #sccs, on systems where we define it at all. */
4040 static int
4041 do_sccs (pfile, keyword, buf, limit)
4042 cpp_reader *pfile;
4043 struct directive *keyword ATTRIBUTE_UNUSED;
4044 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
4046 if (CPP_PEDANTIC (pfile))
4047 cpp_pedwarn (pfile, "ANSI C does not allow `#sccs'");
4048 return 0;
4050 #endif
4053 * handle #if command by
4054 * 1) inserting special `defined' keyword into the hash table
4055 * that gets turned into 0 or 1 by special_symbol (thus,
4056 * if the luser has a symbol called `defined' already, it won't
4057 * work inside the #if command)
4058 * 2) rescan the input into a temporary output buffer
4059 * 3) pass the output buffer to the yacc parser and collect a value
4060 * 4) clean up the mess left from steps 1 and 2.
4061 * 5) call conditional_skip to skip til the next #endif (etc.),
4062 * or not, depending on the value from step 3.
4065 static int
4066 do_if (pfile, keyword, buf, limit)
4067 cpp_reader *pfile;
4068 struct directive *keyword ATTRIBUTE_UNUSED;
4069 U_CHAR *buf, *limit;
4071 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4072 conditional_skip (pfile, value == 0, T_IF, NULL_PTR);
4073 return 0;
4077 * handle a #elif directive by not changing if_stack either.
4078 * see the comment above do_else.
4081 static int
4082 do_elif (pfile, keyword, buf, limit)
4083 cpp_reader *pfile;
4084 struct directive *keyword ATTRIBUTE_UNUSED;
4085 U_CHAR *buf, *limit;
4087 if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack) {
4088 cpp_error (pfile, "`#elif' not within a conditional");
4089 return 0;
4090 } else {
4091 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF) {
4092 cpp_error (pfile, "`#elif' after `#else'");
4093 #if 0
4094 fprintf (stderr, " (matches line %d", pfile->if_stack->lineno);
4095 #endif
4096 if (pfile->if_stack->fname != NULL && CPP_BUFFER (pfile)->fname != NULL
4097 && strcmp (pfile->if_stack->fname,
4098 CPP_BUFFER (pfile)->nominal_fname) != 0)
4099 fprintf (stderr, ", file %s", pfile->if_stack->fname);
4100 fprintf (stderr, ")\n");
4102 pfile->if_stack->type = T_ELIF;
4105 if (pfile->if_stack->if_succeeded)
4106 skip_if_group (pfile, 0);
4107 else {
4108 HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4109 if (value == 0)
4110 skip_if_group (pfile, 0);
4111 else {
4112 ++pfile->if_stack->if_succeeded; /* continue processing input */
4113 output_line_command (pfile, 1, same_file);
4116 return 0;
4120 * evaluate a #if expression in BUF, of length LENGTH,
4121 * then parse the result as a C expression and return the value as an int.
4124 static HOST_WIDE_INT
4125 eval_if_expression (pfile, buf, length)
4126 cpp_reader *pfile;
4127 U_CHAR *buf ATTRIBUTE_UNUSED;
4128 int length ATTRIBUTE_UNUSED;
4130 HASHNODE *save_defined;
4131 HOST_WIDE_INT value;
4132 long old_written = CPP_WRITTEN (pfile);
4134 save_defined = install ((U_CHAR *)"defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4135 pfile->pcp_inside_if = 1;
4137 value = cpp_parse_expr (pfile);
4138 pfile->pcp_inside_if = 0;
4139 delete_macro (save_defined); /* clean up special symbol */
4141 CPP_SET_WRITTEN (pfile, old_written); /* Pop */
4143 return value;
4147 * routine to handle ifdef/ifndef. Try to look up the symbol,
4148 * then do or don't skip to the #endif/#else/#elif depending
4149 * on what directive is actually being processed.
4152 static int
4153 do_xifdef (pfile, keyword, unused1, unused2)
4154 cpp_reader *pfile;
4155 struct directive *keyword;
4156 U_CHAR *unused1 ATTRIBUTE_UNUSED, *unused2 ATTRIBUTE_UNUSED;
4158 int skip;
4159 cpp_buffer *ip = CPP_BUFFER (pfile);
4160 U_CHAR *ident;
4161 int ident_length;
4162 enum cpp_token token;
4163 int start_of_file = 0;
4164 U_CHAR *control_macro = 0;
4165 int old_written = CPP_WRITTEN (pfile);
4167 /* Detect a #ifndef at start of file (not counting comments). */
4168 if (ip->fname != 0 && keyword->type == T_IFNDEF)
4169 start_of_file = pfile->only_seen_white == 2;
4171 pfile->no_macro_expand++;
4172 token = get_directive_token (pfile);
4173 pfile->no_macro_expand--;
4175 ident = pfile->token_buffer + old_written;
4176 ident_length = CPP_WRITTEN (pfile) - old_written;
4177 CPP_SET_WRITTEN (pfile, old_written); /* Pop */
4179 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4181 skip = (keyword->type == T_IFDEF);
4182 if (! CPP_TRADITIONAL (pfile))
4183 cpp_pedwarn (pfile, "`#%s' with no argument", keyword->name);
4185 else if (token == CPP_NAME)
4187 HASHNODE *hp = cpp_lookup (pfile, ident, ident_length, -1);
4188 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
4189 if (start_of_file && !skip)
4191 control_macro = (U_CHAR *) xmalloc (ident_length + 1);
4192 bcopy (ident, control_macro, ident_length + 1);
4195 else
4197 skip = (keyword->type == T_IFDEF);
4198 if (! CPP_TRADITIONAL (pfile))
4199 cpp_error (pfile, "`#%s' with invalid argument", keyword->name);
4202 if (!CPP_TRADITIONAL (pfile))
4203 { int c;
4204 cpp_skip_hspace (pfile);
4205 c = PEEKC ();
4206 if (c != EOF && c != '\n')
4207 cpp_pedwarn (pfile, "garbage at end of `#%s' argument", keyword->name);
4209 skip_rest_of_line (pfile);
4211 #if 0
4212 if (pcp_outfile) {
4213 /* Output a precondition for this macro. */
4214 if (hp && hp->value.defn->predefined)
4215 fprintf (pcp_outfile, "#define %s\n", hp->name);
4216 else {
4217 U_CHAR *cp = buf;
4218 fprintf (pcp_outfile, "#undef ");
4219 while (is_idchar[*cp]) /* Ick! */
4220 fputc (*cp++, pcp_outfile);
4221 putc ('\n', pcp_outfile);
4223 #endif
4225 conditional_skip (pfile, skip, T_IF, control_macro);
4226 return 0;
4229 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4230 If this is a #ifndef starting at the beginning of a file,
4231 CONTROL_MACRO is the macro name tested by the #ifndef.
4232 Otherwise, CONTROL_MACRO is 0. */
4234 static void
4235 conditional_skip (pfile, skip, type, control_macro)
4236 cpp_reader *pfile;
4237 int skip;
4238 enum node_type type;
4239 U_CHAR *control_macro;
4241 IF_STACK_FRAME *temp;
4243 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
4244 temp->fname = CPP_BUFFER (pfile)->nominal_fname;
4245 #if 0
4246 temp->lineno = CPP_BUFFER (pfile)->lineno;
4247 #endif
4248 temp->next = pfile->if_stack;
4249 temp->control_macro = control_macro;
4250 pfile->if_stack = temp;
4252 pfile->if_stack->type = type;
4254 if (skip != 0) {
4255 skip_if_group (pfile, 0);
4256 return;
4257 } else {
4258 ++pfile->if_stack->if_succeeded;
4259 output_line_command (pfile, 1, same_file);
4264 * skip to #endif, #else, or #elif. adjust line numbers, etc.
4265 * leaves input ptr at the sharp sign found.
4266 * If ANY is nonzero, return at next directive of any sort.
4269 static void
4270 skip_if_group (pfile, any)
4271 cpp_reader *pfile;
4272 int any;
4274 int c;
4275 struct directive *kt;
4276 IF_STACK_FRAME *save_if_stack = pfile->if_stack; /* don't pop past here */
4277 #if 0
4278 U_CHAR *beg_of_line = bp;
4279 #endif
4280 register int ident_length;
4281 U_CHAR *ident;
4282 struct parse_marker line_start_mark;
4284 parse_set_mark (&line_start_mark, pfile);
4286 if (CPP_OPTIONS (pfile)->output_conditionals) {
4287 static char failed[] = "#failed\n";
4288 CPP_PUTS (pfile, failed, sizeof(failed)-1);
4289 pfile->lineno++;
4290 output_line_command (pfile, 1, same_file);
4293 beg_of_line:
4294 if (CPP_OPTIONS (pfile)->output_conditionals)
4296 cpp_buffer *pbuf = CPP_BUFFER (pfile);
4297 U_CHAR *start_line = pbuf->buf + line_start_mark.position;
4298 CPP_PUTS (pfile, start_line, pbuf->cur - start_line);
4300 parse_move_mark (&line_start_mark, pfile);
4301 if (!CPP_TRADITIONAL (pfile))
4302 cpp_skip_hspace (pfile);
4303 c = GETC();
4304 if (c == '#')
4306 int old_written = CPP_WRITTEN (pfile);
4307 cpp_skip_hspace (pfile);
4309 parse_name (pfile, GETC());
4310 ident_length = CPP_WRITTEN (pfile) - old_written;
4311 ident = pfile->token_buffer + old_written;
4312 pfile->limit = ident;
4313 #if 0
4314 if (ident_length == 0)
4315 goto not_a_directive;
4317 /* Handle # followed by a line number. */
4319 /* Avoid error for `###' and similar cases unless -pedantic. */
4320 #endif
4322 for (kt = directive_table; kt->length >= 0; kt++)
4324 IF_STACK_FRAME *temp;
4325 if (ident_length == kt->length
4326 && strncmp (ident, kt->name, kt->length) == 0)
4328 /* If we are asked to return on next directive, do so now. */
4329 if (any)
4330 goto done;
4332 switch (kt->type)
4334 case T_IF:
4335 case T_IFDEF:
4336 case T_IFNDEF:
4337 temp
4338 = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
4339 temp->next = pfile->if_stack;
4340 pfile->if_stack = temp;
4341 #if 0
4342 temp->lineno = CPP_BUFFER(pfile)->lineno;
4343 #endif
4344 temp->fname = CPP_BUFFER(pfile)->nominal_fname;
4345 temp->type = kt->type;
4346 break;
4347 case T_ELSE:
4348 case T_ENDIF:
4349 if (CPP_PEDANTIC (pfile) && pfile->if_stack != save_if_stack)
4350 validate_else (pfile,
4351 kt->type == T_ELSE ? "#else" : "#endif");
4352 case T_ELIF:
4353 if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack)
4355 cpp_error (pfile,
4356 "`#%s' not within a conditional", kt->name);
4357 break;
4359 else if (pfile->if_stack == save_if_stack)
4360 goto done; /* found what we came for */
4362 if (kt->type != T_ENDIF)
4364 if (pfile->if_stack->type == T_ELSE)
4365 cpp_error (pfile, "`#else' or `#elif' after `#else'");
4366 pfile->if_stack->type = kt->type;
4367 break;
4370 temp = pfile->if_stack;
4371 pfile->if_stack = temp->next;
4372 free (temp);
4373 break;
4374 default: ;
4376 break;
4378 /* Don't let erroneous code go by. */
4379 if (kt->length < 0 && !CPP_OPTIONS (pfile)->lang_asm
4380 && CPP_PEDANTIC (pfile))
4381 cpp_pedwarn (pfile, "invalid preprocessor directive name");
4383 c = GETC ();
4385 /* We're in the middle of a line. Skip the rest of it. */
4386 for (;;) {
4387 switch (c)
4389 long old;
4390 case EOF:
4391 goto done;
4392 case '/': /* possible comment */
4393 c = skip_comment (pfile, NULL);
4394 if (c == EOF)
4395 goto done;
4396 break;
4397 case '\"':
4398 case '\'':
4399 FORWARD(-1);
4400 old = CPP_WRITTEN (pfile);
4401 cpp_get_token (pfile);
4402 CPP_SET_WRITTEN (pfile, old);
4403 break;
4404 case '\\':
4405 /* Char after backslash loses its special meaning. */
4406 if (PEEKC() == '\n')
4407 FORWARD (1);
4408 break;
4409 case '\n':
4410 goto beg_of_line;
4411 break;
4413 c = GETC ();
4415 done:
4416 if (CPP_OPTIONS (pfile)->output_conditionals) {
4417 static char end_failed[] = "#endfailed\n";
4418 CPP_PUTS (pfile, end_failed, sizeof(end_failed)-1);
4419 pfile->lineno++;
4421 pfile->only_seen_white = 1;
4422 parse_goto_mark (&line_start_mark, pfile);
4423 parse_clear_mark (&line_start_mark);
4427 * handle a #else directive. Do this by just continuing processing
4428 * without changing if_stack ; this is so that the error message
4429 * for missing #endif's etc. will point to the original #if. It
4430 * is possible that something different would be better.
4433 static int
4434 do_else (pfile, keyword, buf, limit)
4435 cpp_reader *pfile;
4436 struct directive *keyword ATTRIBUTE_UNUSED;
4437 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
4439 cpp_buffer *ip = CPP_BUFFER (pfile);
4441 if (CPP_PEDANTIC (pfile))
4442 validate_else (pfile, "#else");
4443 skip_rest_of_line (pfile);
4445 if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack) {
4446 cpp_error (pfile, "`#else' not within a conditional");
4447 return 0;
4448 } else {
4449 /* #ifndef can't have its special treatment for containing the whole file
4450 if it has a #else clause. */
4451 pfile->if_stack->control_macro = 0;
4453 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF) {
4454 cpp_error (pfile, "`#else' after `#else'");
4455 fprintf (stderr, " (matches line %d", pfile->if_stack->lineno);
4456 if (strcmp (pfile->if_stack->fname, ip->nominal_fname) != 0)
4457 fprintf (stderr, ", file %s", pfile->if_stack->fname);
4458 fprintf (stderr, ")\n");
4460 pfile->if_stack->type = T_ELSE;
4463 if (pfile->if_stack->if_succeeded)
4464 skip_if_group (pfile, 0);
4465 else {
4466 ++pfile->if_stack->if_succeeded; /* continue processing input */
4467 output_line_command (pfile, 1, same_file);
4469 return 0;
4473 * unstack after #endif command
4476 static int
4477 do_endif (pfile, keyword, buf, limit)
4478 cpp_reader *pfile;
4479 struct directive *keyword ATTRIBUTE_UNUSED;
4480 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
4482 if (CPP_PEDANTIC (pfile))
4483 validate_else (pfile, "#endif");
4484 skip_rest_of_line (pfile);
4486 if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack)
4487 cpp_error (pfile, "unbalanced `#endif'");
4488 else
4490 IF_STACK_FRAME *temp = pfile->if_stack;
4491 pfile->if_stack = temp->next;
4492 if (temp->control_macro != 0)
4494 /* This #endif matched a #ifndef at the start of the file.
4495 See if it is at the end of the file. */
4496 struct parse_marker start_mark;
4497 int c;
4499 parse_set_mark (&start_mark, pfile);
4501 for (;;)
4503 cpp_skip_hspace (pfile);
4504 c = GETC ();
4505 if (c != '\n')
4506 break;
4508 parse_goto_mark (&start_mark, pfile);
4509 parse_clear_mark (&start_mark);
4511 if (c == EOF)
4513 /* If we get here, this #endif ends a #ifndef
4514 that contains all of the file (aside from whitespace).
4515 Arrange not to include the file again
4516 if the macro that was tested is defined.
4518 Do not do this for the top-level file in a -include or any
4519 file in a -imacros. */
4520 #if 0
4521 FIXME!
4522 if (indepth != 0
4523 && ! (indepth == 1 && pfile->no_record_file)
4524 && ! (pfile->no_record_file && no_output))
4525 #endif
4527 struct file_name_list *ifile = pfile->all_include_files;
4529 for ( ; ifile != NULL; ifile = ifile->next)
4531 if (!strcmp (ifile->fname, CPP_BUFFER (pfile)->fname))
4533 ifile->control_macro = temp->control_macro;
4534 break;
4540 free (temp);
4541 output_line_command (pfile, 1, same_file);
4543 return 0;
4546 /* When an #else or #endif is found while skipping failed conditional,
4547 if -pedantic was specified, this is called to warn about text after
4548 the command name. P points to the first char after the command name. */
4550 static void
4551 validate_else (pfile, directive)
4552 cpp_reader *pfile;
4553 char *directive;
4555 int c;
4556 cpp_skip_hspace (pfile);
4557 c = PEEKC ();
4558 if (c != EOF && c != '\n')
4559 cpp_pedwarn (pfile,
4560 "text following `%s' violates ANSI standard", directive);
4563 /* Get the next token, and add it to the text in pfile->token_buffer.
4564 Return the kind of token we got. */
4566 enum cpp_token
4567 cpp_get_token (pfile)
4568 cpp_reader *pfile;
4570 register int c, c2, c3;
4571 long old_written;
4572 long start_line, start_column;
4573 enum cpp_token token;
4574 struct cpp_options *opts = CPP_OPTIONS (pfile);
4575 CPP_BUFFER (pfile)->prev = CPP_BUFFER (pfile)->cur;
4576 get_next:
4577 c = GETC();
4578 if (c == EOF)
4580 handle_eof:
4581 if (CPP_BUFFER (pfile)->seen_eof)
4583 if (cpp_pop_buffer (pfile) != CPP_NULL_BUFFER (pfile))
4584 goto get_next;
4585 else
4586 return CPP_EOF;
4588 else
4590 cpp_buffer *next_buf
4591 = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
4592 CPP_BUFFER (pfile)->seen_eof = 1;
4593 if (CPP_BUFFER (pfile)->nominal_fname
4594 && next_buf != CPP_NULL_BUFFER (pfile))
4596 /* We're about to return from an #include file.
4597 Emit #line information now (as part of the CPP_POP) result.
4598 But the #line refers to the file we will pop to. */
4599 cpp_buffer *cur_buffer = CPP_BUFFER (pfile);
4600 CPP_BUFFER (pfile) = next_buf;
4601 pfile->input_stack_listing_current = 0;
4602 output_line_command (pfile, 0, leave_file);
4603 CPP_BUFFER (pfile) = cur_buffer;
4605 return CPP_POP;
4608 else
4610 switch (c)
4612 long newlines;
4613 struct parse_marker start_mark;
4614 case '/':
4615 if (PEEKC () == '=')
4616 goto op2;
4617 if (opts->put_out_comments)
4618 parse_set_mark (&start_mark, pfile);
4619 newlines = 0;
4620 cpp_buf_line_and_col (cpp_file_buffer (pfile),
4621 &start_line, &start_column);
4622 c = skip_comment (pfile, &newlines);
4623 if (opts->put_out_comments && (c == '/' || c == EOF))
4624 parse_clear_mark (&start_mark);
4625 if (c == '/')
4626 goto randomchar;
4627 if (c == EOF)
4629 cpp_error_with_line (pfile, start_line, start_column,
4630 "unterminated comment");
4631 goto handle_eof;
4633 c = '/'; /* Initial letter of comment. */
4634 return_comment:
4635 /* Comments are equivalent to spaces.
4636 For -traditional, a comment is equivalent to nothing. */
4637 if (opts->put_out_comments)
4639 cpp_buffer *pbuf = CPP_BUFFER (pfile);
4640 U_CHAR *start = pbuf->buf + start_mark.position;
4641 int len = pbuf->cur - start;
4642 CPP_RESERVE(pfile, 1 + len);
4643 CPP_PUTC_Q (pfile, c);
4644 CPP_PUTS_Q (pfile, start, len);
4645 pfile->lineno += newlines;
4646 parse_clear_mark (&start_mark);
4647 return CPP_COMMENT;
4649 else if (CPP_TRADITIONAL (pfile))
4651 return CPP_COMMENT;
4653 else
4655 #if 0
4656 /* This may not work if cpp_get_token is called recursively,
4657 since many places look for horizontal space. */
4658 if (newlines)
4660 /* Copy the newlines into the output buffer, in order to
4661 avoid the pain of a #line every time a multiline comment
4662 is seen. */
4663 CPP_RESERVE(pfile, newlines);
4664 while (--newlines >= 0)
4666 CPP_PUTC_Q (pfile, '\n');
4667 pfile->lineno++;
4669 return CPP_VSPACE;
4671 #endif
4672 CPP_RESERVE(pfile, 1);
4673 CPP_PUTC_Q (pfile, ' ');
4674 return CPP_HSPACE;
4676 #if 0
4677 if (opts->for_lint) {
4678 U_CHAR *argbp;
4679 int cmdlen, arglen;
4680 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
4682 if (lintcmd != NULL) {
4683 /* I believe it is always safe to emit this newline: */
4684 obp[-1] = '\n';
4685 bcopy ("#pragma lint ", (char *) obp, 13);
4686 obp += 13;
4687 bcopy (lintcmd, (char *) obp, cmdlen);
4688 obp += cmdlen;
4690 if (arglen != 0) {
4691 *(obp++) = ' ';
4692 bcopy (argbp, (char *) obp, arglen);
4693 obp += arglen;
4696 /* OK, now bring us back to the state we were in before we entered
4697 this branch. We need #line because the newline for the pragma
4698 could mess things up. */
4699 output_line_command (pfile, 0, same_file);
4700 *(obp++) = ' '; /* just in case, if comments are copied thru */
4701 *(obp++) = '/';
4704 #endif
4706 case '#':
4707 #if 0
4708 /* If this is expanding a macro definition, don't recognize
4709 preprocessor directives. */
4710 if (ip->macro != 0)
4711 goto randomchar;
4712 /* If this is expand_into_temp_buffer, recognize them
4713 only after an actual newline at this level,
4714 not at the beginning of the input level. */
4715 if (ip->fname == 0 && beg_of_line == ip->buf)
4716 goto randomchar;
4717 if (ident_length)
4718 goto specialchar;
4719 #endif
4721 if (!pfile->only_seen_white)
4722 goto randomchar;
4723 if (handle_directive (pfile))
4724 return CPP_DIRECTIVE;
4725 pfile->only_seen_white = 0;
4726 return CPP_OTHER;
4728 case '\"':
4729 case '\'':
4730 /* A single quoted string is treated like a double -- some
4731 programs (e.g., troff) are perverse this way */
4732 cpp_buf_line_and_col (cpp_file_buffer (pfile),
4733 &start_line, &start_column);
4734 old_written = CPP_WRITTEN (pfile);
4735 string:
4736 CPP_PUTC (pfile, c);
4737 while (1)
4739 int cc = GETC();
4740 if (cc == EOF)
4742 if (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
4744 /* try harder: this string crosses a macro expansion
4745 boundary. This can happen naturally if -traditional.
4746 Otherwise, only -D can make a macro with an unmatched
4747 quote. */
4748 cpp_buffer *next_buf
4749 = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
4750 (*CPP_BUFFER (pfile)->cleanup)
4751 (CPP_BUFFER (pfile), pfile);
4752 CPP_BUFFER (pfile) = next_buf;
4753 continue;
4755 if (!CPP_TRADITIONAL (pfile))
4757 cpp_error_with_line (pfile, start_line, start_column,
4758 "unterminated string or character constant");
4759 if (pfile->multiline_string_line != start_line
4760 && pfile->multiline_string_line != 0)
4761 cpp_error_with_line (pfile,
4762 pfile->multiline_string_line, -1,
4763 "possible real start of unterminated constant");
4764 pfile->multiline_string_line = 0;
4766 break;
4768 CPP_PUTC (pfile, cc);
4769 switch (cc)
4771 case '\n':
4772 /* Traditionally, end of line ends a string constant with
4773 no error. So exit the loop and record the new line. */
4774 if (CPP_TRADITIONAL (pfile))
4775 goto while2end;
4776 if (c == '\'')
4778 cpp_error_with_line (pfile, start_line, start_column,
4779 "unterminated character constant");
4780 goto while2end;
4782 if (CPP_PEDANTIC (pfile)
4783 && pfile->multiline_string_line == 0)
4785 cpp_pedwarn_with_line (pfile, start_line, start_column,
4786 "string constant runs past end of line");
4788 if (pfile->multiline_string_line == 0)
4789 pfile->multiline_string_line = start_line;
4790 break;
4792 case '\\':
4793 cc = GETC();
4794 if (cc == '\n')
4796 /* Backslash newline is replaced by nothing at all. */
4797 CPP_ADJUST_WRITTEN (pfile, -1);
4798 pfile->lineno++;
4800 else
4802 /* ANSI stupidly requires that in \\ the second \
4803 is *not* prevented from combining with a newline. */
4804 NEWLINE_FIX1(cc);
4805 if (cc != EOF)
4806 CPP_PUTC (pfile, cc);
4808 break;
4810 case '\"':
4811 case '\'':
4812 if (cc == c)
4813 goto while2end;
4814 break;
4817 while2end:
4818 pfile->lineno += count_newlines (pfile->token_buffer + old_written,
4819 CPP_PWRITTEN (pfile));
4820 pfile->only_seen_white = 0;
4821 return c == '\'' ? CPP_CHAR : CPP_STRING;
4823 case '$':
4824 if (!opts->dollars_in_ident)
4825 goto randomchar;
4826 goto letter;
4828 case ':':
4829 if (opts->cplusplus && PEEKC () == ':')
4830 goto op2;
4831 goto randomchar;
4833 case '&':
4834 case '+':
4835 case '|':
4836 NEWLINE_FIX;
4837 c2 = PEEKC ();
4838 if (c2 == c || c2 == '=')
4839 goto op2;
4840 goto randomchar;
4842 case '*':
4843 case '!':
4844 case '%':
4845 case '=':
4846 case '^':
4847 NEWLINE_FIX;
4848 if (PEEKC () == '=')
4849 goto op2;
4850 goto randomchar;
4852 case '-':
4853 NEWLINE_FIX;
4854 c2 = PEEKC ();
4855 if (c2 == '-' && opts->chill)
4857 /* Chill style comment */
4858 if (opts->put_out_comments)
4859 parse_set_mark (&start_mark, pfile);
4860 FORWARD(1); /* Skip second '-'. */
4861 for (;;)
4863 c = GETC ();
4864 if (c == EOF)
4865 break;
4866 if (c == '\n')
4868 /* Don't consider final '\n' to be part of comment. */
4869 FORWARD(-1);
4870 break;
4873 c = '-';
4874 goto return_comment;
4876 if (c2 == '-' || c2 == '=' || c2 == '>')
4877 goto op2;
4878 goto randomchar;
4880 case '<':
4881 if (pfile->parsing_include_directive)
4883 for (;;)
4885 CPP_PUTC (pfile, c);
4886 if (c == '>')
4887 break;
4888 c = GETC ();
4889 NEWLINE_FIX1 (c);
4890 if (c == '\n' || c == EOF)
4892 cpp_error (pfile,
4893 "missing '>' in `#include <FILENAME>'");
4894 break;
4897 return CPP_STRING;
4899 /* else fall through */
4900 case '>':
4901 NEWLINE_FIX;
4902 c2 = PEEKC ();
4903 if (c2 == '=')
4904 goto op2;
4905 if (c2 != c)
4906 goto randomchar;
4907 FORWARD(1);
4908 CPP_RESERVE (pfile, 4);
4909 CPP_PUTC (pfile, c);
4910 CPP_PUTC (pfile, c2);
4911 NEWLINE_FIX;
4912 c3 = PEEKC ();
4913 if (c3 == '=')
4914 CPP_PUTC_Q (pfile, GETC ());
4915 CPP_NUL_TERMINATE_Q (pfile);
4916 pfile->only_seen_white = 0;
4917 return CPP_OTHER;
4919 case '@':
4920 if (CPP_BUFFER (pfile)->has_escapes)
4922 c = GETC ();
4923 if (c == '-')
4925 if (pfile->output_escapes)
4926 CPP_PUTS (pfile, "@-", 2);
4927 parse_name (pfile, GETC ());
4928 return CPP_NAME;
4930 else if (is_space [c])
4932 CPP_RESERVE (pfile, 2);
4933 if (pfile->output_escapes)
4934 CPP_PUTC_Q (pfile, '@');
4935 CPP_PUTC_Q (pfile, c);
4936 return CPP_HSPACE;
4939 if (pfile->output_escapes)
4941 CPP_PUTS (pfile, "@@", 2);
4942 return CPP_OTHER;
4944 goto randomchar;
4946 case '.':
4947 NEWLINE_FIX;
4948 c2 = PEEKC ();
4949 if (ISDIGIT(c2))
4951 CPP_RESERVE(pfile, 2);
4952 CPP_PUTC_Q (pfile, '.');
4953 c = GETC ();
4954 goto number;
4956 /* FIXME - misses the case "..\\\n." */
4957 if (c2 == '.' && PEEKN(1) == '.')
4959 CPP_RESERVE(pfile, 4);
4960 CPP_PUTC_Q (pfile, '.');
4961 CPP_PUTC_Q (pfile, '.');
4962 CPP_PUTC_Q (pfile, '.');
4963 FORWARD (2);
4964 CPP_NUL_TERMINATE_Q (pfile);
4965 pfile->only_seen_white = 0;
4966 return CPP_3DOTS;
4968 goto randomchar;
4970 op2:
4971 token = CPP_OTHER;
4972 pfile->only_seen_white = 0;
4973 op2any:
4974 CPP_RESERVE(pfile, 3);
4975 CPP_PUTC_Q (pfile, c);
4976 CPP_PUTC_Q (pfile, GETC ());
4977 CPP_NUL_TERMINATE_Q (pfile);
4978 return token;
4980 case 'L':
4981 NEWLINE_FIX;
4982 c2 = PEEKC ();
4983 if ((c2 == '\'' || c2 == '\"') && !CPP_TRADITIONAL (pfile))
4985 CPP_PUTC (pfile, c);
4986 c = GETC ();
4987 goto string;
4989 goto letter;
4991 case '0': case '1': case '2': case '3': case '4':
4992 case '5': case '6': case '7': case '8': case '9':
4993 number:
4994 c2 = '.';
4995 for (;;)
4997 CPP_RESERVE (pfile, 2);
4998 CPP_PUTC_Q (pfile, c);
4999 NEWLINE_FIX;
5000 c = PEEKC ();
5001 if (c == EOF)
5002 break;
5003 if (!is_idchar[c] && c != '.'
5004 && ((c2 != 'e' && c2 != 'E'
5005 && ((c2 != 'p' && c2 != 'P') || CPP_C89 (pfile)))
5006 || (c != '+' && c != '-')))
5007 break;
5008 FORWARD(1);
5009 c2= c;
5011 CPP_NUL_TERMINATE_Q (pfile);
5012 pfile->only_seen_white = 0;
5013 return CPP_NUMBER;
5014 case 'b': case 'c': case 'd': case 'h': case 'o':
5015 case 'B': case 'C': case 'D': case 'H': case 'O':
5016 if (opts->chill && PEEKC () == '\'')
5018 pfile->only_seen_white = 0;
5019 CPP_RESERVE (pfile, 2);
5020 CPP_PUTC_Q (pfile, c);
5021 CPP_PUTC_Q (pfile, '\'');
5022 FORWARD(1);
5023 for (;;)
5025 c = GETC();
5026 if (c == EOF)
5027 goto chill_number_eof;
5028 if (!is_idchar[c])
5030 if (c == '\\' && PEEKC() == '\n')
5032 FORWARD(2);
5033 continue;
5035 break;
5037 CPP_PUTC (pfile, c);
5039 if (c == '\'')
5041 CPP_RESERVE (pfile, 2);
5042 CPP_PUTC_Q (pfile, c);
5043 CPP_NUL_TERMINATE_Q (pfile);
5044 return CPP_STRING;
5046 else
5048 FORWARD(-1);
5049 chill_number_eof:
5050 CPP_NUL_TERMINATE (pfile);
5051 return CPP_NUMBER;
5054 else
5055 goto letter;
5056 case '_':
5057 case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
5058 case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
5059 case 'r': case 's': case 't': case 'u': case 'v': case 'w':
5060 case 'x': case 'y': case 'z':
5061 case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
5062 case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
5063 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
5064 case 'Y': case 'Z':
5065 letter:
5067 HASHNODE *hp;
5068 unsigned char *ident;
5069 int before_name_written = CPP_WRITTEN (pfile);
5070 int ident_len;
5071 parse_name (pfile, c);
5072 pfile->only_seen_white = 0;
5073 if (pfile->no_macro_expand)
5074 return CPP_NAME;
5075 ident = pfile->token_buffer + before_name_written;
5076 ident_len = CPP_PWRITTEN (pfile) - ident;
5077 hp = cpp_lookup (pfile, ident, ident_len, -1);
5078 if (!hp)
5079 return CPP_NAME;
5080 if (hp->type == T_DISABLED)
5082 if (pfile->output_escapes)
5083 { /* Return "@-IDENT", followed by '\0'. */
5084 int i;
5085 CPP_RESERVE (pfile, 3);
5086 ident = pfile->token_buffer + before_name_written;
5087 CPP_ADJUST_WRITTEN (pfile, 2);
5088 for (i = ident_len; i >= 0; i--) ident[i+2] = ident[i];
5089 ident[0] = '@';
5090 ident[1] = '-';
5092 return CPP_NAME;
5095 /* If macro wants an arglist, verify that a '(' follows.
5096 first skip all whitespace, copying it to the output
5097 after the macro name. Then, if there is no '(',
5098 decide this is not a macro call and leave things that way. */
5099 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5101 struct parse_marker macro_mark;
5102 int is_macro_call;
5103 while (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
5105 cpp_buffer *next_buf;
5106 cpp_skip_hspace (pfile);
5107 if (PEEKC () != EOF)
5108 break;
5109 next_buf = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
5110 (*CPP_BUFFER (pfile)->cleanup) (CPP_BUFFER (pfile), pfile);
5111 CPP_BUFFER (pfile) = next_buf;
5113 parse_set_mark (&macro_mark, pfile);
5114 for (;;)
5116 cpp_skip_hspace (pfile);
5117 c = PEEKC ();
5118 is_macro_call = c == '(';
5119 if (c != '\n')
5120 break;
5121 FORWARD (1);
5123 if (!is_macro_call)
5124 parse_goto_mark (&macro_mark, pfile);
5125 parse_clear_mark (&macro_mark);
5126 if (!is_macro_call)
5127 return CPP_NAME;
5129 /* This is now known to be a macro call. */
5131 /* it might not actually be a macro. */
5132 if (hp->type != T_MACRO) {
5133 int xbuf_len; U_CHAR *xbuf;
5134 CPP_SET_WRITTEN (pfile, before_name_written);
5135 special_symbol (hp, pfile);
5136 xbuf_len = CPP_WRITTEN (pfile) - before_name_written;
5137 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
5138 CPP_SET_WRITTEN (pfile, before_name_written);
5139 bcopy (CPP_PWRITTEN (pfile), xbuf, xbuf_len + 1);
5140 push_macro_expansion (pfile, xbuf, xbuf_len, hp);
5142 else
5144 /* Expand the macro, reading arguments as needed,
5145 and push the expansion on the input stack. */
5146 macroexpand (pfile, hp);
5147 CPP_SET_WRITTEN (pfile, before_name_written);
5150 /* An extra "@ " is added to the end of a macro expansion
5151 to prevent accidental token pasting. We prefer to avoid
5152 unneeded extra spaces (for the sake of cpp-using tools like
5153 imake). Here we remove the space if it is safe to do so. */
5154 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5155 && pfile->buffer->rlimit[-2] == '@'
5156 && pfile->buffer->rlimit[-1] == ' ')
5158 int c1 = pfile->buffer->rlimit[-3];
5159 int c2 = CPP_BUF_PEEK (CPP_PREV_BUFFER (CPP_BUFFER (pfile)));
5160 if (c2 == EOF || ! unsafe_chars (c1, c2))
5161 pfile->buffer->rlimit -= 2;
5164 goto get_next;
5166 case ' ': case '\t': case '\v': case '\r':
5167 for (;;)
5169 CPP_PUTC (pfile, c);
5170 c = PEEKC ();
5171 if (c == EOF || !is_hor_space[c])
5172 break;
5173 FORWARD(1);
5175 return CPP_HSPACE;
5177 case '\\':
5178 c2 = PEEKC ();
5179 if (c2 != '\n')
5180 goto randomchar;
5181 token = CPP_HSPACE;
5182 goto op2any;
5184 case '\n':
5185 CPP_PUTC (pfile, c);
5186 if (pfile->only_seen_white == 0)
5187 pfile->only_seen_white = 1;
5188 pfile->lineno++;
5189 output_line_command (pfile, 1, same_file);
5190 return CPP_VSPACE;
5192 case '(': token = CPP_LPAREN; goto char1;
5193 case ')': token = CPP_RPAREN; goto char1;
5194 case '{': token = CPP_LBRACE; goto char1;
5195 case '}': token = CPP_RBRACE; goto char1;
5196 case ',': token = CPP_COMMA; goto char1;
5197 case ';': token = CPP_SEMICOLON; goto char1;
5199 randomchar:
5200 default:
5201 token = CPP_OTHER;
5202 char1:
5203 pfile->only_seen_white = 0;
5204 CPP_PUTC (pfile, c);
5205 return token;
5210 /* Like cpp_get_token, but skip spaces and comments. */
5212 enum cpp_token
5213 cpp_get_non_space_token (pfile)
5214 cpp_reader *pfile;
5216 int old_written = CPP_WRITTEN (pfile);
5217 for (;;)
5219 enum cpp_token token = cpp_get_token (pfile);
5220 if (token != CPP_COMMENT && token != CPP_POP
5221 && token != CPP_HSPACE && token != CPP_VSPACE)
5222 return token;
5223 CPP_SET_WRITTEN (pfile, old_written);
5227 /* Parse an identifier starting with C. */
5229 static int
5230 parse_name (pfile, c)
5231 cpp_reader *pfile; int c;
5233 for (;;)
5235 if (! is_idchar[c])
5237 if (c == '\\' && PEEKC() == '\n')
5239 FORWARD(2);
5240 continue;
5242 FORWARD (-1);
5243 break;
5246 if (c == '$' && CPP_PEDANTIC (pfile))
5247 cpp_pedwarn (pfile, "`$' in identifier");
5249 CPP_RESERVE(pfile, 2); /* One more for final NUL. */
5250 CPP_PUTC_Q (pfile, c);
5251 c = GETC();
5252 if (c == EOF)
5253 break;
5255 CPP_NUL_TERMINATE_Q (pfile);
5256 return 1;
5260 /* Maintain and search list of included files, for #import. */
5262 /* Hash a file name for import_hash_table. */
5264 static int
5265 import_hash (f)
5266 char *f;
5268 int val = 0;
5270 while (*f) val += *f++;
5271 return (val%IMPORT_HASH_SIZE);
5274 /* Search for file FILENAME in import_hash_table.
5275 Return -2 if found, either a matching name or a matching inode.
5276 Otherwise, open the file and return a file descriptor if successful
5277 or -1 if unsuccessful. */
5279 static int
5280 lookup_import (pfile, filename, searchptr)
5281 cpp_reader *pfile;
5282 char *filename;
5283 struct file_name_list *searchptr;
5285 struct import_file *i;
5286 int h;
5287 int hashval;
5288 struct stat sb;
5289 int fd;
5291 hashval = import_hash (filename);
5293 /* Attempt to find file in list of already included files */
5294 i = pfile->import_hash_table[hashval];
5296 while (i) {
5297 if (!strcmp (filename, i->name))
5298 return -2; /* return found */
5299 i = i->next;
5301 /* Open it and try a match on inode/dev */
5302 fd = open_include_file (pfile, filename, searchptr);
5303 if (fd < 0)
5304 return fd;
5305 fstat (fd, &sb);
5306 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
5307 i = pfile->import_hash_table[h];
5308 while (i) {
5309 /* Compare the inode and the device.
5310 Supposedly on some systems the inode is not a scalar. */
5311 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
5312 && i->dev == sb.st_dev) {
5313 close (fd);
5314 return -2; /* return found */
5316 i = i->next;
5319 return fd; /* Not found, return open file */
5322 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
5324 static void
5325 add_import (pfile, fd, fname)
5326 cpp_reader *pfile;
5327 int fd;
5328 char *fname;
5330 struct import_file *i;
5331 int hashval;
5332 struct stat sb;
5334 hashval = import_hash (fname);
5335 fstat (fd, &sb);
5336 i = (struct import_file *)xmalloc (sizeof (struct import_file));
5337 i->name = (char *)xmalloc (strlen (fname)+1);
5338 strcpy (i->name, fname);
5339 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5340 i->dev = sb.st_dev;
5341 i->next = pfile->import_hash_table[hashval];
5342 pfile->import_hash_table[hashval] = i;
5345 /* The file_name_map structure holds a mapping of file names for a
5346 particular directory. This mapping is read from the file named
5347 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
5348 map filenames on a file system with severe filename restrictions,
5349 such as DOS. The format of the file name map file is just a series
5350 of lines with two tokens on each line. The first token is the name
5351 to map, and the second token is the actual name to use. */
5353 struct file_name_map
5355 struct file_name_map *map_next;
5356 char *map_from;
5357 char *map_to;
5360 #define FILE_NAME_MAP_FILE "header.gcc"
5362 /* Read a space delimited string of unlimited length from a stdio
5363 file. */
5365 static char *
5366 read_filename_string (ch, f)
5367 int ch;
5368 FILE *f;
5370 char *alloc, *set;
5371 int len;
5373 len = 20;
5374 set = alloc = xmalloc (len + 1);
5375 if (! is_space[ch])
5377 *set++ = ch;
5378 while ((ch = getc (f)) != EOF && ! is_space[ch])
5380 if (set - alloc == len)
5382 len *= 2;
5383 alloc = xrealloc (alloc, len + 1);
5384 set = alloc + len / 2;
5386 *set++ = ch;
5389 *set = '\0';
5390 ungetc (ch, f);
5391 return alloc;
5394 /* This structure holds a linked list of file name maps, one per directory. */
5396 struct file_name_map_list
5398 struct file_name_map_list *map_list_next;
5399 char *map_list_name;
5400 struct file_name_map *map_list_map;
5403 /* Read the file name map file for DIRNAME. */
5405 static struct file_name_map *
5406 read_name_map (pfile, dirname)
5407 cpp_reader *pfile;
5408 char *dirname;
5410 register struct file_name_map_list *map_list_ptr;
5411 char *name;
5412 FILE *f;
5414 for (map_list_ptr = CPP_OPTIONS (pfile)->map_list; map_list_ptr;
5415 map_list_ptr = map_list_ptr->map_list_next)
5416 if (! strcmp (map_list_ptr->map_list_name, dirname))
5417 return map_list_ptr->map_list_map;
5419 map_list_ptr = ((struct file_name_map_list *)
5420 xmalloc (sizeof (struct file_name_map_list)));
5421 map_list_ptr->map_list_name = savestring (dirname);
5422 map_list_ptr->map_list_map = NULL;
5424 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
5425 strcpy (name, dirname);
5426 if (*dirname)
5427 strcat (name, "/");
5428 strcat (name, FILE_NAME_MAP_FILE);
5429 f = fopen (name, "r");
5430 if (!f)
5431 map_list_ptr->map_list_map = NULL;
5432 else
5434 int ch;
5435 int dirlen = strlen (dirname);
5437 while ((ch = getc (f)) != EOF)
5439 char *from, *to;
5440 struct file_name_map *ptr;
5442 if (is_space[ch])
5443 continue;
5444 from = read_filename_string (ch, f);
5445 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5447 to = read_filename_string (ch, f);
5449 ptr = ((struct file_name_map *)
5450 xmalloc (sizeof (struct file_name_map)));
5451 ptr->map_from = from;
5453 /* Make the real filename absolute. */
5454 if (*to == '/')
5455 ptr->map_to = to;
5456 else
5458 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
5459 strcpy (ptr->map_to, dirname);
5460 ptr->map_to[dirlen] = '/';
5461 strcpy (ptr->map_to + dirlen + 1, to);
5462 free (to);
5465 ptr->map_next = map_list_ptr->map_list_map;
5466 map_list_ptr->map_list_map = ptr;
5468 while ((ch = getc (f)) != '\n')
5469 if (ch == EOF)
5470 break;
5472 fclose (f);
5475 map_list_ptr->map_list_next = CPP_OPTIONS (pfile)->map_list;
5476 CPP_OPTIONS (pfile)->map_list = map_list_ptr;
5478 return map_list_ptr->map_list_map;
5481 /* Try to open include file FILENAME. SEARCHPTR is the directory
5482 being tried from the include file search path. This function maps
5483 filenames on file systems based on information read by
5484 read_name_map. */
5486 static int
5487 open_include_file (pfile, filename, searchptr)
5488 cpp_reader *pfile;
5489 char *filename;
5490 struct file_name_list *searchptr;
5492 if (CPP_OPTIONS (pfile)->remap)
5494 register struct file_name_map *map;
5495 register char *from;
5496 char *p, *dir;
5498 if (searchptr && ! searchptr->got_name_map)
5500 searchptr->name_map = read_name_map (pfile,
5501 searchptr->fname
5502 ? searchptr->fname : ".");
5503 searchptr->got_name_map = 1;
5506 /* First check the mapping for the directory we are using. */
5507 if (searchptr && searchptr->name_map)
5509 from = filename;
5510 if (searchptr->fname)
5511 from += strlen (searchptr->fname) + 1;
5512 for (map = searchptr->name_map; map; map = map->map_next)
5514 if (! strcmp (map->map_from, from))
5516 /* Found a match. */
5517 return open (map->map_to, O_RDONLY, 0666);
5522 /* Try to find a mapping file for the particular directory we are
5523 looking in. Thus #include <sys/types.h> will look up sys/types.h
5524 in /usr/include/header.gcc and look up types.h in
5525 /usr/include/sys/header.gcc. */
5526 p = rindex (filename, '/');
5527 if (! p)
5528 p = filename;
5529 if (searchptr
5530 && searchptr->fname
5531 && strlen (searchptr->fname) == (size_t) (p - filename)
5532 && ! strncmp (searchptr->fname, filename, p - filename))
5534 /* FILENAME is in SEARCHPTR, which we've already checked. */
5535 return open (filename, O_RDONLY, 0666);
5538 if (p == filename)
5540 dir = ".";
5541 from = filename;
5543 else
5545 dir = (char *) alloca (p - filename + 1);
5546 bcopy (filename, dir, p - filename);
5547 dir[p - filename] = '\0';
5548 from = p + 1;
5550 for (map = read_name_map (pfile, dir); map; map = map->map_next)
5551 if (! strcmp (map->map_from, from))
5552 return open (map->map_to, O_RDONLY, 0666);
5555 return open (filename, O_RDONLY, 0666);
5558 /* Process the contents of include file FNAME, already open on descriptor F,
5559 with output to OP.
5560 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5561 "system" include directories (as decided by the `is_system_include'
5562 function above).
5563 DIRPTR is the link in the dir path through which this file was found,
5564 or 0 if the file name was absolute or via the current directory.
5565 Return 1 on success, 0 on failure.
5567 The caller is responsible for the cpp_push_buffer. */
5569 static int
5570 finclude (pfile, f, fname, system_header_p, dirptr)
5571 cpp_reader *pfile;
5572 int f;
5573 char *fname;
5574 int system_header_p;
5575 struct file_name_list *dirptr;
5577 struct stat st;
5578 size_t st_size;
5579 long i;
5580 int length;
5581 cpp_buffer *fp; /* For input stack frame */
5582 #if 0
5583 int missing_newline = 0;
5584 #endif
5586 if (fstat (f, &st) < 0)
5588 cpp_perror_with_name (pfile, fname);
5589 close (f);
5590 cpp_pop_buffer (pfile);
5591 return 0;
5594 fp = CPP_BUFFER (pfile);
5595 fp->nominal_fname = fp->fname = fname;
5596 #if 0
5597 fp->length = 0;
5598 #endif
5599 fp->dir = dirptr;
5600 fp->system_header_p = system_header_p;
5601 fp->lineno = 1;
5602 fp->colno = 1;
5603 fp->cleanup = file_cleanup;
5605 if (S_ISREG (st.st_mode)) {
5606 st_size = (size_t) st.st_size;
5607 if (st_size != st.st_size || st_size + 2 < st_size) {
5608 cpp_error (pfile, "file `%s' too large", fname);
5609 close (f);
5610 return 0;
5612 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
5613 fp->alimit = fp->buf + st_size + 2;
5614 fp->cur = fp->buf;
5616 /* Read the file contents, knowing that st_size is an upper bound
5617 on the number of bytes we can read. */
5618 length = safe_read (f, fp->buf, st_size);
5619 fp->rlimit = fp->buf + length;
5620 if (length < 0) goto nope;
5622 else if (S_ISDIR (st.st_mode)) {
5623 cpp_error (pfile, "directory `%s' specified in #include", fname);
5624 close (f);
5625 return 0;
5626 } else {
5627 /* Cannot count its file size before reading.
5628 First read the entire file into heap and
5629 copy them into buffer on stack. */
5631 int bsize = 2000;
5633 st_size = 0;
5634 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5636 for (;;) {
5637 i = safe_read (f, fp->buf + st_size, bsize - st_size);
5638 if (i < 0)
5639 goto nope; /* error! */
5640 st_size += i;
5641 if (st_size != bsize)
5642 break; /* End of file */
5643 bsize *= 2;
5644 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5646 fp->cur = fp->buf;
5647 length = st_size;
5650 if ((length > 0 && fp->buf[length - 1] != '\n')
5651 /* Backslash-newline at end is not good enough. */
5652 || (length > 1 && fp->buf[length - 2] == '\\')) {
5653 fp->buf[length++] = '\n';
5654 #if 0
5655 missing_newline = 1;
5656 #endif
5658 fp->buf[length] = '\0';
5659 fp->rlimit = fp->buf + length;
5661 /* Close descriptor now, so nesting does not use lots of descriptors. */
5662 close (f);
5664 /* Must do this before calling trigraph_pcp, so that the correct file name
5665 will be printed in warning messages. */
5667 pfile->input_stack_listing_current = 0;
5669 #if 0
5670 if (!no_trigraphs)
5671 trigraph_pcp (fp);
5672 #endif
5674 #if 0
5675 rescan (op, 0);
5677 if (missing_newline)
5678 fp->lineno--;
5680 if (CPP_PEDANTIC (pfile) && missing_newline)
5681 pedwarn ("file does not end in newline");
5683 indepth--;
5684 input_file_stack_tick++;
5685 free (fp->buf);
5686 #endif
5687 return 1;
5689 nope:
5691 cpp_perror_with_name (pfile, fname);
5692 close (f);
5693 free (fp->buf);
5694 return 1;
5697 /* This is called after options have been processed.
5698 * Check options for consistency, and setup for processing input
5699 * from the file named FNAME. (Use standard input if FNAME==NULL.)
5700 * Return 1 on success, 0 on failure.
5704 cpp_start_read (pfile, fname)
5705 cpp_reader *pfile;
5706 char *fname;
5708 struct cpp_options *opts = CPP_OPTIONS (pfile);
5709 struct cpp_pending *pend;
5710 char *p;
5711 int f;
5712 cpp_buffer *fp;
5714 /* The code looks at the defaults through this pointer, rather than through
5715 the constant structure above. This pointer gets changed if an environment
5716 variable specifies other defaults. */
5717 struct default_include *include_defaults = include_defaults_array;
5719 /* Add dirs from CPATH after dirs from -I. */
5720 /* There seems to be confusion about what CPATH should do,
5721 so for the moment it is not documented. */
5722 /* Some people say that CPATH should replace the standard include dirs,
5723 but that seems pointless: it comes before them, so it overrides them
5724 anyway. */
5725 GET_ENV_PATH_LIST (p, "CPATH");
5726 if (p != 0 && ! opts->no_standard_includes)
5727 path_include (pfile, p);
5729 /* Now that dollars_in_ident is known, initialize is_idchar. */
5730 initialize_char_syntax (opts);
5732 /* Do partial setup of input buffer for the sake of generating
5733 early #line directives (when -g is in effect). */
5734 fp = cpp_push_buffer (pfile, NULL, 0);
5735 if (!fp)
5736 return 0;
5737 if (opts->in_fname == NULL)
5738 opts->in_fname = "";
5739 fp->nominal_fname = fp->fname = opts->in_fname;
5740 fp->lineno = 0;
5742 /* Install __LINE__, etc. Must follow initialize_char_syntax
5743 and option processing. */
5744 initialize_builtins (pfile);
5746 /* Do standard #defines and assertions
5747 that identify system and machine type. */
5749 if (!opts->inhibit_predefs) {
5750 char *p = (char *) alloca (strlen (predefs) + 1);
5751 strcpy (p, predefs);
5752 while (*p) {
5753 char *q;
5754 while (*p == ' ' || *p == '\t')
5755 p++;
5756 /* Handle -D options. */
5757 if (p[0] == '-' && p[1] == 'D') {
5758 q = &p[2];
5759 while (*p && *p != ' ' && *p != '\t')
5760 p++;
5761 if (*p != 0)
5762 *p++= 0;
5763 if (opts->debug_output)
5764 output_line_command (pfile, 0, same_file);
5765 cpp_define (pfile, q);
5766 while (*p == ' ' || *p == '\t')
5767 p++;
5768 } else if (p[0] == '-' && p[1] == 'A') {
5769 /* Handle -A options (assertions). */
5770 char *assertion;
5771 char *past_name;
5772 char *value;
5773 char *past_value;
5774 char *termination;
5775 int save_char;
5777 assertion = &p[2];
5778 past_name = assertion;
5779 /* Locate end of name. */
5780 while (*past_name && *past_name != ' '
5781 && *past_name != '\t' && *past_name != '(')
5782 past_name++;
5783 /* Locate `(' at start of value. */
5784 value = past_name;
5785 while (*value && (*value == ' ' || *value == '\t'))
5786 value++;
5787 if (*value++ != '(')
5788 abort ();
5789 while (*value && (*value == ' ' || *value == '\t'))
5790 value++;
5791 past_value = value;
5792 /* Locate end of value. */
5793 while (*past_value && *past_value != ' '
5794 && *past_value != '\t' && *past_value != ')')
5795 past_value++;
5796 termination = past_value;
5797 while (*termination && (*termination == ' ' || *termination == '\t'))
5798 termination++;
5799 if (*termination++ != ')')
5800 abort ();
5801 if (*termination && *termination != ' ' && *termination != '\t')
5802 abort ();
5803 /* Temporarily null-terminate the value. */
5804 save_char = *termination;
5805 *termination = '\0';
5806 /* Install the assertion. */
5807 make_assertion (pfile, "-A", assertion);
5808 *termination = (char) save_char;
5809 p = termination;
5810 while (*p == ' ' || *p == '\t')
5811 p++;
5812 } else {
5813 abort ();
5818 /* Now handle the command line options. */
5820 /* Do -U's, -D's and -A's in the order they were seen. */
5821 /* First reverse the list. */
5822 opts->pending = nreverse_pending (opts->pending);
5824 for (pend = opts->pending; pend; pend = pend->next)
5826 if (pend->cmd != NULL && pend->cmd[0] == '-')
5828 switch (pend->cmd[1])
5830 case 'U':
5831 if (opts->debug_output)
5832 output_line_command (pfile, 0, same_file);
5833 do_undef (pfile, NULL, pend->arg, pend->arg + strlen (pend->arg));
5834 break;
5835 case 'D':
5836 if (opts->debug_output)
5837 output_line_command (pfile, 0, same_file);
5838 cpp_define (pfile, pend->arg);
5839 break;
5840 case 'A':
5841 make_assertion (pfile, "-A", pend->arg);
5842 break;
5847 opts->done_initializing = 1;
5849 { /* Read the appropriate environment variable and if it exists
5850 replace include_defaults with the listed path. */
5851 char *epath = 0;
5852 switch ((opts->objc << 1) + opts->cplusplus)
5854 case 0:
5855 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
5856 break;
5857 case 1:
5858 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
5859 break;
5860 case 2:
5861 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
5862 break;
5863 case 3:
5864 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
5865 break;
5867 /* If the environment var for this language is set,
5868 add to the default list of include directories. */
5869 if (epath) {
5870 char *nstore = (char *) alloca (strlen (epath) + 2);
5871 int num_dirs;
5872 char *startp, *endp;
5874 for (num_dirs = 1, startp = epath; *startp; startp++)
5875 if (*startp == PATH_SEPARATOR)
5876 num_dirs++;
5877 include_defaults
5878 = (struct default_include *) xmalloc ((num_dirs
5879 * sizeof (struct default_include))
5880 + sizeof (include_defaults_array));
5881 startp = endp = epath;
5882 num_dirs = 0;
5883 while (1) {
5884 /* Handle cases like c:/usr/lib:d:/gcc/lib */
5885 if ((*endp == PATH_SEPARATOR)
5886 || *endp == 0) {
5887 strncpy (nstore, startp, endp-startp);
5888 if (endp == startp)
5889 strcpy (nstore, ".");
5890 else
5891 nstore[endp-startp] = '\0';
5893 include_defaults[num_dirs].fname = savestring (nstore);
5894 include_defaults[num_dirs].component = 0;
5895 include_defaults[num_dirs].cplusplus = opts->cplusplus;
5896 include_defaults[num_dirs].cxx_aware = 1;
5897 num_dirs++;
5898 if (*endp == '\0')
5899 break;
5900 endp = startp = endp + 1;
5901 } else
5902 endp++;
5904 /* Put the usual defaults back in at the end. */
5905 bcopy ((char *) include_defaults_array,
5906 (char *) &include_defaults[num_dirs],
5907 sizeof (include_defaults_array));
5911 append_include_chain (pfile, opts->before_system, opts->last_before_system);
5912 opts->first_system_include = opts->before_system;
5914 /* Unless -fnostdinc,
5915 tack on the standard include file dirs to the specified list */
5916 if (!opts->no_standard_includes) {
5917 struct default_include *p = include_defaults;
5918 char *specd_prefix = opts->include_prefix;
5919 char *default_prefix = savestring (GCC_INCLUDE_DIR);
5920 int default_len = 0;
5921 /* Remove the `include' from /usr/local/lib/gcc.../include. */
5922 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
5923 default_len = strlen (default_prefix) - 7;
5924 default_prefix[default_len] = 0;
5926 /* Search "translated" versions of GNU directories.
5927 These have /usr/local/lib/gcc... replaced by specd_prefix. */
5928 if (specd_prefix != 0 && default_len != 0)
5929 for (p = include_defaults; p->fname; p++) {
5930 /* Some standard dirs are only for C++. */
5931 if (!p->cplusplus
5932 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
5933 /* Does this dir start with the prefix? */
5934 if (!strncmp (p->fname, default_prefix, default_len)) {
5935 /* Yes; change prefix and add to search list. */
5936 struct file_name_list *new
5937 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
5938 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
5939 char *str = (char *) xmalloc (this_len + 1);
5940 strcpy (str, specd_prefix);
5941 strcat (str, p->fname + default_len);
5942 new->fname = str;
5943 new->control_macro = 0;
5944 new->c_system_include_path = !p->cxx_aware;
5945 new->got_name_map = 0;
5946 append_include_chain (pfile, new, new);
5947 if (opts->first_system_include == 0)
5948 opts->first_system_include = new;
5952 /* Search ordinary names for GNU include directories. */
5953 for (p = include_defaults; p->fname; p++) {
5954 /* Some standard dirs are only for C++. */
5955 if (!p->cplusplus
5956 || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
5957 struct file_name_list *new
5958 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
5959 new->control_macro = 0;
5960 new->c_system_include_path = !p->cxx_aware;
5961 new->fname = update_path (p->fname, p->component);
5962 new->got_name_map = 0;
5963 append_include_chain (pfile, new, new);
5964 if (opts->first_system_include == 0)
5965 opts->first_system_include = new;
5970 /* Tack the after_include chain at the end of the include chain. */
5971 append_include_chain (pfile, opts->after_include, opts->last_after_include);
5972 if (opts->first_system_include == 0)
5973 opts->first_system_include = opts->after_include;
5975 /* With -v, print the list of dirs to search. */
5976 if (opts->verbose) {
5977 struct file_name_list *p;
5978 fprintf (stderr, "#include \"...\" search starts here:\n");
5979 for (p = opts->include; p; p = p->next) {
5980 if (p == opts->first_bracket_include)
5981 fprintf (stderr, "#include <...> search starts here:\n");
5982 fprintf (stderr, " %s\n", p->fname);
5984 fprintf (stderr, "End of search list.\n");
5987 /* Copy the entire contents of the main input file into
5988 the stacked input buffer previously allocated for it. */
5989 if (fname == NULL || *fname == 0) {
5990 fname = "";
5991 f = 0;
5992 } else if ((f = open (fname, O_RDONLY, 0666)) < 0)
5993 cpp_pfatal_with_name (pfile, fname);
5995 /* -MG doesn't select the form of output and must be specified with one of
5996 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
5997 inhibit compilation. */
5998 if (opts->print_deps_missing_files
5999 && (opts->print_deps == 0 || !opts->no_output))
6001 cpp_fatal (pfile, "-MG must be specified with one of -M or -MM");
6002 return 0;
6005 /* Either of two environment variables can specify output of deps.
6006 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
6007 where OUTPUT_FILE is the file to write deps info to
6008 and DEPS_TARGET is the target to mention in the deps. */
6010 if (opts->print_deps == 0
6011 && (getenv ("SUNPRO_DEPENDENCIES") != 0
6012 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
6013 char *spec = getenv ("DEPENDENCIES_OUTPUT");
6014 char *s;
6015 char *output_file;
6017 if (spec == 0)
6019 spec = getenv ("SUNPRO_DEPENDENCIES");
6020 opts->print_deps = 2;
6022 else
6023 opts->print_deps = 1;
6025 s = spec;
6026 /* Find the space before the DEPS_TARGET, if there is one. */
6027 /* This should use index. (mrs) */
6028 while (*s != 0 && *s != ' ') s++;
6029 if (*s != 0)
6031 opts->deps_target = s + 1;
6032 output_file = (char *) xmalloc (s - spec + 1);
6033 bcopy (spec, output_file, s - spec);
6034 output_file[s - spec] = 0;
6036 else
6038 opts->deps_target = 0;
6039 output_file = spec;
6042 opts->deps_file = output_file;
6043 opts->print_deps_append = 1;
6046 /* For -M, print the expected object file name
6047 as the target of this Make-rule. */
6048 if (opts->print_deps)
6050 pfile->deps_allocated_size = 200;
6051 pfile->deps_buffer = (char *) xmalloc (pfile->deps_allocated_size);
6052 pfile->deps_buffer[0] = 0;
6053 pfile->deps_size = 0;
6054 pfile->deps_column = 0;
6056 if (opts->deps_target)
6057 deps_output (pfile, opts->deps_target, ':');
6058 else if (*opts->in_fname == 0)
6059 deps_output (pfile, "-", ':');
6060 else
6062 char *p, *q, *r;
6063 int len, x;
6064 static char *known_suffixes[] = { ".c", ".C", ".s", ".S", ".m",
6065 ".cc", ".cxx", ".cpp", ".cp",
6066 ".c++", 0
6069 /* Discard all directory prefixes from filename. */
6070 if ((q = rindex (opts->in_fname, '/')) != NULL
6071 #ifdef DIR_SEPARATOR
6072 && (q = rindex (opts->in_fname, DIR_SEPARATOR)) != NULL
6073 #endif
6075 ++q;
6076 else
6077 q = opts->in_fname;
6079 /* Copy remainder to mungable area. */
6080 p = (char *) alloca (strlen(q) + 8);
6081 strcpy (p, q);
6083 /* Output P, but remove known suffixes. */
6084 len = strlen (p);
6085 q = p + len;
6086 /* Point to the filename suffix. */
6087 r = rindex (p, '.');
6088 /* Compare against the known suffixes. */
6089 x = 0;
6090 while (known_suffixes[x] != 0)
6092 if (strncmp (known_suffixes[x], r, q - r) == 0)
6094 /* Make q point to the bit we're going to overwrite
6095 with an object suffix. */
6096 q = r;
6097 break;
6099 x++;
6102 /* Supply our own suffix. */
6103 #ifndef VMS
6104 strcpy (q, ".o");
6105 #else
6106 strcpy (q, ".obj");
6107 #endif
6109 deps_output (pfile, p, ':');
6110 deps_output (pfile, opts->in_fname, ' ');
6114 #if 0
6115 /* Make sure data ends with a newline. And put a null after it. */
6117 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
6118 /* Backslash-newline at end is not good enough. */
6119 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
6120 fp->buf[fp->length++] = '\n';
6121 missing_newline = 1;
6123 fp->buf[fp->length] = '\0';
6125 /* Unless inhibited, convert trigraphs in the input. */
6127 if (!no_trigraphs)
6128 trigraph_pcp (fp);
6129 #endif
6131 /* Avoid a #line 0 if -include files are present. */
6132 CPP_BUFFER (pfile)->lineno = 1;
6133 output_line_command (pfile, 0, same_file);
6135 /* Scan the -include and -imacros files before the main input. */
6137 pfile->no_record_file++;
6138 for (pend = opts->pending; pend; pend = pend->next)
6140 if (pend->cmd != NULL)
6142 if (strcmp (pend->cmd, "-include") == 0)
6144 int fd = open (pend->arg, O_RDONLY, 0666);
6145 if (fd < 0)
6147 cpp_perror_with_name (pfile, pend->arg);
6148 return 0;
6150 if (!cpp_push_buffer (pfile, NULL, 0))
6151 return 0;
6152 if (finclude (pfile, fd, pend->arg, 0, NULL_PTR))
6154 output_line_command (pfile, 0, enter_file);
6155 cpp_scan_buffer (pfile);
6158 else if (strcmp (pend->cmd, "-imacros") == 0)
6160 int fd = open (pend->arg, O_RDONLY, 0666);
6161 if (fd < 0)
6163 cpp_perror_with_name (pfile, pend->arg);
6164 return 0;
6166 opts->no_output++;
6167 if (!cpp_push_buffer (pfile, NULL, 0))
6168 return 0;
6169 if (finclude (pfile, fd, pend->arg, 0, NULL_PTR))
6170 cpp_scan_buffer (pfile);
6171 opts->no_output--;
6175 pfile->no_record_file--;
6177 /* Free the pending list. */
6178 for (pend = opts->pending; pend; )
6180 struct cpp_pending *next = pend->next;
6181 free (pend);
6182 pend = next;
6184 opts->pending = NULL;
6186 #if 0
6187 /* Scan the input, processing macros and directives. */
6189 rescan (&outbuf, 0);
6191 if (missing_newline)
6192 fp->lineno--;
6194 if (CPP_PEDANTIC (pfile) && missing_newline)
6195 pedwarn ("file does not end in newline");
6197 #endif
6198 finclude (pfile, f, fname, 0, NULL_PTR);
6199 return 1;
6202 void
6203 cpp_reader_init (pfile)
6204 cpp_reader *pfile;
6206 bzero ((char *) pfile, sizeof (cpp_reader));
6207 pfile->get_token = cpp_get_token;
6209 pfile->token_buffer_size = 200;
6210 pfile->token_buffer = (U_CHAR *) xmalloc (pfile->token_buffer_size);
6211 CPP_SET_WRITTEN (pfile, 0);
6213 pfile->system_include_depth = 0;
6214 pfile->dont_repeat_files = 0;
6215 pfile->all_include_files = 0;
6216 pfile->max_include_len = 0;
6217 pfile->timebuf = NULL;
6218 pfile->only_seen_white = 1;
6219 pfile->buffer = CPP_NULL_BUFFER(pfile);
6222 static struct cpp_pending *
6223 nreverse_pending (list)
6224 struct cpp_pending *list;
6227 register struct cpp_pending *prev = 0, *next, *pend;
6228 for (pend = list; pend; pend = next)
6230 next = pend->next;
6231 pend->next = prev;
6232 prev = pend;
6234 return prev;
6237 static void
6238 push_pending (pfile, cmd, arg)
6239 cpp_reader *pfile;
6240 char *cmd;
6241 char *arg;
6243 struct cpp_pending *pend
6244 = (struct cpp_pending *) xmalloc (sizeof (struct cpp_pending));
6245 pend->cmd = cmd;
6246 pend->arg = arg;
6247 pend->next = CPP_OPTIONS (pfile)->pending;
6248 CPP_OPTIONS (pfile)->pending = pend;
6252 static void
6253 print_help ()
6255 printf ("Usage: %s [switches] input output\n", progname);
6256 printf ("Switches:\n");
6257 printf (" -include <file> Include the contents of <file> before other files\n");
6258 printf (" -imacros <file> Accept definition of marcos in <file>\n");
6259 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
6260 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
6261 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
6262 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
6263 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
6264 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
6265 printf (" -nostdinc Do not search the system include directories\n");
6266 printf (" -nostdinc++ Do not search the system include directories for C++\n");
6267 printf (" -o <file> Put output into <file>\n");
6268 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
6269 printf (" -traditional Follow K&R pre-processor behaviour\n");
6270 printf (" -trigraphs Support ANSI C trigraphs\n");
6271 printf (" -lang-c Assume that the input sources are in C\n");
6272 printf (" -lang-c89 Assume that the input sources are in C89\n");
6273 printf (" -lang-c++ Assume that the input sources are in C++\n");
6274 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
6275 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
6276 printf (" -lang-asm Assume that the input sources are in assembler\n");
6277 printf (" -lang-chill Assume that the input sources are in Chill\n");
6278 printf (" -+ Allow parsing of C++ style features\n");
6279 printf (" -w Inhibit warning messages\n");
6280 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
6281 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
6282 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
6283 printf (" -Wno-comment{s} Do not warn about comments\n");
6284 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
6285 printf (" a string if -tradtional is specified\n");
6286 printf (" -Wno-traditional Do not warn about stringification\n");
6287 printf (" -Wundef Warn if an undefined macro is used by #if\n");
6288 printf (" -Wno-undef Do not warn about testing udefined macros\n");
6289 printf (" -Wimport Warn about the use of the #import directive\n");
6290 printf (" -Wno-import Do not warn about the use of #import\n");
6291 printf (" -Werror Treat all warnings as errors\n");
6292 printf (" -Wno-error Do not treat warnings as errors\n");
6293 printf (" -Wall Enable all preprocessor warnings\n");
6294 printf (" -M Generate make dependencies\n");
6295 printf (" -MM As -M, but ignore system header files\n");
6296 printf (" -MD As -M, but put output in a .d file\n");
6297 printf (" -MMD As -MD, but ignore system header files\n");
6298 printf (" -MG Treat missing header file as generated files\n");
6299 printf (" -g Include #define and #undef directives in the output\n");
6300 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
6301 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
6302 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
6303 printf (" -U<macro> Undefine <macro> \n");
6304 printf (" -u or -undef Do not predefine any macros\n");
6305 printf (" -v Display the version number\n");
6306 printf (" -H Print the name of header files as they are used\n");
6307 printf (" -C Do not discard comments\n");
6308 printf (" -dM Display a list of macro definitions active at end\n");
6309 printf (" -dD Preserve macro definitions in output\n");
6310 printf (" -dN As -dD except that only the names are preserved\n");
6311 printf (" -dI Include #include directives in the output\n");
6312 printf (" -ifoutput Describe skipped code blocks in output \n");
6313 printf (" -P Do not generate #line directives\n");
6314 printf (" -$ Do not include '$' in identifiers\n");
6315 printf (" -remap Remap file names when including files.\n");
6316 printf (" -h or --help Display this information\n");
6320 /* Handle one command-line option in (argc, argv).
6321 Can be called multiple times, to handle multiple sets of options.
6322 Returns number of strings consumed. */
6324 cpp_handle_option (pfile, argc, argv)
6325 cpp_reader *pfile;
6326 int argc;
6327 char **argv;
6329 struct cpp_options *opts = CPP_OPTIONS (pfile);
6330 int i = 0;
6331 if (argv[i][0] != '-') {
6332 if (opts->out_fname != NULL)
6334 print_help ();
6335 cpp_fatal (pfile, "Too many arguments");
6337 else if (opts->in_fname != NULL)
6338 opts->out_fname = argv[i];
6339 else
6340 opts->in_fname = argv[i];
6341 } else {
6342 switch (argv[i][1]) {
6344 missing_filename:
6345 cpp_fatal (pfile, "Filename missing after `%s' option", argv[i]);
6346 return argc;
6347 missing_dirname:
6348 cpp_fatal (pfile, "Directory name missing after `%s' option", argv[i]);
6349 return argc;
6351 case 'i':
6352 if (!strcmp (argv[i], "-include")
6353 || !strcmp (argv[i], "-imacros")) {
6354 if (i + 1 == argc)
6355 goto missing_filename;
6356 else
6357 push_pending (pfile, argv[i], argv[i+1]), i++;
6359 if (!strcmp (argv[i], "-iprefix")) {
6360 if (i + 1 == argc)
6361 goto missing_filename;
6362 else
6363 opts->include_prefix = argv[++i];
6365 if (!strcmp (argv[i], "-ifoutput")) {
6366 opts->output_conditionals = 1;
6368 if (!strcmp (argv[i], "-isystem")) {
6369 struct file_name_list *dirtmp;
6371 if (i + 1 == argc)
6372 goto missing_filename;
6374 dirtmp = (struct file_name_list *)
6375 xmalloc (sizeof (struct file_name_list));
6376 dirtmp->next = 0;
6377 dirtmp->control_macro = 0;
6378 dirtmp->c_system_include_path = 1;
6379 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1]) + 1);
6380 strcpy (dirtmp->fname, argv[++i]);
6381 dirtmp->got_name_map = 0;
6383 if (opts->before_system == 0)
6384 opts->before_system = dirtmp;
6385 else
6386 opts->last_before_system->next = dirtmp;
6387 opts->last_before_system = dirtmp; /* Tail follows the last one */
6389 /* Add directory to end of path for includes,
6390 with the default prefix at the front of its name. */
6391 if (!strcmp (argv[i], "-iwithprefix")) {
6392 struct file_name_list *dirtmp;
6393 char *prefix;
6395 if (opts->include_prefix != 0)
6396 prefix = opts->include_prefix;
6397 else {
6398 prefix = savestring (GCC_INCLUDE_DIR);
6399 /* Remove the `include' from /usr/local/lib/gcc.../include. */
6400 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
6401 prefix[strlen (prefix) - 7] = 0;
6404 dirtmp = (struct file_name_list *)
6405 xmalloc (sizeof (struct file_name_list));
6406 dirtmp->next = 0; /* New one goes on the end */
6407 dirtmp->control_macro = 0;
6408 dirtmp->c_system_include_path = 0;
6409 if (i + 1 == argc)
6410 goto missing_dirname;
6412 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
6413 + strlen (prefix) + 1);
6414 strcpy (dirtmp->fname, prefix);
6415 strcat (dirtmp->fname, argv[++i]);
6416 dirtmp->got_name_map = 0;
6418 if (opts->after_include == 0)
6419 opts->after_include = dirtmp;
6420 else
6421 opts->last_after_include->next = dirtmp;
6422 opts->last_after_include = dirtmp; /* Tail follows the last one */
6424 /* Add directory to main path for includes,
6425 with the default prefix at the front of its name. */
6426 if (!strcmp (argv[i], "-iwithprefixbefore")) {
6427 struct file_name_list *dirtmp;
6428 char *prefix;
6430 if (opts->include_prefix != 0)
6431 prefix = opts->include_prefix;
6432 else {
6433 prefix = savestring (GCC_INCLUDE_DIR);
6434 /* Remove the `include' from /usr/local/lib/gcc.../include. */
6435 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
6436 prefix[strlen (prefix) - 7] = 0;
6439 dirtmp = (struct file_name_list *)
6440 xmalloc (sizeof (struct file_name_list));
6441 dirtmp->next = 0; /* New one goes on the end */
6442 dirtmp->control_macro = 0;
6443 dirtmp->c_system_include_path = 0;
6444 if (i + 1 == argc)
6445 goto missing_dirname;
6447 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
6448 + strlen (prefix) + 1);
6449 strcpy (dirtmp->fname, prefix);
6450 strcat (dirtmp->fname, argv[++i]);
6451 dirtmp->got_name_map = 0;
6453 append_include_chain (pfile, dirtmp, dirtmp);
6455 /* Add directory to end of path for includes. */
6456 if (!strcmp (argv[i], "-idirafter")) {
6457 struct file_name_list *dirtmp;
6459 dirtmp = (struct file_name_list *)
6460 xmalloc (sizeof (struct file_name_list));
6461 dirtmp->next = 0; /* New one goes on the end */
6462 dirtmp->control_macro = 0;
6463 dirtmp->c_system_include_path = 0;
6464 if (i + 1 == argc)
6465 goto missing_dirname;
6466 else
6467 dirtmp->fname = argv[++i];
6468 dirtmp->got_name_map = 0;
6470 if (opts->after_include == 0)
6471 opts->after_include = dirtmp;
6472 else
6473 opts->last_after_include->next = dirtmp;
6474 opts->last_after_include = dirtmp; /* Tail follows the last one */
6476 break;
6478 case 'o':
6479 if (opts->out_fname != NULL)
6481 cpp_fatal (pfile, "Output filename specified twice");
6482 return argc;
6484 if (i + 1 == argc)
6485 goto missing_filename;
6486 opts->out_fname = argv[++i];
6487 if (!strcmp (opts->out_fname, "-"))
6488 opts->out_fname = "";
6489 break;
6491 case 'p':
6492 if (!strcmp (argv[i], "-pedantic"))
6493 CPP_PEDANTIC (pfile) = 1;
6494 else if (!strcmp (argv[i], "-pedantic-errors")) {
6495 CPP_PEDANTIC (pfile) = 1;
6496 opts->pedantic_errors = 1;
6498 #if 0
6499 else if (!strcmp (argv[i], "-pcp")) {
6500 char *pcp_fname = argv[++i];
6501 pcp_outfile = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
6502 ? fopen (pcp_fname, "w")
6503 : fdopen (dup (fileno (stdout)), "w"));
6504 if (pcp_outfile == 0)
6505 cpp_pfatal_with_name (pfile, pcp_fname);
6506 no_precomp = 1;
6508 #endif
6509 break;
6511 case 't':
6512 if (!strcmp (argv[i], "-traditional")) {
6513 opts->traditional = 1;
6514 opts->cplusplus_comments = 0;
6515 } else if (!strcmp (argv[i], "-trigraphs")) {
6516 if (!opts->chill)
6517 opts->no_trigraphs = 0;
6519 break;
6521 case 'l':
6522 if (! strcmp (argv[i], "-lang-c"))
6523 opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
6524 opts->objc = 0;
6525 if (! strcmp (argv[i], "-lang-c89"))
6526 opts->cplusplus = 0, opts->cplusplus_comments = 0, opts->c89 = 1,
6527 opts->objc = 0;
6528 if (! strcmp (argv[i], "-lang-c++"))
6529 opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
6530 opts->objc = 0;
6531 if (! strcmp (argv[i], "-lang-objc"))
6532 opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
6533 opts->objc = 1;
6534 if (! strcmp (argv[i], "-lang-objc++"))
6535 opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
6536 opts->objc = 1;
6537 if (! strcmp (argv[i], "-lang-asm"))
6538 opts->lang_asm = 1;
6539 if (! strcmp (argv[i], "-lint"))
6540 opts->for_lint = 1;
6541 if (! strcmp (argv[i], "-lang-chill"))
6542 opts->objc = 0, opts->cplusplus = 0, opts->chill = 1,
6543 opts->traditional = 1, opts->no_trigraphs = 1;
6544 break;
6546 case '+':
6547 opts->cplusplus = 1, opts->cplusplus_comments = 1;
6548 break;
6550 case 'w':
6551 opts->inhibit_warnings = 1;
6552 break;
6554 case 'W':
6555 if (!strcmp (argv[i], "-Wtrigraphs"))
6556 opts->warn_trigraphs = 1;
6557 else if (!strcmp (argv[i], "-Wno-trigraphs"))
6558 opts->warn_trigraphs = 0;
6559 else if (!strcmp (argv[i], "-Wcomment"))
6560 opts->warn_comments = 1;
6561 else if (!strcmp (argv[i], "-Wno-comment"))
6562 opts->warn_comments = 0;
6563 else if (!strcmp (argv[i], "-Wcomments"))
6564 opts->warn_comments = 1;
6565 else if (!strcmp (argv[i], "-Wno-comments"))
6566 opts->warn_comments = 0;
6567 else if (!strcmp (argv[i], "-Wtraditional"))
6568 opts->warn_stringify = 1;
6569 else if (!strcmp (argv[i], "-Wno-traditional"))
6570 opts->warn_stringify = 0;
6571 else if (!strcmp (argv[i], "-Wundef"))
6572 opts->warn_undef = 1;
6573 else if (!strcmp (argv[i], "-Wno-undef"))
6574 opts->warn_undef = 0;
6575 else if (!strcmp (argv[i], "-Wimport"))
6576 opts->warn_import = 1;
6577 else if (!strcmp (argv[i], "-Wno-import"))
6578 opts->warn_import = 0;
6579 else if (!strcmp (argv[i], "-Werror"))
6580 opts->warnings_are_errors = 1;
6581 else if (!strcmp (argv[i], "-Wno-error"))
6582 opts->warnings_are_errors = 0;
6583 else if (!strcmp (argv[i], "-Wall"))
6585 opts->warn_trigraphs = 1;
6586 opts->warn_comments = 1;
6588 break;
6590 case 'M':
6591 /* The style of the choices here is a bit mixed.
6592 The chosen scheme is a hybrid of keeping all options in one string
6593 and specifying each option in a separate argument:
6594 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
6595 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
6596 -M[M][G][D file]. This is awkward to handle in specs, and is not
6597 as extensible. */
6598 /* ??? -MG must be specified in addition to one of -M or -MM.
6599 This can be relaxed in the future without breaking anything.
6600 The converse isn't true. */
6602 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
6603 if (!strcmp (argv[i], "-MG"))
6605 opts->print_deps_missing_files = 1;
6606 break;
6608 if (!strcmp (argv[i], "-M"))
6609 opts->print_deps = 2;
6610 else if (!strcmp (argv[i], "-MM"))
6611 opts->print_deps = 1;
6612 else if (!strcmp (argv[i], "-MD"))
6613 opts->print_deps = 2;
6614 else if (!strcmp (argv[i], "-MMD"))
6615 opts->print_deps = 1;
6616 /* For -MD and -MMD options, write deps on file named by next arg. */
6617 if (!strcmp (argv[i], "-MD") || !strcmp (argv[i], "-MMD"))
6619 if (i+1 == argc)
6620 goto missing_filename;
6621 opts->deps_file = argv[++i];
6623 else
6625 /* For -M and -MM, write deps on standard output
6626 and suppress the usual output. */
6627 opts->no_output = 1;
6629 break;
6631 case 'd':
6633 char *p = argv[i] + 2;
6634 char c;
6635 while ((c = *p++) != 0) {
6636 /* Arg to -d specifies what parts of macros to dump */
6637 switch (c) {
6638 case 'M':
6639 opts->dump_macros = dump_only;
6640 opts->no_output = 1;
6641 break;
6642 case 'N':
6643 opts->dump_macros = dump_names;
6644 break;
6645 case 'D':
6646 opts->dump_macros = dump_definitions;
6647 break;
6648 case 'I':
6649 opts->dump_includes = 1;
6650 break;
6654 break;
6656 case 'g':
6657 if (argv[i][2] == '3')
6658 opts->debug_output = 1;
6659 break;
6661 case '-':
6662 if (strcmp (argv[i], "--help") != 0)
6663 return i;
6664 print_help ();
6665 break;
6667 case 'v':
6668 fprintf (stderr, "GNU CPP version %s", version_string);
6669 #ifdef TARGET_VERSION
6670 TARGET_VERSION;
6671 #endif
6672 fprintf (stderr, "\n");
6673 opts->verbose = 1;
6674 break;
6676 case 'H':
6677 opts->print_include_names = 1;
6678 break;
6680 case 'D':
6681 if (argv[i][2] != 0)
6682 push_pending (pfile, "-D", argv[i] + 2);
6683 else if (i + 1 == argc)
6685 cpp_fatal (pfile, "Macro name missing after -D option");
6686 return argc;
6688 else
6689 i++, push_pending (pfile, "-D", argv[i]);
6690 break;
6692 case 'A':
6694 char *p;
6696 if (argv[i][2] != 0)
6697 p = argv[i] + 2;
6698 else if (i + 1 == argc)
6700 cpp_fatal (pfile, "Assertion missing after -A option");
6701 return argc;
6703 else
6704 p = argv[++i];
6706 if (!strcmp (p, "-")) {
6707 struct cpp_pending **ptr;
6708 /* -A- eliminates all predefined macros and assertions.
6709 Let's include also any that were specified earlier
6710 on the command line. That way we can get rid of any
6711 that were passed automatically in from GCC. */
6712 opts->inhibit_predefs = 1;
6713 for (ptr = &opts->pending; *ptr != NULL; )
6715 struct cpp_pending *pend = *ptr;
6716 if (pend->cmd && pend->cmd[0] == '-'
6717 && (pend->cmd[1] == 'D' || pend->cmd[1] == 'A'))
6719 *ptr = pend->next;
6720 free (pend);
6722 else
6723 ptr = &pend->next;
6725 } else {
6726 push_pending (pfile, "-A", p);
6729 break;
6731 case 'U': /* JF #undef something */
6732 if (argv[i][2] != 0)
6733 push_pending (pfile, "-U", argv[i] + 2);
6734 else if (i + 1 == argc)
6736 cpp_fatal (pfile, "Macro name missing after -U option");
6737 return argc;
6739 else
6740 push_pending (pfile, "-U", argv[i+1]), i++;
6741 break;
6743 case 'C':
6744 opts->put_out_comments = 1;
6745 break;
6747 case 'E': /* -E comes from cc -E; ignore it. */
6748 break;
6750 case 'P':
6751 opts->no_line_commands = 1;
6752 break;
6754 case '$': /* Don't include $ in identifiers. */
6755 opts->dollars_in_ident = 0;
6756 break;
6758 case 'I': /* Add directory to path for includes. */
6760 struct file_name_list *dirtmp;
6762 if (! CPP_OPTIONS(pfile)->ignore_srcdir
6763 && !strcmp (argv[i] + 2, "-")) {
6764 CPP_OPTIONS (pfile)->ignore_srcdir = 1;
6765 /* Don't use any preceding -I directories for #include <...>. */
6766 CPP_OPTIONS (pfile)->first_bracket_include = 0;
6768 else {
6769 dirtmp = (struct file_name_list *)
6770 xmalloc (sizeof (struct file_name_list));
6771 dirtmp->next = 0; /* New one goes on the end */
6772 dirtmp->control_macro = 0;
6773 dirtmp->c_system_include_path = 0;
6774 if (argv[i][2] != 0)
6775 dirtmp->fname = argv[i] + 2;
6776 else if (i + 1 == argc)
6777 goto missing_dirname;
6778 else
6779 dirtmp->fname = argv[++i];
6780 dirtmp->got_name_map = 0;
6781 append_include_chain (pfile, dirtmp, dirtmp);
6784 break;
6786 case 'n':
6787 if (!strcmp (argv[i], "-nostdinc"))
6788 /* -nostdinc causes no default include directories.
6789 You must specify all include-file directories with -I. */
6790 opts->no_standard_includes = 1;
6791 else if (!strcmp (argv[i], "-nostdinc++"))
6792 /* -nostdinc++ causes no default C++-specific include directories. */
6793 opts->no_standard_cplusplus_includes = 1;
6794 #if 0
6795 else if (!strcmp (argv[i], "-noprecomp"))
6796 no_precomp = 1;
6797 #endif
6798 break;
6800 case 'r':
6801 if (!strcmp (argv[i], "-remap"))
6802 opts->remap = 1;
6803 break;
6805 case 'u':
6806 /* Sun compiler passes undocumented switch "-undef".
6807 Let's assume it means to inhibit the predefined symbols. */
6808 opts->inhibit_predefs = 1;
6809 break;
6811 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
6812 if (opts->in_fname == NULL) {
6813 opts->in_fname = "";
6814 break;
6815 } else if (opts->out_fname == NULL) {
6816 opts->out_fname = "";
6817 break;
6818 } /* else fall through into error */
6820 default:
6821 return i;
6825 return i + 1;
6828 /* Handle command-line options in (argc, argv).
6829 Can be called multiple times, to handle multiple sets of options.
6830 Returns if an unrecognized option is seen.
6831 Returns number of strings consumed. */
6834 cpp_handle_options (pfile, argc, argv)
6835 cpp_reader *pfile;
6836 int argc;
6837 char **argv;
6839 int i;
6840 int strings_processed;
6841 for (i = 0; i < argc; i += strings_processed)
6843 strings_processed = cpp_handle_option (pfile, argc - i, argv + i);
6844 if (strings_processed == 0)
6845 break;
6847 return i;
6850 void
6851 cpp_finish (pfile)
6852 cpp_reader *pfile;
6854 struct cpp_options *opts = CPP_OPTIONS (pfile);
6856 if (opts->print_deps)
6858 /* Stream on which to print the dependency information. */
6859 FILE *deps_stream;
6861 /* Don't actually write the deps file if compilation has failed. */
6862 if (pfile->errors == 0)
6864 char *deps_mode = opts->print_deps_append ? "a" : "w";
6865 if (opts->deps_file == 0)
6866 deps_stream = stdout;
6867 else if ((deps_stream = fopen (opts->deps_file, deps_mode)) == 0)
6868 cpp_pfatal_with_name (pfile, opts->deps_file);
6869 fputs (pfile->deps_buffer, deps_stream);
6870 putc ('\n', deps_stream);
6871 if (opts->deps_file)
6873 if (ferror (deps_stream) || fclose (deps_stream) != 0)
6874 cpp_fatal (pfile, "I/O error on output");
6880 /* Free resources used by PFILE.
6881 This is the cpp_reader 'finalizer' or 'destructor' (in C++ terminology). */
6883 void
6884 cpp_cleanup (pfile)
6885 cpp_reader *pfile;
6887 int i;
6888 while ( CPP_BUFFER (pfile) != CPP_NULL_BUFFER (pfile))
6889 cpp_pop_buffer (pfile);
6891 if (pfile->token_buffer)
6893 free (pfile->token_buffer);
6894 pfile->token_buffer = NULL;
6897 if (pfile->deps_buffer)
6899 free (pfile->deps_buffer);
6900 pfile->deps_buffer = NULL;
6901 pfile->deps_allocated_size = 0;
6904 while (pfile->if_stack)
6906 IF_STACK_FRAME *temp = pfile->if_stack;
6907 pfile->if_stack = temp->next;
6908 free (temp);
6911 while (pfile->dont_repeat_files)
6913 struct file_name_list *temp = pfile->dont_repeat_files;
6914 pfile->dont_repeat_files = temp->next;
6915 free (temp->fname);
6916 free (temp);
6919 while (pfile->all_include_files)
6921 struct file_name_list *temp = pfile->all_include_files;
6922 pfile->all_include_files = temp->next;
6923 free (temp->fname);
6924 free (temp);
6927 for (i = IMPORT_HASH_SIZE; --i >= 0; )
6929 register struct import_file *imp = pfile->import_hash_table[i];
6930 while (imp)
6932 struct import_file *next = imp->next;
6933 free (imp->name);
6934 free (imp);
6935 imp = next;
6937 pfile->import_hash_table[i] = 0;
6940 for (i = ASSERTION_HASHSIZE; --i >= 0; )
6942 while (pfile->assertion_hashtab[i])
6943 delete_assertion (pfile->assertion_hashtab[i]);
6946 cpp_hash_cleanup (pfile);
6949 static int
6950 do_assert (pfile, keyword, buf, limit)
6951 cpp_reader *pfile;
6952 struct directive *keyword ATTRIBUTE_UNUSED;
6953 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
6955 long symstart; /* remember where symbol name starts */
6956 int c;
6957 int sym_length; /* and how long it is */
6958 struct arglist *tokens = NULL;
6960 if (CPP_PEDANTIC (pfile) && CPP_OPTIONS (pfile)->done_initializing
6961 && !CPP_BUFFER (pfile)->system_header_p)
6962 cpp_pedwarn (pfile, "ANSI C does not allow `#assert'");
6964 cpp_skip_hspace (pfile);
6965 symstart = CPP_WRITTEN (pfile); /* remember where it starts */
6966 parse_name (pfile, GETC());
6967 sym_length = check_macro_name (pfile, pfile->token_buffer + symstart,
6968 "assertion");
6970 cpp_skip_hspace (pfile);
6971 if (PEEKC() != '(') {
6972 cpp_error (pfile, "missing token-sequence in `#assert'");
6973 goto error;
6977 int error_flag = 0;
6978 tokens = read_token_list (pfile, &error_flag);
6979 if (error_flag)
6980 goto error;
6981 if (tokens == 0) {
6982 cpp_error (pfile, "empty token-sequence in `#assert'");
6983 goto error;
6985 cpp_skip_hspace (pfile);
6986 c = PEEKC ();
6987 if (c != EOF && c != '\n')
6988 cpp_pedwarn (pfile, "junk at end of `#assert'");
6989 skip_rest_of_line (pfile);
6992 /* If this name isn't already an assertion name, make it one.
6993 Error if it was already in use in some other way. */
6996 ASSERTION_HASHNODE *hp;
6997 U_CHAR *symname = pfile->token_buffer + symstart;
6998 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6999 struct tokenlist_list *value
7000 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
7002 hp = assertion_lookup (pfile, symname, sym_length, hashcode);
7003 if (hp == NULL) {
7004 if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
7005 cpp_error (pfile, "`defined' redefined as assertion");
7006 hp = assertion_install (pfile, symname, sym_length, hashcode);
7009 /* Add the spec'd token-sequence to the list of such. */
7010 value->tokens = tokens;
7011 value->next = hp->value;
7012 hp->value = value;
7014 CPP_SET_WRITTEN (pfile, symstart); /* Pop */
7015 return 0;
7016 error:
7017 CPP_SET_WRITTEN (pfile, symstart); /* Pop */
7018 skip_rest_of_line (pfile);
7019 return 1;
7022 static int
7023 do_unassert (pfile, keyword, buf, limit)
7024 cpp_reader *pfile;
7025 struct directive *keyword ATTRIBUTE_UNUSED;
7026 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7028 long symstart; /* remember where symbol name starts */
7029 int sym_length; /* and how long it is */
7030 int c;
7032 struct arglist *tokens = NULL;
7033 int tokens_specified = 0;
7035 if (CPP_PEDANTIC (pfile) && CPP_OPTIONS (pfile)->done_initializing
7036 && !CPP_BUFFER (pfile)->system_header_p)
7037 cpp_pedwarn (pfile, "ANSI C does not allow `#unassert'");
7039 cpp_skip_hspace (pfile);
7041 symstart = CPP_WRITTEN (pfile); /* remember where it starts */
7042 parse_name (pfile, GETC());
7043 sym_length = check_macro_name (pfile, pfile->token_buffer + symstart,
7044 "assertion");
7046 cpp_skip_hspace (pfile);
7047 if (PEEKC() == '(') {
7048 int error_flag = 0;
7050 tokens = read_token_list (pfile, &error_flag);
7051 if (error_flag)
7052 goto error;
7053 if (tokens == 0) {
7054 cpp_error (pfile, "empty token list in `#unassert'");
7055 goto error;
7058 tokens_specified = 1;
7061 cpp_skip_hspace (pfile);
7062 c = PEEKC ();
7063 if (c != EOF && c != '\n')
7064 cpp_error (pfile, "junk at end of `#unassert'");
7065 skip_rest_of_line (pfile);
7068 ASSERTION_HASHNODE *hp;
7069 U_CHAR *symname = pfile->token_buffer + symstart;
7070 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
7071 struct tokenlist_list *tail, *prev;
7073 hp = assertion_lookup (pfile, symname, sym_length, hashcode);
7074 if (hp == NULL)
7075 return 1;
7077 /* If no token list was specified, then eliminate this assertion
7078 entirely. */
7079 if (! tokens_specified)
7080 delete_assertion (hp);
7081 else {
7082 /* If a list of tokens was given, then delete any matching list. */
7084 tail = hp->value;
7085 prev = 0;
7086 while (tail) {
7087 struct tokenlist_list *next = tail->next;
7088 if (compare_token_lists (tail->tokens, tokens)) {
7089 if (prev)
7090 prev->next = next;
7091 else
7092 hp->value = tail->next;
7093 free_token_list (tail->tokens);
7094 free (tail);
7095 } else {
7096 prev = tail;
7098 tail = next;
7103 CPP_SET_WRITTEN (pfile, symstart); /* Pop */
7104 return 0;
7105 error:
7106 CPP_SET_WRITTEN (pfile, symstart); /* Pop */
7107 skip_rest_of_line (pfile);
7108 return 1;
7111 /* Test whether there is an assertion named NAME
7112 and optionally whether it has an asserted token list TOKENS.
7113 NAME is not null terminated; its length is SYM_LENGTH.
7114 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
7117 check_assertion (pfile, name, sym_length, tokens_specified, tokens)
7118 cpp_reader *pfile;
7119 U_CHAR *name;
7120 int sym_length;
7121 int tokens_specified;
7122 struct arglist *tokens;
7124 ASSERTION_HASHNODE *hp;
7125 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
7127 if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
7128 cpp_pedwarn (pfile, "ANSI C does not allow testing assertions");
7130 hp = assertion_lookup (pfile, name, sym_length, hashcode);
7131 if (hp == NULL)
7132 /* It is not an assertion; just return false. */
7133 return 0;
7135 /* If no token list was specified, then value is 1. */
7136 if (! tokens_specified)
7137 return 1;
7140 struct tokenlist_list *tail;
7142 tail = hp->value;
7144 /* If a list of tokens was given,
7145 then succeed if the assertion records a matching list. */
7147 while (tail) {
7148 if (compare_token_lists (tail->tokens, tokens))
7149 return 1;
7150 tail = tail->next;
7153 /* Fail if the assertion has no matching list. */
7154 return 0;
7158 /* Compare two lists of tokens for equality including order of tokens. */
7160 static int
7161 compare_token_lists (l1, l2)
7162 struct arglist *l1, *l2;
7164 while (l1 && l2) {
7165 if (l1->length != l2->length)
7166 return 0;
7167 if (strncmp (l1->name, l2->name, l1->length))
7168 return 0;
7169 l1 = l1->next;
7170 l2 = l2->next;
7173 /* Succeed if both lists end at the same time. */
7174 return l1 == l2;
7177 struct arglist *
7178 reverse_token_list (tokens)
7179 struct arglist *tokens;
7181 register struct arglist *prev = 0, *this, *next;
7182 for (this = tokens; this; this = next)
7184 next = this->next;
7185 this->next = prev;
7186 prev = this;
7188 return prev;
7191 /* Read a space-separated list of tokens ending in a close parenthesis.
7192 Return a list of strings, in the order they were written.
7193 (In case of error, return 0 and store -1 in *ERROR_FLAG.) */
7195 static struct arglist *
7196 read_token_list (pfile, error_flag)
7197 cpp_reader *pfile;
7198 int *error_flag;
7200 struct arglist *token_ptrs = 0;
7201 int depth = 1;
7202 int length;
7204 *error_flag = 0;
7205 FORWARD (1); /* Skip '(' */
7207 /* Loop over the assertion value tokens. */
7208 while (depth > 0)
7210 struct arglist *temp;
7211 long name_written = CPP_WRITTEN (pfile);
7212 int c;
7214 cpp_skip_hspace (pfile);
7216 c = GETC ();
7218 /* Find the end of the token. */
7219 if (c == '(')
7221 CPP_PUTC (pfile, c);
7222 depth++;
7224 else if (c == ')')
7226 depth--;
7227 if (depth == 0)
7228 break;
7229 CPP_PUTC (pfile, c);
7231 else if (c == '"' || c == '\'')
7233 FORWARD(-1);
7234 cpp_get_token (pfile);
7236 else if (c == '\n')
7237 break;
7238 else
7240 while (c != EOF && ! is_space[c] && c != '(' && c != ')'
7241 && c != '"' && c != '\'')
7243 CPP_PUTC (pfile, c);
7244 c = GETC();
7246 if (c != EOF) FORWARD(-1);
7249 length = CPP_WRITTEN (pfile) - name_written;
7250 temp = (struct arglist *)
7251 xmalloc (sizeof (struct arglist) + length + 1);
7252 temp->name = (U_CHAR *) (temp + 1);
7253 bcopy ((char *) (pfile->token_buffer + name_written),
7254 (char *) temp->name, length);
7255 temp->name[length] = 0;
7256 temp->next = token_ptrs;
7257 token_ptrs = temp;
7258 temp->length = length;
7260 CPP_ADJUST_WRITTEN (pfile, -length); /* pop */
7262 if (c == EOF || c == '\n')
7263 { /* FIXME */
7264 cpp_error (pfile,
7265 "unterminated token sequence following `#' operator");
7266 return 0;
7270 /* We accumulated the names in reverse order.
7271 Now reverse them to get the proper order. */
7272 return reverse_token_list (token_ptrs);
7275 static void
7276 free_token_list (tokens)
7277 struct arglist *tokens;
7279 while (tokens) {
7280 struct arglist *next = tokens->next;
7281 free (tokens->name);
7282 free (tokens);
7283 tokens = next;
7287 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7288 retrying if necessary. If MAX_READ_LEN is defined, read at most
7289 that bytes at a time. Return a negative value if an error occurs,
7290 otherwise return the actual number of bytes read,
7291 which must be LEN unless end-of-file was reached. */
7293 static int
7294 safe_read (desc, ptr, len)
7295 int desc;
7296 char *ptr;
7297 int len;
7299 int left, rcount, nchars;
7301 left = len;
7302 while (left > 0) {
7303 rcount = left;
7304 #ifdef MAX_READ_LEN
7305 if (rcount > MAX_READ_LEN)
7306 rcount = MAX_READ_LEN;
7307 #endif
7308 nchars = read (desc, ptr, rcount);
7309 if (nchars < 0)
7311 #ifdef EINTR
7312 if (errno == EINTR)
7313 continue;
7314 #endif
7315 return nchars;
7317 if (nchars == 0)
7318 break;
7319 ptr += nchars;
7320 left -= nchars;
7322 return len - left;
7325 static char *
7326 xcalloc (number, size)
7327 unsigned number, size;
7329 register unsigned total = number * size;
7330 register char *ptr = (char *) xmalloc (total);
7331 bzero (ptr, total);
7332 return ptr;
7335 static char *
7336 savestring (input)
7337 char *input;
7339 unsigned size = strlen (input);
7340 char *output = xmalloc (size + 1);
7341 strcpy (output, input);
7342 return output;
7345 /* Initialize PMARK to remember the current position of PFILE. */
7347 void
7348 parse_set_mark (pmark, pfile)
7349 struct parse_marker *pmark;
7350 cpp_reader *pfile;
7352 cpp_buffer *pbuf = CPP_BUFFER (pfile);
7353 pmark->next = pbuf->marks;
7354 pbuf->marks = pmark;
7355 pmark->buf = pbuf;
7356 pmark->position = pbuf->cur - pbuf->buf;
7359 /* Cleanup PMARK - we no longer need it. */
7361 void
7362 parse_clear_mark (pmark)
7363 struct parse_marker *pmark;
7365 struct parse_marker **pp = &pmark->buf->marks;
7366 for (; ; pp = &(*pp)->next) {
7367 if (*pp == NULL) abort ();
7368 if (*pp == pmark) break;
7370 *pp = pmark->next;
7373 /* Backup the current position of PFILE to that saved in PMARK. */
7375 void
7376 parse_goto_mark (pmark, pfile)
7377 struct parse_marker *pmark;
7378 cpp_reader *pfile;
7380 cpp_buffer *pbuf = CPP_BUFFER (pfile);
7381 if (pbuf != pmark->buf)
7382 cpp_fatal (pfile, "internal error %s", "parse_goto_mark");
7383 pbuf->cur = pbuf->buf + pmark->position;
7386 /* Reset PMARK to point to the current position of PFILE. (Same
7387 as parse_clear_mark (PMARK), parse_set_mark (PMARK, PFILE) but faster. */
7389 void
7390 parse_move_mark (pmark, pfile)
7391 struct parse_marker *pmark;
7392 cpp_reader *pfile;
7394 cpp_buffer *pbuf = CPP_BUFFER (pfile);
7395 if (pbuf != pmark->buf)
7396 cpp_fatal (pfile, "internal error %s", "parse_move_mark");
7397 pmark->position = pbuf->cur - pbuf->buf;
7401 cpp_read_check_assertion (pfile)
7402 cpp_reader *pfile;
7404 int name_start = CPP_WRITTEN (pfile);
7405 int name_length, name_written;
7406 int result;
7407 FORWARD (1); /* Skip '#' */
7408 cpp_skip_hspace (pfile);
7409 parse_name (pfile, GETC ());
7410 name_written = CPP_WRITTEN (pfile);
7411 name_length = name_written - name_start;
7412 cpp_skip_hspace (pfile);
7413 if (CPP_BUF_PEEK (CPP_BUFFER (pfile)) == '(')
7415 int error_flag;
7416 struct arglist *token_ptrs = read_token_list (pfile, &error_flag);
7417 result = check_assertion (pfile,
7418 pfile->token_buffer + name_start, name_length,
7419 1, token_ptrs);
7421 else
7422 result = check_assertion (pfile,
7423 pfile->token_buffer + name_start, name_length,
7424 0, NULL_PTR);
7425 CPP_ADJUST_WRITTEN (pfile, - name_length); /* pop */
7426 return result;
7429 void
7430 cpp_print_file_and_line (pfile)
7431 cpp_reader *pfile;
7433 cpp_buffer *ip = cpp_file_buffer (pfile);
7435 if (ip != NULL)
7437 long line, col;
7438 cpp_buf_line_and_col (ip, &line, &col);
7439 cpp_file_line_for_message (pfile, ip->nominal_fname,
7440 line, pfile->show_column ? col : -1);
7444 static void
7445 v_cpp_error (pfile, msg, ap)
7446 cpp_reader *pfile;
7447 const char *msg;
7448 va_list ap;
7450 cpp_print_containing_files (pfile);
7451 cpp_print_file_and_line (pfile);
7452 v_cpp_message (pfile, 1, msg, ap);
7455 void
7456 cpp_error VPROTO ((cpp_reader * pfile, const char *msg, ...))
7458 #ifndef __STDC__
7459 cpp_reader *pfile;
7460 const char *msg;
7461 #endif
7462 va_list ap;
7464 VA_START(ap, msg);
7466 #ifndef __STDC__
7467 pfile = va_arg (ap, cpp_reader *);
7468 msg = va_arg (ap, const char *);
7469 #endif
7471 v_cpp_error (pfile, msg, ap);
7472 va_end(ap);
7475 /* Print error message but don't count it. */
7477 static void
7478 v_cpp_warning (pfile, msg, ap)
7479 cpp_reader *pfile;
7480 const char *msg;
7481 va_list ap;
7483 if (CPP_OPTIONS (pfile)->inhibit_warnings)
7484 return;
7486 if (CPP_OPTIONS (pfile)->warnings_are_errors)
7487 pfile->errors++;
7489 cpp_print_containing_files (pfile);
7490 cpp_print_file_and_line (pfile);
7491 v_cpp_message (pfile, 0, msg, ap);
7494 void
7495 cpp_warning VPROTO ((cpp_reader * pfile, const char *msg, ...))
7497 #ifndef __STDC__
7498 cpp_reader *pfile;
7499 const char *msg;
7500 #endif
7501 va_list ap;
7503 VA_START (ap, msg);
7505 #ifndef __STDC__
7506 pfile = va_arg (ap, cpp_reader *);
7507 msg = va_arg (ap, const char *);
7508 #endif
7510 v_cpp_warning (pfile, msg, ap);
7511 va_end(ap);
7514 /* Print an error message and maybe count it. */
7516 void
7517 cpp_pedwarn VPROTO ((cpp_reader * pfile, const char *msg, ...))
7519 #ifndef __STDC__
7520 cpp_reader *pfile;
7521 const char *msg;
7522 #endif
7523 va_list ap;
7525 VA_START (ap, msg);
7527 #ifndef __STDC__
7528 pfile = va_arg (ap, cpp_reader *);
7529 msg = va_arg (ap, const char *);
7530 #endif
7532 if (CPP_OPTIONS (pfile)->pedantic_errors)
7533 v_cpp_error (pfile, msg, ap);
7534 else
7535 v_cpp_warning (pfile, msg, ap);
7536 va_end(ap);
7539 static void
7540 v_cpp_error_with_line (pfile, line, column, msg, ap)
7541 cpp_reader * pfile;
7542 int line;
7543 int column;
7544 const char * msg;
7545 va_list ap;
7547 cpp_buffer *ip = cpp_file_buffer (pfile);
7549 cpp_print_containing_files (pfile);
7551 if (ip != NULL)
7552 cpp_file_line_for_message (pfile, ip->nominal_fname, line, column);
7554 v_cpp_message (pfile, 1, msg, ap);
7557 void
7558 cpp_error_with_line VPROTO ((cpp_reader * pfile, int line, int column, const char *msg, ...))
7560 #ifndef __STDC__
7561 cpp_reader *pfile;
7562 int line;
7563 int column;
7564 const char *msg;
7565 #endif
7566 va_list ap;
7568 VA_START (ap, msg);
7570 #ifndef __STDC__
7571 pfile = va_arg (ap, cpp_reader *);
7572 line = va_arg (ap, int);
7573 column = va_arg (ap, int);
7574 msg = va_arg (ap, const char *);
7575 #endif
7577 v_cpp_error_with_line(pfile, line, column, msg, ap);
7578 va_end(ap);
7581 static void
7582 v_cpp_warning_with_line (pfile, line, column, msg, ap)
7583 cpp_reader * pfile;
7584 int line;
7585 int column;
7586 const char *msg;
7587 va_list ap;
7589 cpp_buffer *ip;
7591 if (CPP_OPTIONS (pfile)->inhibit_warnings)
7592 return;
7594 if (CPP_OPTIONS (pfile)->warnings_are_errors)
7595 pfile->errors++;
7597 cpp_print_containing_files (pfile);
7599 ip = cpp_file_buffer (pfile);
7601 if (ip != NULL)
7602 cpp_file_line_for_message (pfile, ip->nominal_fname, line, column);
7604 v_cpp_message (pfile, 0, msg, ap);
7607 #if 0
7608 static void
7609 cpp_warning_with_line VPROTO ((cpp_reader * pfile, int line, int column, const char *msg, ...))
7611 #ifndef __STDC__
7612 cpp_reader *pfile;
7613 int line;
7614 int column;
7615 const char *msg;
7616 #endif
7617 va_list ap;
7619 VA_START (ap, msg);
7621 #ifndef __STDC__
7622 pfile = va_arg (ap, cpp_reader *);
7623 line = va_arg (ap, int);
7624 column = va_arg (ap, int);
7625 msg = va_arg (ap, const char *);
7626 #endif
7628 v_cpp_warning_with_line (pfile, line, column, msg, ap);
7629 va_end(ap);
7631 #endif
7633 void
7634 cpp_pedwarn_with_line VPROTO ((cpp_reader * pfile, int line, int column, const char *msg, ...))
7636 #ifndef __STDC__
7637 cpp_reader *pfile;
7638 int line;
7639 int column;
7640 const char *msg;
7641 #endif
7642 va_list ap;
7644 VA_START (ap, msg);
7646 #ifndef __STDC__
7647 pfile = va_arg (ap, cpp_reader *);
7648 line = va_arg (ap, int);
7649 column = va_arg (ap, int);
7650 msg = va_arg (ap, const char *);
7651 #endif
7653 if (CPP_OPTIONS (pfile)->pedantic_errors)
7654 v_cpp_error_with_line (pfile, column, line, msg, ap);
7655 else
7656 v_cpp_warning_with_line (pfile, line, column, msg, ap);
7657 va_end(ap);
7660 /* Report a warning (or an error if pedantic_errors)
7661 giving specified file name and line number, not current. */
7663 void
7664 cpp_pedwarn_with_file_and_line VPROTO ((cpp_reader *pfile, char *file, int line, const char *msg, ...))
7666 #ifndef __STDC__
7667 cpp_reader *pfile;
7668 char *file;
7669 int line;
7670 const char *msg;
7671 #endif
7672 va_list ap;
7674 VA_START (ap, msg);
7676 #ifndef __STDC__
7677 pfile = va_arg (ap, cpp_reader *);
7678 file = va_arg (ap, char *);
7679 line = va_arg (ap, int);
7680 msg = va_arg (ap, const char *);
7681 #endif
7683 if (!CPP_OPTIONS (pfile)->pedantic_errors
7684 && CPP_OPTIONS (pfile)->inhibit_warnings)
7685 return;
7686 if (file != NULL)
7687 cpp_file_line_for_message (pfile, file, line, -1);
7688 v_cpp_message (pfile, CPP_OPTIONS (pfile)->pedantic_errors, msg, ap);
7689 va_end(ap);
7692 /* my_strerror - return the descriptive text associated with an
7693 `errno' code. */
7695 static char *
7696 my_strerror (errnum)
7697 int errnum;
7699 char *result;
7701 #ifndef VMS
7702 #ifndef HAVE_STRERROR
7703 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
7704 #else
7705 result = strerror (errnum);
7706 #endif
7707 #else /* VMS */
7708 /* VAXCRTL's strerror() takes an optional second argument, which only
7709 matters when the first argument is EVMSERR. However, it's simplest
7710 just to pass it unconditionally. `vaxc$errno' is declared in
7711 <errno.h>, and maintained by the library in parallel with `errno'.
7712 We assume that caller's `errnum' either matches the last setting of
7713 `errno' by the library or else does not have the value `EVMSERR'. */
7715 result = strerror (errnum, vaxc$errno);
7716 #endif
7718 if (!result)
7719 result = "undocumented I/O error";
7721 return result;
7724 /* Error including a message from `errno'. */
7726 void
7727 cpp_error_from_errno (pfile, name)
7728 cpp_reader *pfile;
7729 const char *name;
7731 cpp_message_from_errno (pfile, 1, name);
7734 void
7735 cpp_message_from_errno (pfile, is_error, name)
7736 cpp_reader *pfile;
7737 int is_error;
7738 const char *name;
7740 int e = errno;
7741 cpp_buffer *ip = cpp_file_buffer (pfile);
7743 cpp_print_containing_files (pfile);
7745 if (ip != NULL)
7746 cpp_file_line_for_message (pfile, ip->nominal_fname, ip->lineno, -1);
7748 cpp_message (pfile, is_error, "%s: %s", name, my_strerror (e));
7751 void
7752 cpp_perror_with_name (pfile, name)
7753 cpp_reader *pfile;
7754 const char *name;
7756 cpp_message (pfile, 1, "%s: %s: %s", progname, name, my_strerror (errno));
7759 /* TODO:
7760 * No pre-compiled header file support.
7762 * Possibly different enum token codes for each C/C++ token.
7764 * Should clean up remaining directives to that do_XXX functions
7765 * only take two arguments and all have command_reads_line.
7767 * Find and cleanup remaining uses of static variables,
7769 * Support for trigraphs.
7771 * Support -dM flag (dump_all_macros).
7773 * Support for_lint flag.